Sema.cpp revision 9cf9f868a5a39099d6a9cf57d5d5693c30486d8d
1//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the actions class which performs semantic analysis and
11// builds an AST out of a parse stream.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "llvm/ADT/DenseMap.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/Expr.h"
21#include "clang/Lex/Preprocessor.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "clang/Basic/TargetInfo.h"
24using namespace clang;
25
26/// Determines whether we should have an a.k.a. clause when
27/// pretty-printing a type.  There are two main criteria:
28///
29/// 1) Some types provide very minimal sugar that doesn't impede the
30///    user's understanding --- for example, elaborated type
31///    specifiers.  If this is all the sugar we see, we don't want an
32///    a.k.a. clause.
33/// 2) Some types are technically sugared but are much more familiar
34///    when seen in their sugared form --- for example, va_list,
35///    vector types, and the magic Objective C types.  We don't
36///    want to desugar these, even if we do produce an a.k.a. clause.
37static bool ShouldAKA(ASTContext &Context, QualType QT,
38                      QualType& DesugaredQT) {
39
40  bool AKA = false;
41  QualifierCollector Qc;
42
43  while (true) {
44    const Type *Ty = Qc.strip(QT);
45
46    // Don't aka just because we saw an elaborated type...
47    if (isa<ElaboratedType>(Ty)) {
48      QT = cast<ElaboratedType>(Ty)->desugar();
49      continue;
50    }
51
52    // ...or a qualified name type...
53    if (isa<QualifiedNameType>(Ty)) {
54      QT = cast<QualifiedNameType>(Ty)->desugar();
55      continue;
56    }
57
58    // ...or a substituted template type parameter.
59    if (isa<SubstTemplateTypeParmType>(Ty)) {
60      QT = cast<SubstTemplateTypeParmType>(Ty)->desugar();
61      continue;
62    }
63
64    // Don't desugar template specializations.
65    if (isa<TemplateSpecializationType>(Ty))
66      break;
67
68    // Don't desugar magic Objective-C types.
69    if (QualType(Ty,0) == Context.getObjCIdType() ||
70        QualType(Ty,0) == Context.getObjCClassType() ||
71        QualType(Ty,0) == Context.getObjCSelType() ||
72        QualType(Ty,0) == Context.getObjCProtoType())
73      break;
74
75    // Don't desugar va_list.
76    if (QualType(Ty,0) == Context.getBuiltinVaListType())
77      break;
78
79    // Otherwise, do a single-step desugar.
80    QualType Underlying;
81    bool IsSugar = false;
82    switch (Ty->getTypeClass()) {
83#define ABSTRACT_TYPE(Class, Base)
84#define TYPE(Class, Base) \
85    case Type::Class: { \
86      const Class##Type *CTy = cast<Class##Type>(Ty); \
87      if (CTy->isSugared()) { \
88        IsSugar = true; \
89        Underlying = CTy->desugar(); \
90      } \
91      break; \
92    }
93#include "clang/AST/TypeNodes.def"
94    }
95
96    // If it wasn't sugared, we're done.
97    if (!IsSugar)
98      break;
99
100    // If the desugared type is a vector type, we don't want to expand
101    // it, it will turn into an attribute mess. People want their "vec4".
102    if (isa<VectorType>(Underlying))
103      break;
104
105    // Otherwise, we're tearing through something opaque; note that
106    // we'll eventually need an a.k.a. clause and keep going.
107    AKA = true;
108    QT = Underlying;
109    continue;
110  }
111
112  // If we ever tore through opaque sugar
113  if (AKA) {
114    DesugaredQT = Qc.apply(QT);
115    return true;
116  }
117
118  return false;
119}
120
121/// \brief Convert the given type to a string suitable for printing as part of
122/// a diagnostic.
123///
124/// \param Context the context in which the type was allocated
125/// \param Ty the type to print
126static std::string ConvertTypeToDiagnosticString(ASTContext &Context,
127                                                 QualType Ty) {
128  // FIXME: Playing with std::string is really slow.
129  std::string S = Ty.getAsString(Context.PrintingPolicy);
130
131  // Consider producing an a.k.a. clause if removing all the direct
132  // sugar gives us something "significantly different".
133
134  QualType DesugaredTy;
135  if (ShouldAKA(Context, Ty, DesugaredTy)) {
136    S = "'"+S+"' (aka '";
137    S += DesugaredTy.getAsString(Context.PrintingPolicy);
138    S += "')";
139    return S;
140  }
141
142  S = "'" + S + "'";
143  return S;
144}
145
146/// ConvertQualTypeToStringFn - This function is used to pretty print the
147/// specified QualType as a string in diagnostics.
148static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val,
149                                 const char *Modifier, unsigned ModLen,
150                                 const char *Argument, unsigned ArgLen,
151                                 llvm::SmallVectorImpl<char> &Output,
152                                 void *Cookie) {
153  ASTContext &Context = *static_cast<ASTContext*>(Cookie);
154
155  std::string S;
156  bool NeedQuotes = true;
157
158  switch (Kind) {
159  default: assert(0 && "unknown ArgumentKind");
160  case Diagnostic::ak_qualtype: {
161    assert(ModLen == 0 && ArgLen == 0 &&
162           "Invalid modifier for QualType argument");
163
164    QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
165    S = ConvertTypeToDiagnosticString(Context, Ty);
166    NeedQuotes = false;
167    break;
168  }
169  case Diagnostic::ak_declarationname: {
170    DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
171    S = N.getAsString();
172
173    if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
174      S = '+' + S;
175    else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0)
176      S = '-' + S;
177    else
178      assert(ModLen == 0 && ArgLen == 0 &&
179             "Invalid modifier for DeclarationName argument");
180    break;
181  }
182  case Diagnostic::ak_nameddecl: {
183    bool Qualified;
184    if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0)
185      Qualified = true;
186    else {
187      assert(ModLen == 0 && ArgLen == 0 &&
188           "Invalid modifier for NamedDecl* argument");
189      Qualified = false;
190    }
191    reinterpret_cast<NamedDecl*>(Val)->
192      getNameForDiagnostic(S, Context.PrintingPolicy, Qualified);
193    break;
194  }
195  case Diagnostic::ak_nestednamespec: {
196    llvm::raw_string_ostream OS(S);
197    reinterpret_cast<NestedNameSpecifier*>(Val)->print(OS,
198                                                       Context.PrintingPolicy);
199    NeedQuotes = false;
200    break;
201  }
202  case Diagnostic::ak_declcontext: {
203    DeclContext *DC = reinterpret_cast<DeclContext *> (Val);
204    assert(DC && "Should never have a null declaration context");
205
206    if (DC->isTranslationUnit()) {
207      // FIXME: Get these strings from some localized place
208      if (Context.getLangOptions().CPlusPlus)
209        S = "the global namespace";
210      else
211        S = "the global scope";
212    } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) {
213      S = ConvertTypeToDiagnosticString(Context, Context.getTypeDeclType(Type));
214    } else {
215      // FIXME: Get these strings from some localized place
216      NamedDecl *ND = cast<NamedDecl>(DC);
217      if (isa<NamespaceDecl>(ND))
218        S += "namespace ";
219      else if (isa<ObjCMethodDecl>(ND))
220        S += "method ";
221      else if (isa<FunctionDecl>(ND))
222        S += "function ";
223
224      S += "'";
225      ND->getNameForDiagnostic(S, Context.PrintingPolicy, true);
226      S += "'";
227    }
228    NeedQuotes = false;
229    break;
230  }
231  }
232
233  if (NeedQuotes)
234    Output.push_back('\'');
235
236  Output.append(S.begin(), S.end());
237
238  if (NeedQuotes)
239    Output.push_back('\'');
240}
241
242
243static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) {
244  if (C.getLangOptions().CPlusPlus)
245    return CXXRecordDecl::Create(C, TagDecl::TK_struct,
246                                 C.getTranslationUnitDecl(),
247                                 SourceLocation(), &C.Idents.get(Name));
248
249  return RecordDecl::Create(C, TagDecl::TK_struct,
250                            C.getTranslationUnitDecl(),
251                            SourceLocation(), &C.Idents.get(Name));
252}
253
254void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
255  TUScope = S;
256  PushDeclContext(S, Context.getTranslationUnitDecl());
257
258  if (PP.getTargetInfo().getPointerWidth(0) >= 64) {
259    // Install [u]int128_t for 64-bit targets.
260    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
261                                          SourceLocation(),
262                                          &Context.Idents.get("__int128_t"),
263                                          Context.Int128Ty), TUScope);
264    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
265                                          SourceLocation(),
266                                          &Context.Idents.get("__uint128_t"),
267                                          Context.UnsignedInt128Ty), TUScope);
268  }
269
270
271  if (!PP.getLangOptions().ObjC1) return;
272
273  // Built-in ObjC types may already be set by PCHReader (hence isNull checks).
274  if (Context.getObjCSelType().isNull()) {
275    // Synthesize "typedef struct objc_selector *SEL;"
276    RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector");
277    PushOnScopeChains(SelTag, TUScope);
278
279    QualType SelT = Context.getPointerType(Context.getTagDeclType(SelTag));
280    TypedefDecl *SelTypedef = TypedefDecl::Create(Context, CurContext,
281                                                  SourceLocation(),
282                                                  &Context.Idents.get("SEL"),
283                                                  SelT);
284    PushOnScopeChains(SelTypedef, TUScope);
285    Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
286  }
287
288  // Synthesize "@class Protocol;
289  if (Context.getObjCProtoType().isNull()) {
290    ObjCInterfaceDecl *ProtocolDecl =
291      ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
292                                &Context.Idents.get("Protocol"),
293                                SourceLocation(), true);
294    Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
295    PushOnScopeChains(ProtocolDecl, TUScope);
296  }
297  // Create the built-in typedef for 'id'.
298  if (Context.getObjCIdType().isNull()) {
299    TypedefDecl *IdTypedef =
300      TypedefDecl::Create(
301        Context, CurContext, SourceLocation(), &Context.Idents.get("id"),
302        Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy)
303      );
304    PushOnScopeChains(IdTypedef, TUScope);
305    Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
306    Context.ObjCIdRedefinitionType = Context.getObjCIdType();
307  }
308  // Create the built-in typedef for 'Class'.
309  if (Context.getObjCClassType().isNull()) {
310    TypedefDecl *ClassTypedef =
311      TypedefDecl::Create(
312        Context, CurContext, SourceLocation(), &Context.Idents.get("Class"),
313        Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy)
314      );
315    PushOnScopeChains(ClassTypedef, TUScope);
316    Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
317    Context.ObjCClassRedefinitionType = Context.getObjCClassType();
318  }
319}
320
321Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
322           bool CompleteTranslationUnit)
323  : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
324    Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
325    ExternalSource(0), CodeCompleter(0), CurContext(0),
326    PreDeclaratorDC(0), CurBlock(0), PackContext(0),
327    IdResolver(pp.getLangOptions()), StdNamespace(0), StdBadAlloc(0),
328    GlobalNewDeleteDeclared(false), ExprEvalContext(PotentiallyEvaluated),
329    CompleteTranslationUnit(CompleteTranslationUnit),
330    NumSFINAEErrors(0), CurrentInstantiationScope(0) {
331
332  TUScope = 0;
333  if (getLangOptions().CPlusPlus)
334    FieldCollector.reset(new CXXFieldCollector());
335
336  // Tell diagnostics how to render things from the AST library.
337  PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context);
338}
339
340/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
341/// If there is already an implicit cast, merge into the existing one.
342/// If isLvalue, the result of the cast is an lvalue.
343void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
344                             CastExpr::CastKind Kind, bool isLvalue) {
345  QualType ExprTy = Context.getCanonicalType(Expr->getType());
346  QualType TypeTy = Context.getCanonicalType(Ty);
347
348  if (ExprTy == TypeTy)
349    return;
350
351  if (Expr->getType().getTypePtr()->isPointerType() &&
352      Ty.getTypePtr()->isPointerType()) {
353    QualType ExprBaseType =
354      cast<PointerType>(ExprTy.getUnqualifiedType())->getPointeeType();
355    QualType BaseType =
356      cast<PointerType>(TypeTy.getUnqualifiedType())->getPointeeType();
357    if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
358      Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
359        << Expr->getSourceRange();
360    }
361  }
362
363  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
364    if (ImpCast->getCastKind() == Kind) {
365      ImpCast->setType(Ty);
366      ImpCast->setLvalueCast(isLvalue);
367      return;
368    }
369  }
370
371  Expr = new (Context) ImplicitCastExpr(Ty, Kind, Expr, isLvalue);
372}
373
374void Sema::DeleteExpr(ExprTy *E) {
375  if (E) static_cast<Expr*>(E)->Destroy(Context);
376}
377void Sema::DeleteStmt(StmtTy *S) {
378  if (S) static_cast<Stmt*>(S)->Destroy(Context);
379}
380
381/// ActOnEndOfTranslationUnit - This is called at the very end of the
382/// translation unit when EOF is reached and all but the top-level scope is
383/// popped.
384void Sema::ActOnEndOfTranslationUnit() {
385  // C++: Perform implicit template instantiations.
386  //
387  // FIXME: When we perform these implicit instantiations, we do not carefully
388  // keep track of the point of instantiation (C++ [temp.point]). This means
389  // that name lookup that occurs within the template instantiation will
390  // always happen at the end of the translation unit, so it will find
391  // some names that should not be found. Although this is common behavior
392  // for C++ compilers, it is technically wrong. In the future, we either need
393  // to be able to filter the results of name lookup or we need to perform
394  // template instantiations earlier.
395  PerformPendingImplicitInstantiations();
396
397  // Check for #pragma weak identifiers that were never declared
398  // FIXME: This will cause diagnostics to be emitted in a non-determinstic
399  // order!  Iterating over a densemap like this is bad.
400  for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
401       I = WeakUndeclaredIdentifiers.begin(),
402       E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
403    if (I->second.getUsed()) continue;
404
405    Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
406      << I->first;
407  }
408
409  if (!CompleteTranslationUnit)
410    return;
411
412  // C99 6.9.2p2:
413  //   A declaration of an identifier for an object that has file
414  //   scope without an initializer, and without a storage-class
415  //   specifier or with the storage-class specifier static,
416  //   constitutes a tentative definition. If a translation unit
417  //   contains one or more tentative definitions for an identifier,
418  //   and the translation unit contains no external definition for
419  //   that identifier, then the behavior is exactly as if the
420  //   translation unit contains a file scope declaration of that
421  //   identifier, with the composite type as of the end of the
422  //   translation unit, with an initializer equal to 0.
423  for (unsigned i = 0, e = TentativeDefinitionList.size(); i != e; ++i) {
424    VarDecl *VD = TentativeDefinitions.lookup(TentativeDefinitionList[i]);
425
426    // If the tentative definition was completed, it will be in the list, but
427    // not the map.
428    if (VD == 0 || VD->isInvalidDecl() || !VD->isTentativeDefinition(Context))
429      continue;
430
431    if (const IncompleteArrayType *ArrayT
432        = Context.getAsIncompleteArrayType(VD->getType())) {
433      if (RequireCompleteType(VD->getLocation(),
434                              ArrayT->getElementType(),
435                              diag::err_tentative_def_incomplete_type_arr)) {
436        VD->setInvalidDecl();
437        continue;
438      }
439
440      // Set the length of the array to 1 (C99 6.9.2p5).
441      Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
442      llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
443      QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
444                                                One, ArrayType::Normal, 0);
445      VD->setType(T);
446    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
447                                   diag::err_tentative_def_incomplete_type))
448      VD->setInvalidDecl();
449
450    // Notify the consumer that we've completed a tentative definition.
451    if (!VD->isInvalidDecl())
452      Consumer.CompleteTentativeDefinition(VD);
453
454  }
455}
456
457
458//===----------------------------------------------------------------------===//
459// Helper functions.
460//===----------------------------------------------------------------------===//
461
462DeclContext *Sema::getFunctionLevelDeclContext() {
463  DeclContext *DC = PreDeclaratorDC ? PreDeclaratorDC : CurContext;
464
465  while (isa<BlockDecl>(DC))
466    DC = DC->getParent();
467
468  return DC;
469}
470
471/// getCurFunctionDecl - If inside of a function body, this returns a pointer
472/// to the function decl for the function being parsed.  If we're currently
473/// in a 'block', this returns the containing context.
474FunctionDecl *Sema::getCurFunctionDecl() {
475  DeclContext *DC = getFunctionLevelDeclContext();
476  return dyn_cast<FunctionDecl>(DC);
477}
478
479ObjCMethodDecl *Sema::getCurMethodDecl() {
480  DeclContext *DC = getFunctionLevelDeclContext();
481  return dyn_cast<ObjCMethodDecl>(DC);
482}
483
484NamedDecl *Sema::getCurFunctionOrMethodDecl() {
485  DeclContext *DC = getFunctionLevelDeclContext();
486  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
487    return cast<NamedDecl>(DC);
488  return 0;
489}
490
491Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
492  if (!this->Emit())
493    return;
494
495  // If this is not a note, and we're in a template instantiation
496  // that is different from the last template instantiation where
497  // we emitted an error, print a template instantiation
498  // backtrace.
499  if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
500      !SemaRef.ActiveTemplateInstantiations.empty() &&
501      SemaRef.ActiveTemplateInstantiations.back()
502        != SemaRef.LastTemplateInstantiationErrorContext) {
503    SemaRef.PrintInstantiationStack();
504    SemaRef.LastTemplateInstantiationErrorContext
505      = SemaRef.ActiveTemplateInstantiations.back();
506  }
507}
508
509Sema::SemaDiagnosticBuilder
510Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
511  SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
512  PD.Emit(Builder);
513
514  return Builder;
515}
516
517void Sema::ActOnComment(SourceRange Comment) {
518  Context.Comments.push_back(Comment);
519}
520
521