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