Sema.cpp revision c7e04dad588a30c94648b9bd70cdbe25688d7629
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 "TargetAttributesSema.h" 17#include "llvm/ADT/DenseMap.h" 18#include "llvm/ADT/SmallSet.h" 19#include "llvm/ADT/APFloat.h" 20#include "clang/AST/ASTConsumer.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/ASTDiagnostic.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/AST/Expr.h" 25#include "clang/Lex/Preprocessor.h" 26#include "clang/Basic/PartialDiagnostic.h" 27#include "clang/Basic/TargetInfo.h" 28using namespace clang; 29 30FunctionScopeInfo::~FunctionScopeInfo() { } 31 32void FunctionScopeInfo::Clear(unsigned NumErrors) { 33 NeedsScopeChecking = false; 34 LabelMap.clear(); 35 SwitchStack.clear(); 36 Returns.clear(); 37 NumErrorsAtStartOfFunction = NumErrors; 38} 39 40BlockScopeInfo::~BlockScopeInfo() { } 41 42void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) { 43 TUScope = S; 44 PushDeclContext(S, Context.getTranslationUnitDecl()); 45 46 VAListTagName = PP.getIdentifierInfo("__va_list_tag"); 47 48 if (PP.getTargetInfo().getPointerWidth(0) >= 64) { 49 TypeSourceInfo *TInfo; 50 51 // Install [u]int128_t for 64-bit targets. 52 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty); 53 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 54 SourceLocation(), 55 &Context.Idents.get("__int128_t"), 56 TInfo), TUScope); 57 58 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty); 59 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 60 SourceLocation(), 61 &Context.Idents.get("__uint128_t"), 62 TInfo), TUScope); 63 } 64 65 66 if (!PP.getLangOptions().ObjC1) return; 67 68 // Built-in ObjC types may already be set by PCHReader (hence isNull checks). 69 if (Context.getObjCSelType().isNull()) { 70 // Create the built-in typedef for 'SEL'. 71 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy); 72 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT); 73 TypedefDecl *SelTypedef 74 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 75 &Context.Idents.get("SEL"), SelInfo); 76 PushOnScopeChains(SelTypedef, TUScope); 77 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef)); 78 Context.ObjCSelRedefinitionType = Context.getObjCSelType(); 79 } 80 81 // Synthesize "@class Protocol; 82 if (Context.getObjCProtoType().isNull()) { 83 ObjCInterfaceDecl *ProtocolDecl = 84 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(), 85 &Context.Idents.get("Protocol"), 86 SourceLocation(), true); 87 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl)); 88 PushOnScopeChains(ProtocolDecl, TUScope, false); 89 } 90 // Create the built-in typedef for 'id'. 91 if (Context.getObjCIdType().isNull()) { 92 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 0, 0); 93 T = Context.getObjCObjectPointerType(T); 94 TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(T); 95 TypedefDecl *IdTypedef 96 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 97 &Context.Idents.get("id"), IdInfo); 98 PushOnScopeChains(IdTypedef, TUScope); 99 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef)); 100 Context.ObjCIdRedefinitionType = Context.getObjCIdType(); 101 } 102 // Create the built-in typedef for 'Class'. 103 if (Context.getObjCClassType().isNull()) { 104 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 0, 0); 105 T = Context.getObjCObjectPointerType(T); 106 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(T); 107 TypedefDecl *ClassTypedef 108 = TypedefDecl::Create(Context, CurContext, SourceLocation(), 109 &Context.Idents.get("Class"), ClassInfo); 110 PushOnScopeChains(ClassTypedef, TUScope); 111 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef)); 112 Context.ObjCClassRedefinitionType = Context.getObjCClassType(); 113 } 114} 115 116Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 117 bool CompleteTranslationUnit, 118 CodeCompleteConsumer *CodeCompleter) 119 : TheTargetAttributesSema(0), 120 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer), 121 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), 122 ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0), 123 PackContext(0), TopFunctionScope(0), ParsingDeclDepth(0), 124 IdResolver(pp.getLangOptions()), StdNamespace(0), StdBadAlloc(0), 125 GlobalNewDeleteDeclared(false), 126 CompleteTranslationUnit(CompleteTranslationUnit), 127 NumSFINAEErrors(0), NonInstantiationEntries(0), 128 CurrentInstantiationScope(0), TyposCorrected(0), 129 AnalysisWarnings(*this) 130{ 131 TUScope = 0; 132 if (getLangOptions().CPlusPlus) 133 FieldCollector.reset(new CXXFieldCollector()); 134 135 // Tell diagnostics how to render things from the AST library. 136 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument, 137 &Context); 138 139 ExprEvalContexts.push_back( 140 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0)); 141} 142 143Sema::~Sema() { 144 if (PackContext) FreePackedContext(); 145 delete TheTargetAttributesSema; 146 while (!FunctionScopes.empty()) 147 PopFunctionOrBlockScope(); 148} 149 150/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 151/// If there is already an implicit cast, merge into the existing one. 152/// If isLvalue, the result of the cast is an lvalue. 153void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, 154 CastExpr::CastKind Kind, 155 bool isLvalue, CXXBaseSpecifierArray BasePath) { 156 QualType ExprTy = Context.getCanonicalType(Expr->getType()); 157 QualType TypeTy = Context.getCanonicalType(Ty); 158 159 if (ExprTy == TypeTy) 160 return; 161 162 if (Expr->getType()->isPointerType() && Ty->isPointerType()) { 163 QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType(); 164 QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType(); 165 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) { 166 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast) 167 << Expr->getSourceRange(); 168 } 169 } 170 171 // If this is a derived-to-base cast to a through a virtual base, we 172 // need a vtable. 173 if (Kind == CastExpr::CK_DerivedToBase && 174 BasePathInvolvesVirtualBase(BasePath)) { 175 QualType T = Expr->getType(); 176 if (const PointerType *Pointer = T->getAs<PointerType>()) 177 T = Pointer->getPointeeType(); 178 if (const RecordType *RecordTy = T->getAs<RecordType>()) 179 MarkVTableUsed(Expr->getLocStart(), 180 cast<CXXRecordDecl>(RecordTy->getDecl())); 181 } 182 183 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) { 184 if (ImpCast->getCastKind() == Kind && BasePath.empty()) { 185 ImpCast->setType(Ty); 186 ImpCast->setLvalueCast(isLvalue); 187 return; 188 } 189 } 190 191 Expr = new (Context) ImplicitCastExpr(Ty, Kind, Expr, BasePath, isLvalue); 192} 193 194void Sema::DeleteExpr(ExprTy *E) { 195 if (E) static_cast<Expr*>(E)->Destroy(Context); 196} 197void Sema::DeleteStmt(StmtTy *S) { 198 if (S) static_cast<Stmt*>(S)->Destroy(Context); 199} 200 201/// ActOnEndOfTranslationUnit - This is called at the very end of the 202/// translation unit when EOF is reached and all but the top-level scope is 203/// popped. 204void Sema::ActOnEndOfTranslationUnit() { 205 while (1) { 206 // C++: Perform implicit template instantiations. 207 // 208 // FIXME: When we perform these implicit instantiations, we do not carefully 209 // keep track of the point of instantiation (C++ [temp.point]). This means 210 // that name lookup that occurs within the template instantiation will 211 // always happen at the end of the translation unit, so it will find 212 // some names that should not be found. Although this is common behavior 213 // for C++ compilers, it is technically wrong. In the future, we either need 214 // to be able to filter the results of name lookup or we need to perform 215 // template instantiations earlier. 216 PerformPendingImplicitInstantiations(); 217 218 /// If DefinedUsedVTables ends up marking any virtual member 219 /// functions it might lead to more pending template 220 /// instantiations, which is why we need to loop here. 221 if (!DefineUsedVTables()) 222 break; 223 } 224 225 // Remove functions that turned out to be used. 226 UnusedStaticFuncs.erase(std::remove_if(UnusedStaticFuncs.begin(), 227 UnusedStaticFuncs.end(), 228 std::mem_fun(&FunctionDecl::isUsed)), 229 UnusedStaticFuncs.end()); 230 231 // Check for #pragma weak identifiers that were never declared 232 // FIXME: This will cause diagnostics to be emitted in a non-determinstic 233 // order! Iterating over a densemap like this is bad. 234 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 235 I = WeakUndeclaredIdentifiers.begin(), 236 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) { 237 if (I->second.getUsed()) continue; 238 239 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared) 240 << I->first; 241 } 242 243 if (!CompleteTranslationUnit) 244 return; 245 246 // C99 6.9.2p2: 247 // A declaration of an identifier for an object that has file 248 // scope without an initializer, and without a storage-class 249 // specifier or with the storage-class specifier static, 250 // constitutes a tentative definition. If a translation unit 251 // contains one or more tentative definitions for an identifier, 252 // and the translation unit contains no external definition for 253 // that identifier, then the behavior is exactly as if the 254 // translation unit contains a file scope declaration of that 255 // identifier, with the composite type as of the end of the 256 // translation unit, with an initializer equal to 0. 257 llvm::SmallSet<VarDecl *, 32> Seen; 258 for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) { 259 VarDecl *VD = TentativeDefinitions[i]->getActingDefinition(); 260 261 // If the tentative definition was completed, getActingDefinition() returns 262 // null. If we've already seen this variable before, insert()'s second 263 // return value is false. 264 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD)) 265 continue; 266 267 if (const IncompleteArrayType *ArrayT 268 = Context.getAsIncompleteArrayType(VD->getType())) { 269 if (RequireCompleteType(VD->getLocation(), 270 ArrayT->getElementType(), 271 diag::err_tentative_def_incomplete_type_arr)) { 272 VD->setInvalidDecl(); 273 continue; 274 } 275 276 // Set the length of the array to 1 (C99 6.9.2p5). 277 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 278 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 279 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), 280 One, ArrayType::Normal, 0); 281 VD->setType(T); 282 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 283 diag::err_tentative_def_incomplete_type)) 284 VD->setInvalidDecl(); 285 286 // Notify the consumer that we've completed a tentative definition. 287 if (!VD->isInvalidDecl()) 288 Consumer.CompleteTentativeDefinition(VD); 289 290 } 291 292 // Output warning for unused functions. 293 for (std::vector<FunctionDecl*>::iterator 294 F = UnusedStaticFuncs.begin(), 295 FEnd = UnusedStaticFuncs.end(); 296 F != FEnd; 297 ++F) 298 Diag((*F)->getLocation(), diag::warn_unused_function) << (*F)->getDeclName(); 299 300} 301 302 303//===----------------------------------------------------------------------===// 304// Helper functions. 305//===----------------------------------------------------------------------===// 306 307DeclContext *Sema::getFunctionLevelDeclContext() { 308 DeclContext *DC = CurContext; 309 310 while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC)) 311 DC = DC->getParent(); 312 313 return DC; 314} 315 316/// getCurFunctionDecl - If inside of a function body, this returns a pointer 317/// to the function decl for the function being parsed. If we're currently 318/// in a 'block', this returns the containing context. 319FunctionDecl *Sema::getCurFunctionDecl() { 320 DeclContext *DC = getFunctionLevelDeclContext(); 321 return dyn_cast<FunctionDecl>(DC); 322} 323 324ObjCMethodDecl *Sema::getCurMethodDecl() { 325 DeclContext *DC = getFunctionLevelDeclContext(); 326 return dyn_cast<ObjCMethodDecl>(DC); 327} 328 329NamedDecl *Sema::getCurFunctionOrMethodDecl() { 330 DeclContext *DC = getFunctionLevelDeclContext(); 331 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 332 return cast<NamedDecl>(DC); 333 return 0; 334} 335 336Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { 337 if (!this->Emit()) 338 return; 339 340 // If this is not a note, and we're in a template instantiation 341 // that is different from the last template instantiation where 342 // we emitted an error, print a template instantiation 343 // backtrace. 344 if (!SemaRef.Diags.isBuiltinNote(DiagID) && 345 !SemaRef.ActiveTemplateInstantiations.empty() && 346 SemaRef.ActiveTemplateInstantiations.back() 347 != SemaRef.LastTemplateInstantiationErrorContext) { 348 SemaRef.PrintInstantiationStack(); 349 SemaRef.LastTemplateInstantiationErrorContext 350 = SemaRef.ActiveTemplateInstantiations.back(); 351 } 352} 353 354Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) { 355 if (isSFINAEContext()) { 356 switch (Diagnostic::getDiagnosticSFINAEResponse(DiagID)) { 357 case Diagnostic::SFINAE_Report: 358 // Fall through; we'll report the diagnostic below. 359 break; 360 361 case Diagnostic::SFINAE_SubstitutionFailure: 362 // Count this failure so that we know that template argument deduction 363 // has failed. 364 ++NumSFINAEErrors; 365 // Fall through 366 367 case Diagnostic::SFINAE_Suppress: 368 // Suppress this diagnostic. 369 Diags.setLastDiagnosticIgnored(); 370 return SemaDiagnosticBuilder(*this); 371 } 372 } 373 374 DiagnosticBuilder DB = Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID); 375 return SemaDiagnosticBuilder(DB, *this, DiagID); 376} 377 378Sema::SemaDiagnosticBuilder 379Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 380 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 381 PD.Emit(Builder); 382 383 return Builder; 384} 385 386 387/// \brief Enter a new function scope 388void Sema::PushFunctionScope() { 389 if (FunctionScopes.empty()) { 390 // Use the "top" function scope rather than having to allocate memory for 391 // a new scope. 392 TopFunctionScope.Clear(getDiagnostics().getNumErrors()); 393 FunctionScopes.push_back(&TopFunctionScope); 394 return; 395 } 396 397 FunctionScopes.push_back( 398 new FunctionScopeInfo(getDiagnostics().getNumErrors())); 399} 400 401void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { 402 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics().getNumErrors(), 403 BlockScope, Block)); 404} 405 406void Sema::PopFunctionOrBlockScope() { 407 if (FunctionScopes.back() != &TopFunctionScope) 408 delete FunctionScopes.back(); 409 else 410 TopFunctionScope.Clear(getDiagnostics().getNumErrors()); 411 412 FunctionScopes.pop_back(); 413} 414 415/// \brief Determine whether any errors occurred within this function/method/ 416/// block. 417bool Sema::hasAnyErrorsInThisFunction() const { 418 unsigned NumErrors = TopFunctionScope.NumErrorsAtStartOfFunction; 419 if (!FunctionScopes.empty()) 420 NumErrors = FunctionScopes.back()->NumErrorsAtStartOfFunction; 421 return NumErrors != getDiagnostics().getNumErrors(); 422} 423 424BlockScopeInfo *Sema::getCurBlock() { 425 if (FunctionScopes.empty()) 426 return 0; 427 428 return dyn_cast<BlockScopeInfo>(FunctionScopes.back()); 429} 430