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