Sema.cpp revision 75f48e16726933b75d77737f4af43620e21bfdcd
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/// ConvertQualTypeToStringFn - This function is used to pretty print the 27/// specified QualType as a string in diagnostics. 28static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val, 29 const char *Modifier, unsigned ModLen, 30 const char *Argument, unsigned ArgLen, 31 llvm::SmallVectorImpl<char> &Output, 32 void *Cookie) { 33 ASTContext &Context = *static_cast<ASTContext*>(Cookie); 34 35 std::string S; 36 if (Kind == Diagnostic::ak_qualtype) { 37 assert(ModLen == 0 && ArgLen == 0 && 38 "Invalid modifier for QualType argument"); 39 40 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val))); 41 42 // FIXME: Playing with std::string is really slow. 43 S = Ty.getAsString(Context.PrintingPolicy); 44 45 // If this is a sugared type (like a typedef, typeof, etc), then unwrap one 46 // level of the sugar so that the type is more obvious to the user. 47 QualType DesugaredTy = Ty->getDesugaredType(true); 48 DesugaredTy.setCVRQualifiers(DesugaredTy.getCVRQualifiers() | 49 Ty.getCVRQualifiers()); 50 51 if (Ty != DesugaredTy && 52 // If the desugared type is a vector type, we don't want to expand it, 53 // it will turn into an attribute mess. People want their "vec4". 54 !isa<VectorType>(DesugaredTy) && 55 56 // Don't aka just because we saw an elaborated type. 57 (!isa<ElaboratedType>(Ty) || 58 cast<ElaboratedType>(Ty)->getUnderlyingType() != DesugaredTy) && 59 60 // Don't desugar magic Objective-C types. 61 Ty.getUnqualifiedType() != Context.getObjCIdType() && 62 Ty.getUnqualifiedType() != Context.getObjCClassType() && 63 Ty.getUnqualifiedType() != Context.getObjCSelType() && 64 Ty.getUnqualifiedType() != Context.getObjCProtoType() && 65 66 // Not va_list. 67 Ty.getUnqualifiedType() != Context.getBuiltinVaListType()) { 68 S = "'"+S+"' (aka '"; 69 S += DesugaredTy.getAsString(Context.PrintingPolicy); 70 S += "')"; 71 Output.append(S.begin(), S.end()); 72 return; 73 } 74 75 } else if (Kind == Diagnostic::ak_declarationname) { 76 77 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val); 78 S = N.getAsString(); 79 80 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0) 81 S = '+' + S; 82 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0) 83 S = '-' + S; 84 else 85 assert(ModLen == 0 && ArgLen == 0 && 86 "Invalid modifier for DeclarationName argument"); 87 } else if (Kind == Diagnostic::ak_nameddecl) { 88 bool Qualified; 89 if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0) 90 Qualified = true; 91 else { 92 assert(ModLen == 0 && ArgLen == 0 && 93 "Invalid modifier for NamedDecl* argument"); 94 Qualified = false; 95 } 96 reinterpret_cast<NamedDecl*>(Val)->getNameForDiagnostic(S, 97 Context.PrintingPolicy, 98 Qualified); 99 } else { 100 llvm::raw_string_ostream OS(S); 101 assert(Kind == Diagnostic::ak_nestednamespec); 102 reinterpret_cast<NestedNameSpecifier*> (Val)->print(OS, 103 Context.PrintingPolicy); 104 } 105 106 Output.push_back('\''); 107 Output.append(S.begin(), S.end()); 108 Output.push_back('\''); 109} 110 111 112static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) { 113 if (C.getLangOptions().CPlusPlus) 114 return CXXRecordDecl::Create(C, TagDecl::TK_struct, 115 C.getTranslationUnitDecl(), 116 SourceLocation(), &C.Idents.get(Name)); 117 118 return RecordDecl::Create(C, TagDecl::TK_struct, 119 C.getTranslationUnitDecl(), 120 SourceLocation(), &C.Idents.get(Name)); 121} 122 123void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) { 124 TUScope = S; 125 PushDeclContext(S, Context.getTranslationUnitDecl()); 126 127 if (PP.getTargetInfo().getPointerWidth(0) >= 64) { 128 // Install [u]int128_t for 64-bit targets. 129 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 130 SourceLocation(), 131 &Context.Idents.get("__int128_t"), 132 Context.Int128Ty), TUScope); 133 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 134 SourceLocation(), 135 &Context.Idents.get("__uint128_t"), 136 Context.UnsignedInt128Ty), TUScope); 137 } 138 139 140 if (!PP.getLangOptions().ObjC1) return; 141 142 // Built-in ObjC types may already be set by PCHReader (hence isNull checks). 143 if (Context.getObjCSelType().isNull()) { 144 // Synthesize "typedef struct objc_selector *SEL;" 145 RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector"); 146 PushOnScopeChains(SelTag, TUScope); 147 148 QualType SelT = Context.getPointerType(Context.getTagDeclType(SelTag)); 149 TypedefDecl *SelTypedef = TypedefDecl::Create(Context, CurContext, 150 SourceLocation(), 151 &Context.Idents.get("SEL"), 152 SelT); 153 PushOnScopeChains(SelTypedef, TUScope); 154 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef)); 155 } 156 157 // Synthesize "@class Protocol; 158 if (Context.getObjCProtoType().isNull()) { 159 ObjCInterfaceDecl *ProtocolDecl = 160 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(), 161 &Context.Idents.get("Protocol"), 162 SourceLocation(), true); 163 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl)); 164 PushOnScopeChains(ProtocolDecl, TUScope); 165 } 166 // Create the built-in typedef for 'id'. 167 if (Context.getObjCIdType().isNull()) { 168 TypedefDecl *IdTypedef = 169 TypedefDecl::Create( 170 Context, CurContext, SourceLocation(), &Context.Idents.get("id"), 171 Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy) 172 ); 173 PushOnScopeChains(IdTypedef, TUScope); 174 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef)); 175 Context.ObjCIdRedefinitionType = Context.getObjCIdType(); 176 } 177 // Create the built-in typedef for 'Class'. 178 if (Context.getObjCClassType().isNull()) { 179 TypedefDecl *ClassTypedef = 180 TypedefDecl::Create( 181 Context, CurContext, SourceLocation(), &Context.Idents.get("Class"), 182 Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy) 183 ); 184 PushOnScopeChains(ClassTypedef, TUScope); 185 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef)); 186 Context.ObjCClassRedefinitionType = Context.getObjCClassType(); 187 } 188} 189 190Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 191 bool CompleteTranslationUnit) 192 : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer), 193 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), 194 ExternalSource(0), CurContext(0), PreDeclaratorDC(0), 195 CurBlock(0), PackContext(0), IdResolver(pp.getLangOptions()), 196 GlobalNewDeleteDeclared(false), ExprEvalContext(PotentiallyEvaluated), 197 CompleteTranslationUnit(CompleteTranslationUnit), 198 NumSFINAEErrors(0), CurrentInstantiationScope(0) { 199 200 StdNamespace = 0; 201 TUScope = 0; 202 if (getLangOptions().CPlusPlus) 203 FieldCollector.reset(new CXXFieldCollector()); 204 205 // Tell diagnostics how to render things from the AST library. 206 PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context); 207} 208 209/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 210/// If there is already an implicit cast, merge into the existing one. 211/// If isLvalue, the result of the cast is an lvalue. 212void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, 213 CastExpr::CastKind Kind, bool isLvalue) { 214 QualType ExprTy = Context.getCanonicalType(Expr->getType()); 215 QualType TypeTy = Context.getCanonicalType(Ty); 216 217 if (ExprTy == TypeTy) 218 return; 219 220 if (Expr->getType().getTypePtr()->isPointerType() && 221 Ty.getTypePtr()->isPointerType()) { 222 QualType ExprBaseType = 223 cast<PointerType>(ExprTy.getUnqualifiedType())->getPointeeType(); 224 QualType BaseType = 225 cast<PointerType>(TypeTy.getUnqualifiedType())->getPointeeType(); 226 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) { 227 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast) 228 << Expr->getSourceRange(); 229 } 230 } 231 232 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) { 233 ImpCast->setType(Ty); 234 ImpCast->setLvalueCast(isLvalue); 235 } else 236 Expr = new (Context) ImplicitCastExpr(Ty, Kind, Expr, isLvalue); 237} 238 239void Sema::DeleteExpr(ExprTy *E) { 240 if (E) static_cast<Expr*>(E)->Destroy(Context); 241} 242void Sema::DeleteStmt(StmtTy *S) { 243 if (S) static_cast<Stmt*>(S)->Destroy(Context); 244} 245 246/// ActOnEndOfTranslationUnit - This is called at the very end of the 247/// translation unit when EOF is reached and all but the top-level scope is 248/// popped. 249void Sema::ActOnEndOfTranslationUnit() { 250 // C++: Perform implicit template instantiations. 251 // 252 // FIXME: When we perform these implicit instantiations, we do not carefully 253 // keep track of the point of instantiation (C++ [temp.point]). This means 254 // that name lookup that occurs within the template instantiation will 255 // always happen at the end of the translation unit, so it will find 256 // some names that should not be found. Although this is common behavior 257 // for C++ compilers, it is technically wrong. In the future, we either need 258 // to be able to filter the results of name lookup or we need to perform 259 // template instantiations earlier. 260 PerformPendingImplicitInstantiations(); 261 262 // Check for #pragma weak identifiers that were never declared 263 // FIXME: This will cause diagnostics to be emitted in a non-determinstic 264 // order! Iterating over a densemap like this is bad. 265 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 266 I = WeakUndeclaredIdentifiers.begin(), 267 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) { 268 if (I->second.getUsed()) continue; 269 270 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared) 271 << I->first; 272 } 273 274 if (!CompleteTranslationUnit) 275 return; 276 277 // C99 6.9.2p2: 278 // A declaration of an identifier for an object that has file 279 // scope without an initializer, and without a storage-class 280 // specifier or with the storage-class specifier static, 281 // constitutes a tentative definition. If a translation unit 282 // contains one or more tentative definitions for an identifier, 283 // and the translation unit contains no external definition for 284 // that identifier, then the behavior is exactly as if the 285 // translation unit contains a file scope declaration of that 286 // identifier, with the composite type as of the end of the 287 // translation unit, with an initializer equal to 0. 288 for (unsigned i = 0, e = TentativeDefinitionList.size(); i != e; ++i) { 289 VarDecl *VD = TentativeDefinitions.lookup(TentativeDefinitionList[i]); 290 291 // If the tentative definition was completed, it will be in the list, but 292 // not the map. 293 if (VD == 0 || VD->isInvalidDecl() || !VD->isTentativeDefinition(Context)) 294 continue; 295 296 if (const IncompleteArrayType *ArrayT 297 = Context.getAsIncompleteArrayType(VD->getType())) { 298 if (RequireCompleteType(VD->getLocation(), 299 ArrayT->getElementType(), 300 diag::err_tentative_def_incomplete_type_arr)) { 301 VD->setInvalidDecl(); 302 continue; 303 } 304 305 // Set the length of the array to 1 (C99 6.9.2p5). 306 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 307 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 308 QualType T 309 = Context.getConstantArrayWithoutExprType(ArrayT->getElementType(), 310 One, ArrayType::Normal, 0); 311 VD->setType(T); 312 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 313 diag::err_tentative_def_incomplete_type)) 314 VD->setInvalidDecl(); 315 316 // Notify the consumer that we've completed a tentative definition. 317 if (!VD->isInvalidDecl()) 318 Consumer.CompleteTentativeDefinition(VD); 319 320 } 321} 322 323 324//===----------------------------------------------------------------------===// 325// Helper functions. 326//===----------------------------------------------------------------------===// 327 328DeclContext *Sema::getFunctionLevelDeclContext() { 329 DeclContext *DC = PreDeclaratorDC ? PreDeclaratorDC : CurContext; 330 331 while (isa<BlockDecl>(DC)) 332 DC = DC->getParent(); 333 334 return DC; 335} 336 337/// getCurFunctionDecl - If inside of a function body, this returns a pointer 338/// to the function decl for the function being parsed. If we're currently 339/// in a 'block', this returns the containing context. 340FunctionDecl *Sema::getCurFunctionDecl() { 341 DeclContext *DC = getFunctionLevelDeclContext(); 342 return dyn_cast<FunctionDecl>(DC); 343} 344 345ObjCMethodDecl *Sema::getCurMethodDecl() { 346 DeclContext *DC = getFunctionLevelDeclContext(); 347 return dyn_cast<ObjCMethodDecl>(DC); 348} 349 350NamedDecl *Sema::getCurFunctionOrMethodDecl() { 351 DeclContext *DC = getFunctionLevelDeclContext(); 352 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 353 return cast<NamedDecl>(DC); 354 return 0; 355} 356 357void Sema::DiagnoseMissingMember(SourceLocation MemberLoc, 358 DeclarationName Member, 359 NestedNameSpecifier *NNS, SourceRange Range) { 360 switch (NNS->getKind()) { 361 default: assert(0 && "Unexpected nested name specifier kind!"); 362 case NestedNameSpecifier::TypeSpec: { 363 const Type *Ty = Context.getCanonicalType(NNS->getAsType()); 364 RecordDecl *RD = cast<RecordType>(Ty)->getDecl(); 365 Diag(MemberLoc, diag::err_typecheck_record_no_member) 366 << Member << RD->getTagKind() << RD << Range; 367 break; 368 } 369 case NestedNameSpecifier::Namespace: { 370 Diag(MemberLoc, diag::err_typecheck_namespace_no_member) 371 << Member << NNS->getAsNamespace() << Range; 372 break; 373 } 374 case NestedNameSpecifier::Global: { 375 Diag(MemberLoc, diag::err_typecheck_global_namespace_no_member) 376 << Member << Range; 377 break; 378 } 379 } 380} 381 382Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { 383 if (!this->Emit()) 384 return; 385 386 // If this is not a note, and we're in a template instantiation 387 // that is different from the last template instantiation where 388 // we emitted an error, print a template instantiation 389 // backtrace. 390 if (!SemaRef.Diags.isBuiltinNote(DiagID) && 391 !SemaRef.ActiveTemplateInstantiations.empty() && 392 SemaRef.ActiveTemplateInstantiations.back() 393 != SemaRef.LastTemplateInstantiationErrorContext) { 394 SemaRef.PrintInstantiationStack(); 395 SemaRef.LastTemplateInstantiationErrorContext 396 = SemaRef.ActiveTemplateInstantiations.back(); 397 } 398} 399 400Sema::SemaDiagnosticBuilder 401Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 402 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 403 PD.Emit(Builder); 404 405 return Builder; 406} 407 408void Sema::ActOnComment(SourceRange Comment) { 409 Context.Comments.push_back(Comment); 410} 411 412