Sema.cpp revision 3d27b107c515ab1a8fd47b33c41adcf5a65f465b
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 "clang/Sema/Sema.h"
16#include "TargetAttributesSema.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/APFloat.h"
20#include "clang/Sema/ExternalSemaSource.h"
21#include "clang/Sema/SemaConsumer.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/ASTDiagnostic.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/AST/Expr.h"
26#include "clang/Lex/Preprocessor.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/TargetInfo.h"
29using namespace clang;
30
31FunctionScopeInfo::~FunctionScopeInfo() { }
32
33void FunctionScopeInfo::Clear(unsigned NumErrors) {
34  HasBranchProtectedScope = false;
35  HasBranchIntoScope = false;
36  HasIndirectGoto = false;
37
38  LabelMap.clear();
39  SwitchStack.clear();
40  Returns.clear();
41  NumErrorsAtStartOfFunction = NumErrors;
42}
43
44BlockScopeInfo::~BlockScopeInfo() { }
45
46void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
47  TUScope = S;
48  PushDeclContext(S, Context.getTranslationUnitDecl());
49
50  VAListTagName = PP.getIdentifierInfo("__va_list_tag");
51
52  if (!Context.isInt128Installed() && // May be set by PCHReader.
53      PP.getTargetInfo().getPointerWidth(0) >= 64) {
54    TypeSourceInfo *TInfo;
55
56    // Install [u]int128_t for 64-bit targets.
57    TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty);
58    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
59                                          SourceLocation(),
60                                          &Context.Idents.get("__int128_t"),
61                                          TInfo), TUScope);
62
63    TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty);
64    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
65                                          SourceLocation(),
66                                          &Context.Idents.get("__uint128_t"),
67                                          TInfo), TUScope);
68    Context.setInt128Installed();
69  }
70
71
72  if (!PP.getLangOptions().ObjC1) return;
73
74  // Built-in ObjC types may already be set by PCHReader (hence isNull checks).
75  if (Context.getObjCSelType().isNull()) {
76    // Create the built-in typedef for 'SEL'.
77    QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy);
78    TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT);
79    TypedefDecl *SelTypedef
80      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
81                            &Context.Idents.get("SEL"), SelInfo);
82    PushOnScopeChains(SelTypedef, TUScope);
83    Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
84    Context.ObjCSelRedefinitionType = Context.getObjCSelType();
85  }
86
87  // Synthesize "@class Protocol;
88  if (Context.getObjCProtoType().isNull()) {
89    ObjCInterfaceDecl *ProtocolDecl =
90      ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
91                                &Context.Idents.get("Protocol"),
92                                SourceLocation(), true);
93    Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
94    PushOnScopeChains(ProtocolDecl, TUScope, false);
95  }
96  // Create the built-in typedef for 'id'.
97  if (Context.getObjCIdType().isNull()) {
98    QualType T = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 0, 0);
99    T = Context.getObjCObjectPointerType(T);
100    TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(T);
101    TypedefDecl *IdTypedef
102      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
103                            &Context.Idents.get("id"), IdInfo);
104    PushOnScopeChains(IdTypedef, TUScope);
105    Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
106    Context.ObjCIdRedefinitionType = Context.getObjCIdType();
107  }
108  // Create the built-in typedef for 'Class'.
109  if (Context.getObjCClassType().isNull()) {
110    QualType T = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 0, 0);
111    T = Context.getObjCObjectPointerType(T);
112    TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(T);
113    TypedefDecl *ClassTypedef
114      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
115                            &Context.Idents.get("Class"), ClassInfo);
116    PushOnScopeChains(ClassTypedef, TUScope);
117    Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
118    Context.ObjCClassRedefinitionType = Context.getObjCClassType();
119  }
120}
121
122Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
123           bool CompleteTranslationUnit,
124           CodeCompleteConsumer *CodeCompleter)
125  : TheTargetAttributesSema(0),
126    LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
127    Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
128    ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0),
129    PackContext(0), VisContext(0), TopFunctionScope(0), ParsingDeclDepth(0),
130    IdResolver(pp.getLangOptions()), GlobalNewDeleteDeclared(false),
131    CompleteTranslationUnit(CompleteTranslationUnit),
132    NumSFINAEErrors(0), SuppressAccessChecking(false),
133    NonInstantiationEntries(0), CurrentInstantiationScope(0), TyposCorrected(0),
134    AnalysisWarnings(*this)
135{
136  TUScope = 0;
137  if (getLangOptions().CPlusPlus)
138    FieldCollector.reset(new CXXFieldCollector());
139
140  // Tell diagnostics how to render things from the AST library.
141  PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
142                                       &Context);
143
144  ExprEvalContexts.push_back(
145                  ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0));
146}
147
148void Sema::Initialize() {
149  // Tell the AST consumer about this Sema object.
150  Consumer.Initialize(Context);
151
152  // FIXME: Isn't this redundant with the initialization above?
153  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
154    SC->InitializeSema(*this);
155
156  // Tell the external Sema source about this Sema object.
157  if (ExternalSemaSource *ExternalSema
158      = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
159    ExternalSema->InitializeSema(*this);
160}
161
162Sema::~Sema() {
163  if (PackContext) FreePackedContext();
164  if (VisContext) FreeVisContext();
165  delete TheTargetAttributesSema;
166  while (!FunctionScopes.empty())
167    PopFunctionOrBlockScope();
168
169  // Tell the SemaConsumer to forget about us; we're going out of scope.
170  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
171    SC->ForgetSema();
172
173  // Detach from the external Sema source.
174  if (ExternalSemaSource *ExternalSema
175        = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
176    ExternalSema->ForgetSema();
177}
178
179/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
180/// If there is already an implicit cast, merge into the existing one.
181/// The result is of the given category.
182void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
183                             CastExpr::CastKind Kind,
184                             ImplicitCastExpr::ResultCategory Category,
185                             const CXXCastPath *BasePath) {
186  QualType ExprTy = Context.getCanonicalType(Expr->getType());
187  QualType TypeTy = Context.getCanonicalType(Ty);
188
189  if (ExprTy == TypeTy)
190    return;
191
192  if (Expr->getType()->isPointerType() && Ty->isPointerType()) {
193    QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType();
194    QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType();
195    if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
196      Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
197        << Expr->getSourceRange();
198    }
199  }
200
201  // If this is a derived-to-base cast to a through a virtual base, we
202  // need a vtable.
203  if (Kind == CastExpr::CK_DerivedToBase &&
204      BasePathInvolvesVirtualBase(*BasePath)) {
205    QualType T = Expr->getType();
206    if (const PointerType *Pointer = T->getAs<PointerType>())
207      T = Pointer->getPointeeType();
208    if (const RecordType *RecordTy = T->getAs<RecordType>())
209      MarkVTableUsed(Expr->getLocStart(),
210                     cast<CXXRecordDecl>(RecordTy->getDecl()));
211  }
212
213  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
214    if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
215      ImpCast->setType(Ty);
216      ImpCast->setCategory(Category);
217      return;
218    }
219  }
220
221  Expr = ImplicitCastExpr::Create(Context, Ty, Kind, Expr, BasePath, Category);
222}
223
224ImplicitCastExpr::ResultCategory Sema::CastCategory(Expr *E) {
225  Expr::Classification Classification = E->Classify(Context);
226  return Classification.isRValue() ?
227      ImplicitCastExpr::RValue :
228      (Classification.isLValue() ?
229          ImplicitCastExpr::LValue :
230          ImplicitCastExpr::XValue);
231}
232
233void Sema::DeleteExpr(ExprTy *E) {
234}
235void Sema::DeleteStmt(StmtTy *S) {
236}
237
238/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
239static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
240  if (D->isUsed())
241    return true;
242
243  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
244    // UnusedFileScopedDecls stores the first declaration.
245    // The declaration may have become definition so check again.
246    const FunctionDecl *DeclToCheck;
247    if (FD->hasBody(DeclToCheck))
248      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
249
250    // Later redecls may add new information resulting in not having to warn,
251    // so check again.
252    DeclToCheck = FD->getMostRecentDeclaration();
253    if (DeclToCheck != FD)
254      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
255  }
256
257  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
258    // UnusedFileScopedDecls stores the first declaration.
259    // The declaration may have become definition so check again.
260    const VarDecl *DeclToCheck = VD->getDefinition();
261    if (DeclToCheck)
262      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
263
264    // Later redecls may add new information resulting in not having to warn,
265    // so check again.
266    DeclToCheck = VD->getMostRecentDeclaration();
267    if (DeclToCheck != VD)
268      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
269  }
270
271  return false;
272}
273
274/// ActOnEndOfTranslationUnit - This is called at the very end of the
275/// translation unit when EOF is reached and all but the top-level scope is
276/// popped.
277void Sema::ActOnEndOfTranslationUnit() {
278  // At PCH writing, implicit instantiations and VTable handling info are
279  // stored and performed when the PCH is included.
280  if (CompleteTranslationUnit)
281    while (1) {
282      // C++: Perform implicit template instantiations.
283      //
284      // FIXME: When we perform these implicit instantiations, we do not
285      // carefully keep track of the point of instantiation (C++ [temp.point]).
286      // This means that name lookup that occurs within the template
287      // instantiation will always happen at the end of the translation unit,
288      // so it will find some names that should not be found. Although this is
289      // common behavior for C++ compilers, it is technically wrong. In the
290      // future, we either need to be able to filter the results of name lookup
291      // or we need to perform template instantiations earlier.
292      PerformPendingImplicitInstantiations();
293
294      /// If DefinedUsedVTables ends up marking any virtual member
295      /// functions it might lead to more pending template
296      /// instantiations, which is why we need to loop here.
297      if (!DefineUsedVTables())
298        break;
299    }
300
301  // Remove file scoped decls that turned out to be used.
302  UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(),
303                                             UnusedFileScopedDecls.end(),
304                              std::bind1st(std::ptr_fun(ShouldRemoveFromUnused),
305                                           this)),
306                              UnusedFileScopedDecls.end());
307
308  if (!CompleteTranslationUnit) {
309    TUScope = 0;
310    return;
311  }
312
313  // Check for #pragma weak identifiers that were never declared
314  // FIXME: This will cause diagnostics to be emitted in a non-determinstic
315  // order!  Iterating over a densemap like this is bad.
316  for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
317       I = WeakUndeclaredIdentifiers.begin(),
318       E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
319    if (I->second.getUsed()) continue;
320
321    Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
322      << I->first;
323  }
324
325  // C99 6.9.2p2:
326  //   A declaration of an identifier for an object that has file
327  //   scope without an initializer, and without a storage-class
328  //   specifier or with the storage-class specifier static,
329  //   constitutes a tentative definition. If a translation unit
330  //   contains one or more tentative definitions for an identifier,
331  //   and the translation unit contains no external definition for
332  //   that identifier, then the behavior is exactly as if the
333  //   translation unit contains a file scope declaration of that
334  //   identifier, with the composite type as of the end of the
335  //   translation unit, with an initializer equal to 0.
336  llvm::SmallSet<VarDecl *, 32> Seen;
337  for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
338    VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
339
340    // If the tentative definition was completed, getActingDefinition() returns
341    // null. If we've already seen this variable before, insert()'s second
342    // return value is false.
343    if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
344      continue;
345
346    if (const IncompleteArrayType *ArrayT
347        = Context.getAsIncompleteArrayType(VD->getType())) {
348      if (RequireCompleteType(VD->getLocation(),
349                              ArrayT->getElementType(),
350                              diag::err_tentative_def_incomplete_type_arr)) {
351        VD->setInvalidDecl();
352        continue;
353      }
354
355      // Set the length of the array to 1 (C99 6.9.2p5).
356      Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
357      llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
358      QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
359                                                One, ArrayType::Normal, 0);
360      VD->setType(T);
361    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
362                                   diag::err_tentative_def_incomplete_type))
363      VD->setInvalidDecl();
364
365    // Notify the consumer that we've completed a tentative definition.
366    if (!VD->isInvalidDecl())
367      Consumer.CompleteTentativeDefinition(VD);
368
369  }
370
371  // Output warning for unused file scoped decls.
372  for (std::vector<const DeclaratorDecl*>::iterator
373         I = UnusedFileScopedDecls.begin(),
374         E = UnusedFileScopedDecls.end(); I != E; ++I) {
375    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
376      const FunctionDecl *DiagD;
377      if (!FD->hasBody(DiagD))
378        DiagD = FD;
379      Diag(DiagD->getLocation(),
380           isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_method
381                                     : diag::warn_unused_function)
382            << DiagD->getDeclName();
383    } else {
384      const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
385      if (!DiagD)
386        DiagD = cast<VarDecl>(*I);
387      Diag(DiagD->getLocation(), diag::warn_unused_variable)
388            << DiagD->getDeclName();
389    }
390  }
391
392  TUScope = 0;
393}
394
395
396//===----------------------------------------------------------------------===//
397// Helper functions.
398//===----------------------------------------------------------------------===//
399
400DeclContext *Sema::getFunctionLevelDeclContext() {
401  DeclContext *DC = CurContext;
402
403  while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
404    DC = DC->getParent();
405
406  return DC;
407}
408
409/// getCurFunctionDecl - If inside of a function body, this returns a pointer
410/// to the function decl for the function being parsed.  If we're currently
411/// in a 'block', this returns the containing context.
412FunctionDecl *Sema::getCurFunctionDecl() {
413  DeclContext *DC = getFunctionLevelDeclContext();
414  return dyn_cast<FunctionDecl>(DC);
415}
416
417ObjCMethodDecl *Sema::getCurMethodDecl() {
418  DeclContext *DC = getFunctionLevelDeclContext();
419  return dyn_cast<ObjCMethodDecl>(DC);
420}
421
422NamedDecl *Sema::getCurFunctionOrMethodDecl() {
423  DeclContext *DC = getFunctionLevelDeclContext();
424  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
425    return cast<NamedDecl>(DC);
426  return 0;
427}
428
429Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
430  if (!this->Emit())
431    return;
432
433  // If this is not a note, and we're in a template instantiation
434  // that is different from the last template instantiation where
435  // we emitted an error, print a template instantiation
436  // backtrace.
437  if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
438      !SemaRef.ActiveTemplateInstantiations.empty() &&
439      SemaRef.ActiveTemplateInstantiations.back()
440        != SemaRef.LastTemplateInstantiationErrorContext) {
441    SemaRef.PrintInstantiationStack();
442    SemaRef.LastTemplateInstantiationErrorContext
443      = SemaRef.ActiveTemplateInstantiations.back();
444  }
445}
446
447Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
448  if (isSFINAEContext()) {
449    switch (Diagnostic::getDiagnosticSFINAEResponse(DiagID)) {
450    case Diagnostic::SFINAE_Report:
451      // Fall through; we'll report the diagnostic below.
452      break;
453
454    case Diagnostic::SFINAE_SubstitutionFailure:
455      // Count this failure so that we know that template argument deduction
456      // has failed.
457      ++NumSFINAEErrors;
458      // Fall through
459
460    case Diagnostic::SFINAE_Suppress:
461      // Suppress this diagnostic.
462      Diags.setLastDiagnosticIgnored();
463      return SemaDiagnosticBuilder(*this);
464    }
465  }
466
467  DiagnosticBuilder DB = Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
468  return SemaDiagnosticBuilder(DB, *this, DiagID);
469}
470
471Sema::SemaDiagnosticBuilder
472Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
473  SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
474  PD.Emit(Builder);
475
476  return Builder;
477}
478
479/// \brief Determines the active Scope associated with the given declaration
480/// context.
481///
482/// This routine maps a declaration context to the active Scope object that
483/// represents that declaration context in the parser. It is typically used
484/// from "scope-less" code (e.g., template instantiation, lazy creation of
485/// declarations) that injects a name for name-lookup purposes and, therefore,
486/// must update the Scope.
487///
488/// \returns The scope corresponding to the given declaraion context, or NULL
489/// if no such scope is open.
490Scope *Sema::getScopeForContext(DeclContext *Ctx) {
491
492  if (!Ctx)
493    return 0;
494
495  Ctx = Ctx->getPrimaryContext();
496  for (Scope *S = getCurScope(); S; S = S->getParent()) {
497    // Ignore scopes that cannot have declarations. This is important for
498    // out-of-line definitions of static class members.
499    if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
500      if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
501        if (Ctx == Entity->getPrimaryContext())
502          return S;
503  }
504
505  return 0;
506}
507
508/// \brief Enter a new function scope
509void Sema::PushFunctionScope() {
510  if (FunctionScopes.empty()) {
511    // Use the "top" function scope rather than having to allocate memory for
512    // a new scope.
513    TopFunctionScope.Clear(getDiagnostics().getNumErrors());
514    FunctionScopes.push_back(&TopFunctionScope);
515    return;
516  }
517
518  FunctionScopes.push_back(
519                      new FunctionScopeInfo(getDiagnostics().getNumErrors()));
520}
521
522void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
523  FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics().getNumErrors(),
524                                              BlockScope, Block));
525}
526
527void Sema::PopFunctionOrBlockScope() {
528  if (FunctionScopes.back() != &TopFunctionScope)
529    delete FunctionScopes.back();
530  else
531    TopFunctionScope.Clear(getDiagnostics().getNumErrors());
532
533  FunctionScopes.pop_back();
534}
535
536/// \brief Determine whether any errors occurred within this function/method/
537/// block.
538bool Sema::hasAnyErrorsInThisFunction() const {
539  unsigned NumErrors = TopFunctionScope.NumErrorsAtStartOfFunction;
540  if (!FunctionScopes.empty())
541    NumErrors = FunctionScopes.back()->NumErrorsAtStartOfFunction;
542  return NumErrors != getDiagnostics().getNumErrors();
543}
544
545BlockScopeInfo *Sema::getCurBlock() {
546  if (FunctionScopes.empty())
547    return 0;
548
549  return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
550}
551
552// Pin this vtable to this file.
553ExternalSemaSource::~ExternalSemaSource() {}
554