Sema.cpp revision 136a6988960ac3aeb96f298da7a1a182db7217cd
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 const CastExpr::CastInfo &Info, 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, Info, Expr, 237 isLvalue); 238} 239 240void Sema::DeleteExpr(ExprTy *E) { 241 if (E) static_cast<Expr*>(E)->Destroy(Context); 242} 243void Sema::DeleteStmt(StmtTy *S) { 244 if (S) static_cast<Stmt*>(S)->Destroy(Context); 245} 246 247/// ActOnEndOfTranslationUnit - This is called at the very end of the 248/// translation unit when EOF is reached and all but the top-level scope is 249/// popped. 250void Sema::ActOnEndOfTranslationUnit() { 251 // C++: Perform implicit template instantiations. 252 // 253 // FIXME: When we perform these implicit instantiations, we do not carefully 254 // keep track of the point of instantiation (C++ [temp.point]). This means 255 // that name lookup that occurs within the template instantiation will 256 // always happen at the end of the translation unit, so it will find 257 // some names that should not be found. Although this is common behavior 258 // for C++ compilers, it is technically wrong. In the future, we either need 259 // to be able to filter the results of name lookup or we need to perform 260 // template instantiations earlier. 261 PerformPendingImplicitInstantiations(); 262 263 // Check for #pragma weak identifiers that were never declared 264 // FIXME: This will cause diagnostics to be emitted in a non-determinstic 265 // order! Iterating over a densemap like this is bad. 266 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 267 I = WeakUndeclaredIdentifiers.begin(), 268 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) { 269 if (I->second.getUsed()) continue; 270 271 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared) 272 << I->first; 273 } 274 275 if (!CompleteTranslationUnit) 276 return; 277 278 // C99 6.9.2p2: 279 // A declaration of an identifier for an object that has file 280 // scope without an initializer, and without a storage-class 281 // specifier or with the storage-class specifier static, 282 // constitutes a tentative definition. If a translation unit 283 // contains one or more tentative definitions for an identifier, 284 // and the translation unit contains no external definition for 285 // that identifier, then the behavior is exactly as if the 286 // translation unit contains a file scope declaration of that 287 // identifier, with the composite type as of the end of the 288 // translation unit, with an initializer equal to 0. 289 for (unsigned i = 0, e = TentativeDefinitionList.size(); i != e; ++i) { 290 VarDecl *VD = TentativeDefinitions.lookup(TentativeDefinitionList[i]); 291 292 // If the tentative definition was completed, it will be in the list, but 293 // not the map. 294 if (VD == 0 || VD->isInvalidDecl() || !VD->isTentativeDefinition(Context)) 295 continue; 296 297 if (const IncompleteArrayType *ArrayT 298 = Context.getAsIncompleteArrayType(VD->getType())) { 299 if (RequireCompleteType(VD->getLocation(), 300 ArrayT->getElementType(), 301 diag::err_tentative_def_incomplete_type_arr)) { 302 VD->setInvalidDecl(); 303 continue; 304 } 305 306 // Set the length of the array to 1 (C99 6.9.2p5). 307 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 308 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 309 QualType T 310 = Context.getConstantArrayWithoutExprType(ArrayT->getElementType(), 311 One, ArrayType::Normal, 0); 312 VD->setType(T); 313 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 314 diag::err_tentative_def_incomplete_type)) 315 VD->setInvalidDecl(); 316 317 // Notify the consumer that we've completed a tentative definition. 318 if (!VD->isInvalidDecl()) 319 Consumer.CompleteTentativeDefinition(VD); 320 321 } 322} 323 324 325//===----------------------------------------------------------------------===// 326// Helper functions. 327//===----------------------------------------------------------------------===// 328 329DeclContext *Sema::getFunctionLevelDeclContext() { 330 DeclContext *DC = PreDeclaratorDC ? PreDeclaratorDC : CurContext; 331 332 while (isa<BlockDecl>(DC)) 333 DC = DC->getParent(); 334 335 return DC; 336} 337 338/// getCurFunctionDecl - If inside of a function body, this returns a pointer 339/// to the function decl for the function being parsed. If we're currently 340/// in a 'block', this returns the containing context. 341FunctionDecl *Sema::getCurFunctionDecl() { 342 DeclContext *DC = getFunctionLevelDeclContext(); 343 return dyn_cast<FunctionDecl>(DC); 344} 345 346ObjCMethodDecl *Sema::getCurMethodDecl() { 347 DeclContext *DC = getFunctionLevelDeclContext(); 348 return dyn_cast<ObjCMethodDecl>(DC); 349} 350 351NamedDecl *Sema::getCurFunctionOrMethodDecl() { 352 DeclContext *DC = getFunctionLevelDeclContext(); 353 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 354 return cast<NamedDecl>(DC); 355 return 0; 356} 357 358void Sema::DiagnoseMissingMember(SourceLocation MemberLoc, 359 DeclarationName Member, 360 NestedNameSpecifier *NNS, SourceRange Range) { 361 switch (NNS->getKind()) { 362 default: assert(0 && "Unexpected nested name specifier kind!"); 363 case NestedNameSpecifier::TypeSpec: { 364 const Type *Ty = Context.getCanonicalType(NNS->getAsType()); 365 RecordDecl *RD = cast<RecordType>(Ty)->getDecl(); 366 Diag(MemberLoc, diag::err_typecheck_record_no_member) 367 << Member << RD->getTagKind() << RD << Range; 368 break; 369 } 370 case NestedNameSpecifier::Namespace: { 371 Diag(MemberLoc, diag::err_typecheck_namespace_no_member) 372 << Member << NNS->getAsNamespace() << Range; 373 break; 374 } 375 case NestedNameSpecifier::Global: { 376 Diag(MemberLoc, diag::err_typecheck_global_namespace_no_member) 377 << Member << Range; 378 break; 379 } 380 } 381} 382 383Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { 384 if (!this->Emit()) 385 return; 386 387 // If this is not a note, and we're in a template instantiation 388 // that is different from the last template instantiation where 389 // we emitted an error, print a template instantiation 390 // backtrace. 391 if (!SemaRef.Diags.isBuiltinNote(DiagID) && 392 !SemaRef.ActiveTemplateInstantiations.empty() && 393 SemaRef.ActiveTemplateInstantiations.back() 394 != SemaRef.LastTemplateInstantiationErrorContext) { 395 SemaRef.PrintInstantiationStack(); 396 SemaRef.LastTemplateInstantiationErrorContext 397 = SemaRef.ActiveTemplateInstantiations.back(); 398 } 399} 400 401Sema::SemaDiagnosticBuilder 402Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 403 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 404 PD.Emit(Builder); 405 406 return Builder; 407} 408 409void Sema::ActOnComment(SourceRange Comment) { 410 Context.Comments.push_back(Comment); 411} 412 413