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