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