Sema.cpp revision e783d000b13283ca45fbf56e735404e86c9e990d
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  // Tell the AST consumer about this Sema object.
148  Consumer.Initialize(Context);
149
150  // FIXME: Isn't this redundant with the initialization above?
151  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
152    SC->InitializeSema(*this);
153
154  // Tell the external Sema source about this Sema object.
155  if (ExternalSemaSource *ExternalSema
156        = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
157    ExternalSema->InitializeSema(*this);
158}
159
160Sema::~Sema() {
161  if (PackContext) FreePackedContext();
162  if (VisContext) FreeVisContext();
163  delete TheTargetAttributesSema;
164  while (!FunctionScopes.empty())
165    PopFunctionOrBlockScope();
166
167  // Tell the SemaConsumer to forget about us; we're going out of scope.
168  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
169    SC->ForgetSema();
170
171  // Detach from the external Sema source.
172  if (ExternalSemaSource *ExternalSema
173      = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
174    ExternalSema->ForgetSema();
175}
176
177/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
178/// If there is already an implicit cast, merge into the existing one.
179/// The result is of the given category.
180void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
181                             CastExpr::CastKind Kind,
182                             ImplicitCastExpr::ResultCategory Category,
183                             const CXXCastPath *BasePath) {
184  QualType ExprTy = Context.getCanonicalType(Expr->getType());
185  QualType TypeTy = Context.getCanonicalType(Ty);
186
187  if (ExprTy == TypeTy)
188    return;
189
190  if (Expr->getType()->isPointerType() && Ty->isPointerType()) {
191    QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType();
192    QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType();
193    if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
194      Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
195        << Expr->getSourceRange();
196    }
197  }
198
199  // If this is a derived-to-base cast to a through a virtual base, we
200  // need a vtable.
201  if (Kind == CastExpr::CK_DerivedToBase &&
202      BasePathInvolvesVirtualBase(*BasePath)) {
203    QualType T = Expr->getType();
204    if (const PointerType *Pointer = T->getAs<PointerType>())
205      T = Pointer->getPointeeType();
206    if (const RecordType *RecordTy = T->getAs<RecordType>())
207      MarkVTableUsed(Expr->getLocStart(),
208                     cast<CXXRecordDecl>(RecordTy->getDecl()));
209  }
210
211  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
212    if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
213      ImpCast->setType(Ty);
214      ImpCast->setCategory(Category);
215      return;
216    }
217  }
218
219  Expr = ImplicitCastExpr::Create(Context, Ty, Kind, Expr, BasePath, Category);
220}
221
222ImplicitCastExpr::ResultCategory Sema::CastCategory(Expr *E) {
223  Expr::Classification Classification = E->Classify(Context);
224  return Classification.isRValue() ?
225      ImplicitCastExpr::RValue :
226      (Classification.isLValue() ?
227          ImplicitCastExpr::LValue :
228          ImplicitCastExpr::XValue);
229}
230
231void Sema::DeleteExpr(ExprTy *E) {
232}
233void Sema::DeleteStmt(StmtTy *S) {
234}
235
236/// ActOnEndOfTranslationUnit - This is called at the very end of the
237/// translation unit when EOF is reached and all but the top-level scope is
238/// popped.
239void Sema::ActOnEndOfTranslationUnit() {
240  // At PCH writing, implicit instantiations and VTable handling info are
241  // stored and performed when the PCH is included.
242  if (CompleteTranslationUnit)
243    while (1) {
244      // C++: Perform implicit template instantiations.
245      //
246      // FIXME: When we perform these implicit instantiations, we do not
247      // carefully keep track of the point of instantiation (C++ [temp.point]).
248      // This means that name lookup that occurs within the template
249      // instantiation will always happen at the end of the translation unit,
250      // so it will find some names that should not be found. Although this is
251      // common behavior for C++ compilers, it is technically wrong. In the
252      // future, we either need to be able to filter the results of name lookup
253      // or we need to perform template instantiations earlier.
254      PerformPendingImplicitInstantiations();
255
256      /// If DefinedUsedVTables ends up marking any virtual member
257      /// functions it might lead to more pending template
258      /// instantiations, which is why we need to loop here.
259      if (!DefineUsedVTables())
260        break;
261    }
262
263  // Remove functions that turned out to be used.
264  UnusedStaticFuncs.erase(std::remove_if(UnusedStaticFuncs.begin(),
265                                         UnusedStaticFuncs.end(),
266                             std::bind2nd(std::mem_fun(&FunctionDecl::isUsed),
267                                          true)),
268                          UnusedStaticFuncs.end());
269
270  if (!CompleteTranslationUnit)
271    return;
272
273  // Check for #pragma weak identifiers that were never declared
274  // FIXME: This will cause diagnostics to be emitted in a non-determinstic
275  // order!  Iterating over a densemap like this is bad.
276  for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
277       I = WeakUndeclaredIdentifiers.begin(),
278       E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
279    if (I->second.getUsed()) continue;
280
281    Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
282      << I->first;
283  }
284
285  // C99 6.9.2p2:
286  //   A declaration of an identifier for an object that has file
287  //   scope without an initializer, and without a storage-class
288  //   specifier or with the storage-class specifier static,
289  //   constitutes a tentative definition. If a translation unit
290  //   contains one or more tentative definitions for an identifier,
291  //   and the translation unit contains no external definition for
292  //   that identifier, then the behavior is exactly as if the
293  //   translation unit contains a file scope declaration of that
294  //   identifier, with the composite type as of the end of the
295  //   translation unit, with an initializer equal to 0.
296  llvm::SmallSet<VarDecl *, 32> Seen;
297  for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
298    VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
299
300    // If the tentative definition was completed, getActingDefinition() returns
301    // null. If we've already seen this variable before, insert()'s second
302    // return value is false.
303    if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
304      continue;
305
306    if (const IncompleteArrayType *ArrayT
307        = Context.getAsIncompleteArrayType(VD->getType())) {
308      if (RequireCompleteType(VD->getLocation(),
309                              ArrayT->getElementType(),
310                              diag::err_tentative_def_incomplete_type_arr)) {
311        VD->setInvalidDecl();
312        continue;
313      }
314
315      // Set the length of the array to 1 (C99 6.9.2p5).
316      Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
317      llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
318      QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
319                                                One, ArrayType::Normal, 0);
320      VD->setType(T);
321    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
322                                   diag::err_tentative_def_incomplete_type))
323      VD->setInvalidDecl();
324
325    // Notify the consumer that we've completed a tentative definition.
326    if (!VD->isInvalidDecl())
327      Consumer.CompleteTentativeDefinition(VD);
328
329  }
330
331  // Output warning for unused functions.
332  for (std::vector<FunctionDecl*>::iterator
333       F = UnusedStaticFuncs.begin(),
334       FEnd = UnusedStaticFuncs.end();
335       F != FEnd;
336       ++F)
337    Diag((*F)->getLocation(), diag::warn_unused_function) << (*F)->getDeclName();
338
339}
340
341
342//===----------------------------------------------------------------------===//
343// Helper functions.
344//===----------------------------------------------------------------------===//
345
346DeclContext *Sema::getFunctionLevelDeclContext() {
347  DeclContext *DC = CurContext;
348
349  while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
350    DC = DC->getParent();
351
352  return DC;
353}
354
355/// getCurFunctionDecl - If inside of a function body, this returns a pointer
356/// to the function decl for the function being parsed.  If we're currently
357/// in a 'block', this returns the containing context.
358FunctionDecl *Sema::getCurFunctionDecl() {
359  DeclContext *DC = getFunctionLevelDeclContext();
360  return dyn_cast<FunctionDecl>(DC);
361}
362
363ObjCMethodDecl *Sema::getCurMethodDecl() {
364  DeclContext *DC = getFunctionLevelDeclContext();
365  return dyn_cast<ObjCMethodDecl>(DC);
366}
367
368NamedDecl *Sema::getCurFunctionOrMethodDecl() {
369  DeclContext *DC = getFunctionLevelDeclContext();
370  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
371    return cast<NamedDecl>(DC);
372  return 0;
373}
374
375Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
376  if (!this->Emit())
377    return;
378
379  // If this is not a note, and we're in a template instantiation
380  // that is different from the last template instantiation where
381  // we emitted an error, print a template instantiation
382  // backtrace.
383  if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
384      !SemaRef.ActiveTemplateInstantiations.empty() &&
385      SemaRef.ActiveTemplateInstantiations.back()
386        != SemaRef.LastTemplateInstantiationErrorContext) {
387    SemaRef.PrintInstantiationStack();
388    SemaRef.LastTemplateInstantiationErrorContext
389      = SemaRef.ActiveTemplateInstantiations.back();
390  }
391}
392
393Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
394  if (isSFINAEContext()) {
395    switch (Diagnostic::getDiagnosticSFINAEResponse(DiagID)) {
396    case Diagnostic::SFINAE_Report:
397      // Fall through; we'll report the diagnostic below.
398      break;
399
400    case Diagnostic::SFINAE_SubstitutionFailure:
401      // Count this failure so that we know that template argument deduction
402      // has failed.
403      ++NumSFINAEErrors;
404      // Fall through
405
406    case Diagnostic::SFINAE_Suppress:
407      // Suppress this diagnostic.
408      Diags.setLastDiagnosticIgnored();
409      return SemaDiagnosticBuilder(*this);
410    }
411  }
412
413  DiagnosticBuilder DB = Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
414  return SemaDiagnosticBuilder(DB, *this, DiagID);
415}
416
417Sema::SemaDiagnosticBuilder
418Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
419  SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
420  PD.Emit(Builder);
421
422  return Builder;
423}
424
425/// \brief Determines the active Scope associated with the given declaration
426/// context.
427///
428/// This routine maps a declaration context to the active Scope object that
429/// represents that declaration context in the parser. It is typically used
430/// from "scope-less" code (e.g., template instantiation, lazy creation of
431/// declarations) that injects a name for name-lookup purposes and, therefore,
432/// must update the Scope.
433///
434/// \returns The scope corresponding to the given declaraion context, or NULL
435/// if no such scope is open.
436Scope *Sema::getScopeForContext(DeclContext *Ctx) {
437
438  if (!Ctx)
439    return 0;
440
441  Ctx = Ctx->getPrimaryContext();
442  for (Scope *S = getCurScope(); S; S = S->getParent()) {
443    // Ignore scopes that cannot have declarations. This is important for
444    // out-of-line definitions of static class members.
445    if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
446      if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
447        if (Ctx == Entity->getPrimaryContext())
448          return S;
449  }
450
451  return 0;
452}
453
454/// \brief Enter a new function scope
455void Sema::PushFunctionScope() {
456  if (FunctionScopes.empty()) {
457    // Use the "top" function scope rather than having to allocate memory for
458    // a new scope.
459    TopFunctionScope.Clear(getDiagnostics().getNumErrors());
460    FunctionScopes.push_back(&TopFunctionScope);
461    return;
462  }
463
464  FunctionScopes.push_back(
465                      new FunctionScopeInfo(getDiagnostics().getNumErrors()));
466}
467
468void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
469  FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics().getNumErrors(),
470                                              BlockScope, Block));
471}
472
473void Sema::PopFunctionOrBlockScope() {
474  if (FunctionScopes.back() != &TopFunctionScope)
475    delete FunctionScopes.back();
476  else
477    TopFunctionScope.Clear(getDiagnostics().getNumErrors());
478
479  FunctionScopes.pop_back();
480}
481
482/// \brief Determine whether any errors occurred within this function/method/
483/// block.
484bool Sema::hasAnyErrorsInThisFunction() const {
485  unsigned NumErrors = TopFunctionScope.NumErrorsAtStartOfFunction;
486  if (!FunctionScopes.empty())
487    NumErrors = FunctionScopes.back()->NumErrorsAtStartOfFunction;
488  return NumErrors != getDiagnostics().getNumErrors();
489}
490
491BlockScopeInfo *Sema::getCurBlock() {
492  if (FunctionScopes.empty())
493    return 0;
494
495  return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
496}
497
498// Pin this vtable to this file.
499ExternalSemaSource::~ExternalSemaSource() {}
500