1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 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 coordinates the per-module state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenModule.h" 15 #include "CGDebugInfo.h" 16 #include "CodeGenFunction.h" 17 #include "CGCall.h" 18 #include "CGObjCRuntime.h" 19 #include "Mangle.h" 20 #include "clang/Frontend/CompileOptions.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclCXX.h" 24 #include "clang/Basic/Builtins.h" 25 #include "clang/Basic/Diagnostic.h" 26 #include "clang/Basic/SourceManager.h" 27 #include "clang/Basic/TargetInfo.h" 28 #include "clang/Basic/ConvertUTF.h" 29 #include "llvm/CallingConv.h" 30 #include "llvm/Module.h" 31 #include "llvm/Intrinsics.h" 32 #include "llvm/Target/TargetData.h" 33 using namespace clang; 34 using namespace CodeGen; 35 36 37 CodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts, 38 llvm::Module &M, const llvm::TargetData &TD, 39 Diagnostic &diags) 40 : BlockModule(C, M, TD, Types, *this), Context(C), 41 Features(C.getLangOptions()), CompileOpts(compileOpts), TheModule(M), 42 TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0), 43 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0), 44 VMContext(M.getContext()) { 45 46 if (!Features.ObjC1) 47 Runtime = 0; 48 else if (!Features.NeXTRuntime) 49 Runtime = CreateGNUObjCRuntime(*this); 50 else if (Features.ObjCNonFragileABI) 51 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 52 else 53 Runtime = CreateMacObjCRuntime(*this); 54 55 // If debug info generation is enabled, create the CGDebugInfo object. 56 DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0; 57 } 58 59 CodeGenModule::~CodeGenModule() { 60 delete Runtime; 61 delete DebugInfo; 62 } 63 64 void CodeGenModule::Release() { 65 // We need to call this first because it can add deferred declarations. 66 EmitCXXGlobalInitFunc(); 67 68 EmitDeferred(); 69 if (Runtime) 70 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 71 AddGlobalCtor(ObjCInitFunction); 72 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 73 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 74 EmitAnnotations(); 75 EmitLLVMUsed(); 76 } 77 78 /// ErrorUnsupported - Print out an error that codegen doesn't support the 79 /// specified stmt yet. 80 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 81 bool OmitOnError) { 82 if (OmitOnError && getDiags().hasErrorOccurred()) 83 return; 84 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 85 "cannot compile this %0 yet"); 86 std::string Msg = Type; 87 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 88 << Msg << S->getSourceRange(); 89 } 90 91 /// ErrorUnsupported - Print out an error that codegen doesn't support the 92 /// specified decl yet. 93 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 94 bool OmitOnError) { 95 if (OmitOnError && getDiags().hasErrorOccurred()) 96 return; 97 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 98 "cannot compile this %0 yet"); 99 std::string Msg = Type; 100 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 101 } 102 103 LangOptions::VisibilityMode 104 CodeGenModule::getDeclVisibilityMode(const Decl *D) const { 105 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 106 if (VD->getStorageClass() == VarDecl::PrivateExtern) 107 return LangOptions::Hidden; 108 109 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) { 110 switch (attr->getVisibility()) { 111 default: assert(0 && "Unknown visibility!"); 112 case VisibilityAttr::DefaultVisibility: 113 return LangOptions::Default; 114 case VisibilityAttr::HiddenVisibility: 115 return LangOptions::Hidden; 116 case VisibilityAttr::ProtectedVisibility: 117 return LangOptions::Protected; 118 } 119 } 120 121 return getLangOptions().getVisibilityMode(); 122 } 123 124 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 125 const Decl *D) const { 126 // Internal definitions always have default visibility. 127 if (GV->hasLocalLinkage()) { 128 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 129 return; 130 } 131 132 switch (getDeclVisibilityMode(D)) { 133 default: assert(0 && "Unknown visibility!"); 134 case LangOptions::Default: 135 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 136 case LangOptions::Hidden: 137 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 138 case LangOptions::Protected: 139 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 140 } 141 } 142 143 const char *CodeGenModule::getMangledName(const GlobalDecl &GD) { 144 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 145 146 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 147 return getMangledCXXCtorName(D, GD.getCtorType()); 148 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 149 return getMangledCXXDtorName(D, GD.getDtorType()); 150 151 return getMangledName(ND); 152 } 153 154 /// \brief Retrieves the mangled name for the given declaration. 155 /// 156 /// If the given declaration requires a mangled name, returns an 157 /// const char* containing the mangled name. Otherwise, returns 158 /// the unmangled name. 159 /// 160 const char *CodeGenModule::getMangledName(const NamedDecl *ND) { 161 // In C, functions with no attributes never need to be mangled. Fastpath them. 162 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) { 163 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 164 return ND->getNameAsCString(); 165 } 166 167 llvm::SmallString<256> Name; 168 llvm::raw_svector_ostream Out(Name); 169 if (!mangleName(ND, Context, Out)) { 170 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 171 return ND->getNameAsCString(); 172 } 173 174 Name += '\0'; 175 return UniqueMangledName(Name.begin(), Name.end()); 176 } 177 178 const char *CodeGenModule::UniqueMangledName(const char *NameStart, 179 const char *NameEnd) { 180 assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!"); 181 182 return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData(); 183 } 184 185 /// AddGlobalCtor - Add a function to the list that will be called before 186 /// main() runs. 187 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 188 // FIXME: Type coercion of void()* types. 189 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 190 } 191 192 /// AddGlobalDtor - Add a function to the list that will be called 193 /// when the module is unloaded. 194 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 195 // FIXME: Type coercion of void()* types. 196 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 197 } 198 199 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 200 // Ctor function type is void()*. 201 llvm::FunctionType* CtorFTy = 202 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 203 std::vector<const llvm::Type*>(), 204 false); 205 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 206 207 // Get the type of a ctor entry, { i32, void ()* }. 208 llvm::StructType* CtorStructTy = 209 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext), 210 llvm::PointerType::getUnqual(CtorFTy), NULL); 211 212 // Construct the constructor and destructor arrays. 213 std::vector<llvm::Constant*> Ctors; 214 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 215 std::vector<llvm::Constant*> S; 216 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 217 I->second, false)); 218 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 219 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 220 } 221 222 if (!Ctors.empty()) { 223 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 224 new llvm::GlobalVariable(TheModule, AT, false, 225 llvm::GlobalValue::AppendingLinkage, 226 llvm::ConstantArray::get(AT, Ctors), 227 GlobalName); 228 } 229 } 230 231 void CodeGenModule::EmitAnnotations() { 232 if (Annotations.empty()) 233 return; 234 235 // Create a new global variable for the ConstantStruct in the Module. 236 llvm::Constant *Array = 237 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 238 Annotations.size()), 239 Annotations); 240 llvm::GlobalValue *gv = 241 new llvm::GlobalVariable(TheModule, Array->getType(), false, 242 llvm::GlobalValue::AppendingLinkage, Array, 243 "llvm.global.annotations"); 244 gv->setSection("llvm.metadata"); 245 } 246 247 static CodeGenModule::GVALinkage 248 GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD, 249 const LangOptions &Features) { 250 // Everything located semantically within an anonymous namespace is 251 // always internal. 252 if (FD->isInAnonymousNamespace()) 253 return CodeGenModule::GVA_Internal; 254 255 // The kind of external linkage this function will have, if it is not 256 // inline or static. 257 CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal; 258 if (Context.getLangOptions().CPlusPlus && 259 FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 260 External = CodeGenModule::GVA_TemplateInstantiation; 261 262 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 263 // C++ member functions defined inside the class are always inline. 264 if (MD->isInline() || !MD->isOutOfLine()) 265 return CodeGenModule::GVA_CXXInline; 266 267 return External; 268 } 269 270 // "static" functions get internal linkage. 271 if (FD->getStorageClass() == FunctionDecl::Static) 272 return CodeGenModule::GVA_Internal; 273 274 if (!FD->isInline()) 275 return External; 276 277 if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 278 // GNU or C99 inline semantics. Determine whether this symbol should be 279 // externally visible. 280 if (FD->isInlineDefinitionExternallyVisible()) 281 return External; 282 283 // C99 inline semantics, where the symbol is not externally visible. 284 return CodeGenModule::GVA_C99Inline; 285 } 286 287 // C++ inline semantics 288 assert(Features.CPlusPlus && "Must be in C++ mode"); 289 return CodeGenModule::GVA_CXXInline; 290 } 291 292 /// SetFunctionDefinitionAttributes - Set attributes for a global. 293 /// 294 /// FIXME: This is currently only done for aliases and functions, but not for 295 /// variables (these details are set in EmitGlobalVarDefinition for variables). 296 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 297 llvm::GlobalValue *GV) { 298 GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features); 299 300 if (Linkage == GVA_Internal) { 301 GV->setLinkage(llvm::Function::InternalLinkage); 302 } else if (D->hasAttr<DLLExportAttr>()) { 303 GV->setLinkage(llvm::Function::DLLExportLinkage); 304 } else if (D->hasAttr<WeakAttr>()) { 305 GV->setLinkage(llvm::Function::WeakAnyLinkage); 306 } else if (Linkage == GVA_C99Inline) { 307 // In C99 mode, 'inline' functions are guaranteed to have a strong 308 // definition somewhere else, so we can use available_externally linkage. 309 GV->setLinkage(llvm::Function::AvailableExternallyLinkage); 310 } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) { 311 // In C++, the compiler has to emit a definition in every translation unit 312 // that references the function. We should use linkonce_odr because 313 // a) if all references in this translation unit are optimized away, we 314 // don't need to codegen it. b) if the function persists, it needs to be 315 // merged with other definitions. c) C++ has the ODR, so we know the 316 // definition is dependable. 317 GV->setLinkage(llvm::Function::LinkOnceODRLinkage); 318 } else { 319 assert(Linkage == GVA_StrongExternal); 320 // Otherwise, we have strong external linkage. 321 GV->setLinkage(llvm::Function::ExternalLinkage); 322 } 323 324 SetCommonAttributes(D, GV); 325 } 326 327 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 328 const CGFunctionInfo &Info, 329 llvm::Function *F) { 330 unsigned CallingConv; 331 AttributeListType AttributeList; 332 ConstructAttributeList(Info, D, AttributeList, CallingConv); 333 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 334 AttributeList.size())); 335 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 336 } 337 338 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 339 llvm::Function *F) { 340 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 341 F->addFnAttr(llvm::Attribute::NoUnwind); 342 343 if (D->hasAttr<AlwaysInlineAttr>()) 344 F->addFnAttr(llvm::Attribute::AlwaysInline); 345 346 if (D->hasAttr<NoInlineAttr>()) 347 F->addFnAttr(llvm::Attribute::NoInline); 348 349 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) 350 F->setAlignment(AA->getAlignment()/8); 351 } 352 353 void CodeGenModule::SetCommonAttributes(const Decl *D, 354 llvm::GlobalValue *GV) { 355 setGlobalVisibility(GV, D); 356 357 if (D->hasAttr<UsedAttr>()) 358 AddUsedGlobal(GV); 359 360 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 361 GV->setSection(SA->getName()); 362 } 363 364 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 365 llvm::Function *F, 366 const CGFunctionInfo &FI) { 367 SetLLVMFunctionAttributes(D, FI, F); 368 SetLLVMFunctionAttributesForDefinition(D, F); 369 370 F->setLinkage(llvm::Function::InternalLinkage); 371 372 SetCommonAttributes(D, F); 373 } 374 375 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD, 376 llvm::Function *F, 377 bool IsIncompleteFunction) { 378 if (!IsIncompleteFunction) 379 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F); 380 381 // Only a few attributes are set on declarations; these may later be 382 // overridden by a definition. 383 384 if (FD->hasAttr<DLLImportAttr>()) { 385 F->setLinkage(llvm::Function::DLLImportLinkage); 386 } else if (FD->hasAttr<WeakAttr>() || 387 FD->hasAttr<WeakImportAttr>()) { 388 // "extern_weak" is overloaded in LLVM; we probably should have 389 // separate linkage types for this. 390 F->setLinkage(llvm::Function::ExternalWeakLinkage); 391 } else { 392 F->setLinkage(llvm::Function::ExternalLinkage); 393 } 394 395 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 396 F->setSection(SA->getName()); 397 } 398 399 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 400 assert(!GV->isDeclaration() && 401 "Only globals with definition can force usage."); 402 LLVMUsed.push_back(GV); 403 } 404 405 void CodeGenModule::EmitLLVMUsed() { 406 // Don't create llvm.used if there is no need. 407 if (LLVMUsed.empty()) 408 return; 409 410 llvm::Type *i8PTy = 411 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 412 413 // Convert LLVMUsed to what ConstantArray needs. 414 std::vector<llvm::Constant*> UsedArray; 415 UsedArray.resize(LLVMUsed.size()); 416 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 417 UsedArray[i] = 418 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 419 i8PTy); 420 } 421 422 if (UsedArray.empty()) 423 return; 424 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); 425 426 llvm::GlobalVariable *GV = 427 new llvm::GlobalVariable(getModule(), ATy, false, 428 llvm::GlobalValue::AppendingLinkage, 429 llvm::ConstantArray::get(ATy, UsedArray), 430 "llvm.used"); 431 432 GV->setSection("llvm.metadata"); 433 } 434 435 void CodeGenModule::EmitDeferred() { 436 // Emit code for any potentially referenced deferred decls. Since a 437 // previously unused static decl may become used during the generation of code 438 // for a static function, iterate until no changes are made. 439 while (!DeferredDeclsToEmit.empty()) { 440 GlobalDecl D = DeferredDeclsToEmit.back(); 441 DeferredDeclsToEmit.pop_back(); 442 443 // The mangled name for the decl must have been emitted in GlobalDeclMap. 444 // Look it up to see if it was defined with a stronger definition (e.g. an 445 // extern inline function with a strong function redefinition). If so, 446 // just ignore the deferred decl. 447 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)]; 448 assert(CGRef && "Deferred decl wasn't referenced?"); 449 450 if (!CGRef->isDeclaration()) 451 continue; 452 453 // Otherwise, emit the definition and move on to the next one. 454 EmitGlobalDefinition(D); 455 } 456 } 457 458 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 459 /// annotation information for a given GlobalValue. The annotation struct is 460 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 461 /// GlobalValue being annotated. The second field is the constant string 462 /// created from the AnnotateAttr's annotation. The third field is a constant 463 /// string containing the name of the translation unit. The fourth field is 464 /// the line number in the file of the annotated value declaration. 465 /// 466 /// FIXME: this does not unique the annotation string constants, as llvm-gcc 467 /// appears to. 468 /// 469 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 470 const AnnotateAttr *AA, 471 unsigned LineNo) { 472 llvm::Module *M = &getModule(); 473 474 // get [N x i8] constants for the annotation string, and the filename string 475 // which are the 2nd and 3rd elements of the global annotation structure. 476 const llvm::Type *SBP = 477 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 478 llvm::Constant *anno = llvm::ConstantArray::get(VMContext, 479 AA->getAnnotation(), true); 480 llvm::Constant *unit = llvm::ConstantArray::get(VMContext, 481 M->getModuleIdentifier(), 482 true); 483 484 // Get the two global values corresponding to the ConstantArrays we just 485 // created to hold the bytes of the strings. 486 llvm::GlobalValue *annoGV = 487 new llvm::GlobalVariable(*M, anno->getType(), false, 488 llvm::GlobalValue::PrivateLinkage, anno, 489 GV->getName()); 490 // translation unit name string, emitted into the llvm.metadata section. 491 llvm::GlobalValue *unitGV = 492 new llvm::GlobalVariable(*M, unit->getType(), false, 493 llvm::GlobalValue::PrivateLinkage, unit, 494 ".str"); 495 496 // Create the ConstantStruct for the global annotation. 497 llvm::Constant *Fields[4] = { 498 llvm::ConstantExpr::getBitCast(GV, SBP), 499 llvm::ConstantExpr::getBitCast(annoGV, SBP), 500 llvm::ConstantExpr::getBitCast(unitGV, SBP), 501 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo) 502 }; 503 return llvm::ConstantStruct::get(VMContext, Fields, 4, false); 504 } 505 506 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 507 // Never defer when EmitAllDecls is specified or the decl has 508 // attribute used. 509 if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>()) 510 return false; 511 512 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 513 // Constructors and destructors should never be deferred. 514 if (FD->hasAttr<ConstructorAttr>() || 515 FD->hasAttr<DestructorAttr>()) 516 return false; 517 518 GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features); 519 520 // static, static inline, always_inline, and extern inline functions can 521 // always be deferred. Normal inline functions can be deferred in C99/C++. 522 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || 523 Linkage == GVA_CXXInline) 524 return true; 525 return false; 526 } 527 528 const VarDecl *VD = cast<VarDecl>(Global); 529 assert(VD->isFileVarDecl() && "Invalid decl"); 530 531 return VD->getStorageClass() == VarDecl::Static; 532 } 533 534 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 535 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 536 537 // If this is an alias definition (which otherwise looks like a declaration) 538 // emit it now. 539 if (Global->hasAttr<AliasAttr>()) 540 return EmitAliasDefinition(Global); 541 542 // Ignore declarations, they will be emitted on their first use. 543 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 544 // Forward declarations are emitted lazily on first use. 545 if (!FD->isThisDeclarationADefinition()) 546 return; 547 } else { 548 const VarDecl *VD = cast<VarDecl>(Global); 549 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 550 551 // In C++, if this is marked "extern", defer code generation. 552 if (getLangOptions().CPlusPlus && !VD->getInit() && 553 (VD->getStorageClass() == VarDecl::Extern || 554 VD->isExternC())) 555 return; 556 557 // In C, if this isn't a definition, defer code generation. 558 if (!getLangOptions().CPlusPlus && !VD->getInit()) 559 return; 560 } 561 562 // Defer code generation when possible if this is a static definition, inline 563 // function etc. These we only want to emit if they are used. 564 if (MayDeferGeneration(Global)) { 565 // If the value has already been used, add it directly to the 566 // DeferredDeclsToEmit list. 567 const char *MangledName = getMangledName(GD); 568 if (GlobalDeclMap.count(MangledName)) 569 DeferredDeclsToEmit.push_back(GD); 570 else { 571 // Otherwise, remember that we saw a deferred decl with this name. The 572 // first use of the mangled name will cause it to move into 573 // DeferredDeclsToEmit. 574 DeferredDecls[MangledName] = GD; 575 } 576 return; 577 } 578 579 // Otherwise emit the definition. 580 EmitGlobalDefinition(GD); 581 } 582 583 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 584 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 585 586 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 587 EmitCXXConstructor(CD, GD.getCtorType()); 588 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 589 EmitCXXDestructor(DD, GD.getDtorType()); 590 else if (isa<FunctionDecl>(D)) 591 EmitGlobalFunctionDefinition(GD); 592 else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 593 EmitGlobalVarDefinition(VD); 594 else { 595 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 596 } 597 } 598 599 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 600 /// module, create and return an llvm Function with the specified type. If there 601 /// is something in the module with the specified name, return it potentially 602 /// bitcasted to the right type. 603 /// 604 /// If D is non-null, it specifies a decl that correspond to this. This is used 605 /// to set the attributes on the function when it is first created. 606 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName, 607 const llvm::Type *Ty, 608 GlobalDecl D) { 609 // Lookup the entry, lazily creating it if necessary. 610 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 611 if (Entry) { 612 if (Entry->getType()->getElementType() == Ty) 613 return Entry; 614 615 // Make sure the result is of the correct type. 616 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 617 return llvm::ConstantExpr::getBitCast(Entry, PTy); 618 } 619 620 // This is the first use or definition of a mangled name. If there is a 621 // deferred decl with this name, remember that we need to emit it at the end 622 // of the file. 623 llvm::DenseMap<const char*, GlobalDecl>::iterator DDI = 624 DeferredDecls.find(MangledName); 625 if (DDI != DeferredDecls.end()) { 626 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 627 // list, and remove it from DeferredDecls (since we don't need it anymore). 628 DeferredDeclsToEmit.push_back(DDI->second); 629 DeferredDecls.erase(DDI); 630 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) { 631 // If this the first reference to a C++ inline function in a class, queue up 632 // the deferred function body for emission. These are not seen as 633 // top-level declarations. 634 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD)) 635 DeferredDeclsToEmit.push_back(D); 636 // A called constructor which has no definition or declaration need be 637 // synthesized. 638 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 639 const CXXRecordDecl *ClassDecl = 640 cast<CXXRecordDecl>(CD->getDeclContext()); 641 if (CD->isCopyConstructor(getContext())) 642 DeferredCopyConstructorToEmit(D); 643 else if (!ClassDecl->hasUserDeclaredConstructor()) 644 DeferredDeclsToEmit.push_back(D); 645 } 646 else if (isa<CXXDestructorDecl>(FD)) 647 DeferredDestructorToEmit(D); 648 else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 649 if (MD->isCopyAssignment()) 650 DeferredCopyAssignmentToEmit(D); 651 } 652 653 // This function doesn't have a complete type (for example, the return 654 // type is an incomplete struct). Use a fake type instead, and make 655 // sure not to try to set attributes. 656 bool IsIncompleteFunction = false; 657 if (!isa<llvm::FunctionType>(Ty)) { 658 Ty = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 659 std::vector<const llvm::Type*>(), false); 660 IsIncompleteFunction = true; 661 } 662 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty), 663 llvm::Function::ExternalLinkage, 664 "", &getModule()); 665 F->setName(MangledName); 666 if (D.getDecl()) 667 SetFunctionAttributes(cast<FunctionDecl>(D.getDecl()), F, 668 IsIncompleteFunction); 669 Entry = F; 670 return F; 671 } 672 673 /// Defer definition of copy constructor(s) which need be implicitly defined. 674 void CodeGenModule::DeferredCopyConstructorToEmit(GlobalDecl CopyCtorDecl) { 675 const CXXConstructorDecl *CD = 676 cast<CXXConstructorDecl>(CopyCtorDecl.getDecl()); 677 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext()); 678 if (ClassDecl->hasTrivialCopyConstructor() || 679 ClassDecl->hasUserDeclaredCopyConstructor()) 680 return; 681 682 // First make sure all direct base classes and virtual bases and non-static 683 // data mebers which need to have their copy constructors implicitly defined 684 // are defined. 12.8.p7 685 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 686 Base != ClassDecl->bases_end(); ++Base) { 687 CXXRecordDecl *BaseClassDecl 688 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 689 if (CXXConstructorDecl *BaseCopyCtor = 690 BaseClassDecl->getCopyConstructor(Context, 0)) 691 GetAddrOfCXXConstructor(BaseCopyCtor, Ctor_Complete); 692 } 693 694 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 695 FieldEnd = ClassDecl->field_end(); 696 Field != FieldEnd; ++Field) { 697 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 698 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 699 FieldType = Array->getElementType(); 700 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 701 if ((*Field)->isAnonymousStructOrUnion()) 702 continue; 703 CXXRecordDecl *FieldClassDecl 704 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 705 if (CXXConstructorDecl *FieldCopyCtor = 706 FieldClassDecl->getCopyConstructor(Context, 0)) 707 GetAddrOfCXXConstructor(FieldCopyCtor, Ctor_Complete); 708 } 709 } 710 DeferredDeclsToEmit.push_back(CopyCtorDecl); 711 } 712 713 /// Defer definition of copy assignments which need be implicitly defined. 714 void CodeGenModule::DeferredCopyAssignmentToEmit(GlobalDecl CopyAssignDecl) { 715 const CXXMethodDecl *CD = cast<CXXMethodDecl>(CopyAssignDecl.getDecl()); 716 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext()); 717 718 if (ClassDecl->hasTrivialCopyAssignment() || 719 ClassDecl->hasUserDeclaredCopyAssignment()) 720 return; 721 722 // First make sure all direct base classes and virtual bases and non-static 723 // data mebers which need to have their copy assignments implicitly defined 724 // are defined. 12.8.p12 725 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 726 Base != ClassDecl->bases_end(); ++Base) { 727 CXXRecordDecl *BaseClassDecl 728 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 729 const CXXMethodDecl *MD = 0; 730 if (!BaseClassDecl->hasTrivialCopyAssignment() && 731 !BaseClassDecl->hasUserDeclaredCopyAssignment() && 732 BaseClassDecl->hasConstCopyAssignment(getContext(), MD)) 733 GetAddrOfFunction(MD, 0); 734 } 735 736 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 737 FieldEnd = ClassDecl->field_end(); 738 Field != FieldEnd; ++Field) { 739 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 740 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 741 FieldType = Array->getElementType(); 742 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 743 if ((*Field)->isAnonymousStructOrUnion()) 744 continue; 745 CXXRecordDecl *FieldClassDecl 746 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 747 const CXXMethodDecl *MD = 0; 748 if (!FieldClassDecl->hasTrivialCopyAssignment() && 749 !FieldClassDecl->hasUserDeclaredCopyAssignment() && 750 FieldClassDecl->hasConstCopyAssignment(getContext(), MD)) 751 GetAddrOfFunction(MD, 0); 752 } 753 } 754 DeferredDeclsToEmit.push_back(CopyAssignDecl); 755 } 756 757 void CodeGenModule::DeferredDestructorToEmit(GlobalDecl DtorDecl) { 758 const CXXDestructorDecl *DD = cast<CXXDestructorDecl>(DtorDecl.getDecl()); 759 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext()); 760 if (ClassDecl->hasTrivialDestructor() || 761 ClassDecl->hasUserDeclaredDestructor()) 762 return; 763 764 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 765 Base != ClassDecl->bases_end(); ++Base) { 766 CXXRecordDecl *BaseClassDecl 767 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 768 if (const CXXDestructorDecl *BaseDtor = 769 BaseClassDecl->getDestructor(Context)) 770 GetAddrOfCXXDestructor(BaseDtor, Dtor_Complete); 771 } 772 773 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 774 FieldEnd = ClassDecl->field_end(); 775 Field != FieldEnd; ++Field) { 776 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 777 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 778 FieldType = Array->getElementType(); 779 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 780 if ((*Field)->isAnonymousStructOrUnion()) 781 continue; 782 CXXRecordDecl *FieldClassDecl 783 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 784 if (const CXXDestructorDecl *FieldDtor = 785 FieldClassDecl->getDestructor(Context)) 786 GetAddrOfCXXDestructor(FieldDtor, Dtor_Complete); 787 } 788 } 789 DeferredDeclsToEmit.push_back(DtorDecl); 790 } 791 792 793 /// GetAddrOfFunction - Return the address of the given function. If Ty is 794 /// non-null, then this function will use the specified type if it has to 795 /// create it (this occurs when we see a definition of the function). 796 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 797 const llvm::Type *Ty) { 798 // If there was no specific requested type, just convert it now. 799 if (!Ty) 800 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 801 return GetOrCreateLLVMFunction(getMangledName(GD), Ty, GD); 802 } 803 804 /// CreateRuntimeFunction - Create a new runtime function with the specified 805 /// type and name. 806 llvm::Constant * 807 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 808 const char *Name) { 809 // Convert Name to be a uniqued string from the IdentifierInfo table. 810 Name = getContext().Idents.get(Name).getName(); 811 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl()); 812 } 813 814 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 815 /// create and return an llvm GlobalVariable with the specified type. If there 816 /// is something in the module with the specified name, return it potentially 817 /// bitcasted to the right type. 818 /// 819 /// If D is non-null, it specifies a decl that correspond to this. This is used 820 /// to set the attributes on the global when it is first created. 821 llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName, 822 const llvm::PointerType*Ty, 823 const VarDecl *D) { 824 // Lookup the entry, lazily creating it if necessary. 825 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 826 if (Entry) { 827 if (Entry->getType() == Ty) 828 return Entry; 829 830 // Make sure the result is of the correct type. 831 return llvm::ConstantExpr::getBitCast(Entry, Ty); 832 } 833 834 // This is the first use or definition of a mangled name. If there is a 835 // deferred decl with this name, remember that we need to emit it at the end 836 // of the file. 837 llvm::DenseMap<const char*, GlobalDecl>::iterator DDI = 838 DeferredDecls.find(MangledName); 839 if (DDI != DeferredDecls.end()) { 840 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 841 // list, and remove it from DeferredDecls (since we don't need it anymore). 842 DeferredDeclsToEmit.push_back(DDI->second); 843 DeferredDecls.erase(DDI); 844 } 845 846 llvm::GlobalVariable *GV = 847 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 848 llvm::GlobalValue::ExternalLinkage, 849 0, "", 0, 850 false, Ty->getAddressSpace()); 851 GV->setName(MangledName); 852 853 // Handle things which are present even on external declarations. 854 if (D) { 855 // FIXME: This code is overly simple and should be merged with other global 856 // handling. 857 GV->setConstant(D->getType().isConstant(Context)); 858 859 // FIXME: Merge with other attribute handling code. 860 if (D->getStorageClass() == VarDecl::PrivateExtern) 861 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 862 863 if (D->hasAttr<WeakAttr>() || 864 D->hasAttr<WeakImportAttr>()) 865 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 866 867 GV->setThreadLocal(D->isThreadSpecified()); 868 } 869 870 return Entry = GV; 871 } 872 873 874 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 875 /// given global variable. If Ty is non-null and if the global doesn't exist, 876 /// then it will be greated with the specified type instead of whatever the 877 /// normal requested type would be. 878 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 879 const llvm::Type *Ty) { 880 assert(D->hasGlobalStorage() && "Not a global variable"); 881 QualType ASTTy = D->getType(); 882 if (Ty == 0) 883 Ty = getTypes().ConvertTypeForMem(ASTTy); 884 885 const llvm::PointerType *PTy = 886 llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 887 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D); 888 } 889 890 /// CreateRuntimeVariable - Create a new runtime global variable with the 891 /// specified type and name. 892 llvm::Constant * 893 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 894 const char *Name) { 895 // Convert Name to be a uniqued string from the IdentifierInfo table. 896 Name = getContext().Idents.get(Name).getName(); 897 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0); 898 } 899 900 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 901 assert(!D->getInit() && "Cannot emit definite definitions here!"); 902 903 if (MayDeferGeneration(D)) { 904 // If we have not seen a reference to this variable yet, place it 905 // into the deferred declarations table to be emitted if needed 906 // later. 907 const char *MangledName = getMangledName(D); 908 if (GlobalDeclMap.count(MangledName) == 0) { 909 DeferredDecls[MangledName] = D; 910 return; 911 } 912 } 913 914 // The tentative definition is the only definition. 915 EmitGlobalVarDefinition(D); 916 } 917 918 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 919 llvm::Constant *Init = 0; 920 QualType ASTTy = D->getType(); 921 922 if (D->getInit() == 0) { 923 // This is a tentative definition; tentative definitions are 924 // implicitly initialized with { 0 }. 925 // 926 // Note that tentative definitions are only emitted at the end of 927 // a translation unit, so they should never have incomplete 928 // type. In addition, EmitTentativeDefinition makes sure that we 929 // never attempt to emit a tentative definition if a real one 930 // exists. A use may still exists, however, so we still may need 931 // to do a RAUW. 932 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 933 Init = EmitNullConstant(D->getType()); 934 } else { 935 Init = EmitConstantExpr(D->getInit(), D->getType()); 936 937 if (!Init) { 938 QualType T = D->getInit()->getType(); 939 if (getLangOptions().CPlusPlus) { 940 CXXGlobalInits.push_back(D); 941 Init = EmitNullConstant(T); 942 } else { 943 ErrorUnsupported(D, "static initializer"); 944 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 945 } 946 } 947 } 948 949 const llvm::Type* InitType = Init->getType(); 950 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 951 952 // Strip off a bitcast if we got one back. 953 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 954 assert(CE->getOpcode() == llvm::Instruction::BitCast || 955 // all zero index gep. 956 CE->getOpcode() == llvm::Instruction::GetElementPtr); 957 Entry = CE->getOperand(0); 958 } 959 960 // Entry is now either a Function or GlobalVariable. 961 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 962 963 // We have a definition after a declaration with the wrong type. 964 // We must make a new GlobalVariable* and update everything that used OldGV 965 // (a declaration or tentative definition) with the new GlobalVariable* 966 // (which will be a definition). 967 // 968 // This happens if there is a prototype for a global (e.g. 969 // "extern int x[];") and then a definition of a different type (e.g. 970 // "int x[10];"). This also happens when an initializer has a different type 971 // from the type of the global (this happens with unions). 972 if (GV == 0 || 973 GV->getType()->getElementType() != InitType || 974 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 975 976 // Remove the old entry from GlobalDeclMap so that we'll create a new one. 977 GlobalDeclMap.erase(getMangledName(D)); 978 979 // Make a new global with the correct type, this is now guaranteed to work. 980 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 981 GV->takeName(cast<llvm::GlobalValue>(Entry)); 982 983 // Replace all uses of the old global with the new global 984 llvm::Constant *NewPtrForOldDecl = 985 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 986 Entry->replaceAllUsesWith(NewPtrForOldDecl); 987 988 // Erase the old global, since it is no longer used. 989 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 990 } 991 992 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 993 SourceManager &SM = Context.getSourceManager(); 994 AddAnnotation(EmitAnnotateAttr(GV, AA, 995 SM.getInstantiationLineNumber(D->getLocation()))); 996 } 997 998 GV->setInitializer(Init); 999 1000 // If it is safe to mark the global 'constant', do so now. 1001 GV->setConstant(false); 1002 if (D->getType().isConstant(Context)) { 1003 // FIXME: In C++, if the variable has a non-trivial ctor/dtor or any mutable 1004 // members, it cannot be declared "LLVM const". 1005 GV->setConstant(true); 1006 } 1007 1008 GV->setAlignment(getContext().getDeclAlignInBytes(D)); 1009 1010 // Set the llvm linkage type as appropriate. 1011 if (D->isInAnonymousNamespace()) 1012 GV->setLinkage(llvm::Function::InternalLinkage); 1013 else if (D->getStorageClass() == VarDecl::Static) 1014 GV->setLinkage(llvm::Function::InternalLinkage); 1015 else if (D->hasAttr<DLLImportAttr>()) 1016 GV->setLinkage(llvm::Function::DLLImportLinkage); 1017 else if (D->hasAttr<DLLExportAttr>()) 1018 GV->setLinkage(llvm::Function::DLLExportLinkage); 1019 else if (D->hasAttr<WeakAttr>()) { 1020 if (GV->isConstant()) 1021 GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage); 1022 else 1023 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1024 } else if (!CompileOpts.NoCommon && 1025 !D->hasExternalStorage() && !D->getInit() && 1026 !D->getAttr<SectionAttr>()) { 1027 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 1028 // common vars aren't constant even if declared const. 1029 GV->setConstant(false); 1030 } else 1031 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 1032 1033 SetCommonAttributes(D, GV); 1034 1035 // Emit global variable debug information. 1036 if (CGDebugInfo *DI = getDebugInfo()) { 1037 DI->setLocation(D->getLocation()); 1038 DI->EmitGlobalVariable(GV, D); 1039 } 1040 } 1041 1042 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1043 /// implement a function with no prototype, e.g. "int foo() {}". If there are 1044 /// existing call uses of the old function in the module, this adjusts them to 1045 /// call the new function directly. 1046 /// 1047 /// This is not just a cleanup: the always_inline pass requires direct calls to 1048 /// functions to be able to inline them. If there is a bitcast in the way, it 1049 /// won't inline them. Instcombine normally deletes these calls, but it isn't 1050 /// run at -O0. 1051 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1052 llvm::Function *NewFn) { 1053 // If we're redefining a global as a function, don't transform it. 1054 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1055 if (OldFn == 0) return; 1056 1057 const llvm::Type *NewRetTy = NewFn->getReturnType(); 1058 llvm::SmallVector<llvm::Value*, 4> ArgList; 1059 1060 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1061 UI != E; ) { 1062 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1063 unsigned OpNo = UI.getOperandNo(); 1064 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++); 1065 if (!CI || OpNo != 0) continue; 1066 1067 // If the return types don't match exactly, and if the call isn't dead, then 1068 // we can't transform this call. 1069 if (CI->getType() != NewRetTy && !CI->use_empty()) 1070 continue; 1071 1072 // If the function was passed too few arguments, don't transform. If extra 1073 // arguments were passed, we silently drop them. If any of the types 1074 // mismatch, we don't transform. 1075 unsigned ArgNo = 0; 1076 bool DontTransform = false; 1077 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1078 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1079 if (CI->getNumOperands()-1 == ArgNo || 1080 CI->getOperand(ArgNo+1)->getType() != AI->getType()) { 1081 DontTransform = true; 1082 break; 1083 } 1084 } 1085 if (DontTransform) 1086 continue; 1087 1088 // Okay, we can transform this. Create the new call instruction and copy 1089 // over the required information. 1090 ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo); 1091 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(), 1092 ArgList.end(), "", CI); 1093 ArgList.clear(); 1094 if (!NewCall->getType()->isVoidTy()) 1095 NewCall->takeName(CI); 1096 NewCall->setAttributes(CI->getAttributes()); 1097 NewCall->setCallingConv(CI->getCallingConv()); 1098 1099 // Finally, remove the old call, replacing any uses with the new one. 1100 if (!CI->use_empty()) 1101 CI->replaceAllUsesWith(NewCall); 1102 CI->eraseFromParent(); 1103 } 1104 } 1105 1106 1107 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1108 const llvm::FunctionType *Ty; 1109 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1110 1111 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 1112 bool isVariadic = D->getType()->getAs<FunctionProtoType>()->isVariadic(); 1113 1114 Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic); 1115 } else { 1116 Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType())); 1117 1118 // As a special case, make sure that definitions of K&R function 1119 // "type foo()" aren't declared as varargs (which forces the backend 1120 // to do unnecessary work). 1121 if (D->getType()->isFunctionNoProtoType()) { 1122 assert(Ty->isVarArg() && "Didn't lower type as expected"); 1123 // Due to stret, the lowered function could have arguments. 1124 // Just create the same type as was lowered by ConvertType 1125 // but strip off the varargs bit. 1126 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end()); 1127 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false); 1128 } 1129 } 1130 1131 // Get or create the prototype for the function. 1132 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1133 1134 // Strip off a bitcast if we got one back. 1135 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1136 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1137 Entry = CE->getOperand(0); 1138 } 1139 1140 1141 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1142 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1143 1144 // If the types mismatch then we have to rewrite the definition. 1145 assert(OldFn->isDeclaration() && 1146 "Shouldn't replace non-declaration"); 1147 1148 // F is the Function* for the one with the wrong type, we must make a new 1149 // Function* and update everything that used F (a declaration) with the new 1150 // Function* (which will be a definition). 1151 // 1152 // This happens if there is a prototype for a function 1153 // (e.g. "int f()") and then a definition of a different type 1154 // (e.g. "int f(int x)"). Start by making a new function of the 1155 // correct type, RAUW, then steal the name. 1156 GlobalDeclMap.erase(getMangledName(D)); 1157 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1158 NewFn->takeName(OldFn); 1159 1160 // If this is an implementation of a function without a prototype, try to 1161 // replace any existing uses of the function (which may be calls) with uses 1162 // of the new function 1163 if (D->getType()->isFunctionNoProtoType()) { 1164 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1165 OldFn->removeDeadConstantUsers(); 1166 } 1167 1168 // Replace uses of F with the Function we will endow with a body. 1169 if (!Entry->use_empty()) { 1170 llvm::Constant *NewPtrForOldDecl = 1171 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1172 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1173 } 1174 1175 // Ok, delete the old function now, which is dead. 1176 OldFn->eraseFromParent(); 1177 1178 Entry = NewFn; 1179 } 1180 1181 llvm::Function *Fn = cast<llvm::Function>(Entry); 1182 1183 CodeGenFunction(*this).GenerateCode(D, Fn); 1184 1185 SetFunctionDefinitionAttributes(D, Fn); 1186 SetLLVMFunctionAttributesForDefinition(D, Fn); 1187 1188 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1189 AddGlobalCtor(Fn, CA->getPriority()); 1190 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1191 AddGlobalDtor(Fn, DA->getPriority()); 1192 } 1193 1194 void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) { 1195 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1196 assert(AA && "Not an alias?"); 1197 1198 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1199 1200 // Unique the name through the identifier table. 1201 const char *AliaseeName = AA->getAliasee().c_str(); 1202 AliaseeName = getContext().Idents.get(AliaseeName).getName(); 1203 1204 // Create a reference to the named value. This ensures that it is emitted 1205 // if a deferred decl. 1206 llvm::Constant *Aliasee; 1207 if (isa<llvm::FunctionType>(DeclTy)) 1208 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl()); 1209 else 1210 Aliasee = GetOrCreateLLVMGlobal(AliaseeName, 1211 llvm::PointerType::getUnqual(DeclTy), 0); 1212 1213 // Create the new alias itself, but don't set a name yet. 1214 llvm::GlobalValue *GA = 1215 new llvm::GlobalAlias(Aliasee->getType(), 1216 llvm::Function::ExternalLinkage, 1217 "", Aliasee, &getModule()); 1218 1219 // See if there is already something with the alias' name in the module. 1220 const char *MangledName = getMangledName(D); 1221 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 1222 1223 if (Entry && !Entry->isDeclaration()) { 1224 // If there is a definition in the module, then it wins over the alias. 1225 // This is dubious, but allow it to be safe. Just ignore the alias. 1226 GA->eraseFromParent(); 1227 return; 1228 } 1229 1230 if (Entry) { 1231 // If there is a declaration in the module, then we had an extern followed 1232 // by the alias, as in: 1233 // extern int test6(); 1234 // ... 1235 // int test6() __attribute__((alias("test7"))); 1236 // 1237 // Remove it and replace uses of it with the alias. 1238 1239 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1240 Entry->getType())); 1241 Entry->eraseFromParent(); 1242 } 1243 1244 // Now we know that there is no conflict, set the name. 1245 Entry = GA; 1246 GA->setName(MangledName); 1247 1248 // Set attributes which are particular to an alias; this is a 1249 // specialization of the attributes which may be set on a global 1250 // variable/function. 1251 if (D->hasAttr<DLLExportAttr>()) { 1252 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1253 // The dllexport attribute is ignored for undefined symbols. 1254 if (FD->getBody()) 1255 GA->setLinkage(llvm::Function::DLLExportLinkage); 1256 } else { 1257 GA->setLinkage(llvm::Function::DLLExportLinkage); 1258 } 1259 } else if (D->hasAttr<WeakAttr>() || 1260 D->hasAttr<WeakImportAttr>()) { 1261 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1262 } 1263 1264 SetCommonAttributes(D, GA); 1265 } 1266 1267 /// getBuiltinLibFunction - Given a builtin id for a function like 1268 /// "__builtin_fabsf", return a Function* for "fabsf". 1269 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD, 1270 unsigned BuiltinID) { 1271 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 1272 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 1273 "isn't a lib fn"); 1274 1275 // Get the name, skip over the __builtin_ prefix (if necessary). 1276 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 1277 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 1278 Name += 10; 1279 1280 // Get the type for the builtin. 1281 ASTContext::GetBuiltinTypeError Error; 1282 QualType Type = Context.GetBuiltinType(BuiltinID, Error); 1283 assert(Error == ASTContext::GE_None && "Can't get builtin type"); 1284 1285 const llvm::FunctionType *Ty = 1286 cast<llvm::FunctionType>(getTypes().ConvertType(Type)); 1287 1288 // Unique the name through the identifier table. 1289 Name = getContext().Idents.get(Name).getName(); 1290 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD)); 1291 } 1292 1293 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 1294 unsigned NumTys) { 1295 return llvm::Intrinsic::getDeclaration(&getModule(), 1296 (llvm::Intrinsic::ID)IID, Tys, NumTys); 1297 } 1298 1299 llvm::Function *CodeGenModule::getMemCpyFn() { 1300 if (MemCpyFn) return MemCpyFn; 1301 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1302 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1); 1303 } 1304 1305 llvm::Function *CodeGenModule::getMemMoveFn() { 1306 if (MemMoveFn) return MemMoveFn; 1307 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1308 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1); 1309 } 1310 1311 llvm::Function *CodeGenModule::getMemSetFn() { 1312 if (MemSetFn) return MemSetFn; 1313 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext); 1314 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1); 1315 } 1316 1317 static llvm::StringMapEntry<llvm::Constant*> & 1318 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1319 const StringLiteral *Literal, 1320 bool TargetIsLSB, 1321 bool &IsUTF16, 1322 unsigned &StringLength) { 1323 unsigned NumBytes = Literal->getByteLength(); 1324 1325 // Check for simple case. 1326 if (!Literal->containsNonAsciiOrNull()) { 1327 StringLength = NumBytes; 1328 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1329 StringLength)); 1330 } 1331 1332 // Otherwise, convert the UTF8 literals into a byte string. 1333 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 1334 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData(); 1335 UTF16 *ToPtr = &ToBuf[0]; 1336 1337 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1338 &ToPtr, ToPtr + NumBytes, 1339 strictConversion); 1340 1341 // Check for conversion failure. 1342 if (Result != conversionOK) { 1343 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove 1344 // this duplicate code. 1345 assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed"); 1346 StringLength = NumBytes; 1347 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(), 1348 StringLength)); 1349 } 1350 1351 // ConvertUTF8toUTF16 returns the length in ToPtr. 1352 StringLength = ToPtr - &ToBuf[0]; 1353 1354 // Render the UTF-16 string into a byte array and convert to the target byte 1355 // order. 1356 // 1357 // FIXME: This isn't something we should need to do here. 1358 llvm::SmallString<128> AsBytes; 1359 AsBytes.reserve(StringLength * 2); 1360 for (unsigned i = 0; i != StringLength; ++i) { 1361 unsigned short Val = ToBuf[i]; 1362 if (TargetIsLSB) { 1363 AsBytes.push_back(Val & 0xFF); 1364 AsBytes.push_back(Val >> 8); 1365 } else { 1366 AsBytes.push_back(Val >> 8); 1367 AsBytes.push_back(Val & 0xFF); 1368 } 1369 } 1370 // Append one extra null character, the second is automatically added by our 1371 // caller. 1372 AsBytes.push_back(0); 1373 1374 IsUTF16 = true; 1375 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size())); 1376 } 1377 1378 llvm::Constant * 1379 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1380 unsigned StringLength = 0; 1381 bool isUTF16 = false; 1382 llvm::StringMapEntry<llvm::Constant*> &Entry = 1383 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1384 getTargetData().isLittleEndian(), 1385 isUTF16, StringLength); 1386 1387 if (llvm::Constant *C = Entry.getValue()) 1388 return C; 1389 1390 llvm::Constant *Zero = 1391 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1392 llvm::Constant *Zeros[] = { Zero, Zero }; 1393 1394 // If we don't already have it, get __CFConstantStringClassReference. 1395 if (!CFConstantStringClassRef) { 1396 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1397 Ty = llvm::ArrayType::get(Ty, 0); 1398 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1399 "__CFConstantStringClassReference"); 1400 // Decay array -> ptr 1401 CFConstantStringClassRef = 1402 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1403 } 1404 1405 QualType CFTy = getContext().getCFConstantStringType(); 1406 1407 const llvm::StructType *STy = 1408 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1409 1410 std::vector<llvm::Constant*> Fields(4); 1411 1412 // Class pointer. 1413 Fields[0] = CFConstantStringClassRef; 1414 1415 // Flags. 1416 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1417 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1418 llvm::ConstantInt::get(Ty, 0x07C8); 1419 1420 // String pointer. 1421 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1422 1423 const char *Sect, *Prefix; 1424 bool isConstant; 1425 llvm::GlobalValue::LinkageTypes Linkage; 1426 if (isUTF16) { 1427 Prefix = getContext().Target.getUnicodeStringSymbolPrefix(); 1428 Sect = getContext().Target.getUnicodeStringSection(); 1429 // FIXME: why do utf strings get "l" labels instead of "L" labels? 1430 Linkage = llvm::GlobalValue::InternalLinkage; 1431 // FIXME: Why does GCC not set constant here? 1432 isConstant = false; 1433 } else { 1434 Prefix = ".str"; 1435 Sect = getContext().Target.getCFStringDataSection(); 1436 Linkage = llvm::GlobalValue::PrivateLinkage; 1437 // FIXME: -fwritable-strings should probably affect this, but we 1438 // are following gcc here. 1439 isConstant = true; 1440 } 1441 llvm::GlobalVariable *GV = 1442 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, 1443 Linkage, C, Prefix); 1444 if (Sect) 1445 GV->setSection(Sect); 1446 if (isUTF16) { 1447 unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8; 1448 GV->setAlignment(Align); 1449 } 1450 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1451 1452 // String length. 1453 Ty = getTypes().ConvertType(getContext().LongTy); 1454 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1455 1456 // The struct. 1457 C = llvm::ConstantStruct::get(STy, Fields); 1458 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1459 llvm::GlobalVariable::PrivateLinkage, C, 1460 "_unnamed_cfstring_"); 1461 if (const char *Sect = getContext().Target.getCFStringSection()) 1462 GV->setSection(Sect); 1463 Entry.setValue(GV); 1464 1465 return GV; 1466 } 1467 1468 /// GetStringForStringLiteral - Return the appropriate bytes for a 1469 /// string literal, properly padded to match the literal type. 1470 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1471 const char *StrData = E->getStrData(); 1472 unsigned Len = E->getByteLength(); 1473 1474 const ConstantArrayType *CAT = 1475 getContext().getAsConstantArrayType(E->getType()); 1476 assert(CAT && "String isn't pointer or array!"); 1477 1478 // Resize the string to the right size. 1479 std::string Str(StrData, StrData+Len); 1480 uint64_t RealLen = CAT->getSize().getZExtValue(); 1481 1482 if (E->isWide()) 1483 RealLen *= getContext().Target.getWCharWidth()/8; 1484 1485 Str.resize(RealLen, '\0'); 1486 1487 return Str; 1488 } 1489 1490 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1491 /// constant array for the given string literal. 1492 llvm::Constant * 1493 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1494 // FIXME: This can be more efficient. 1495 return GetAddrOfConstantString(GetStringForStringLiteral(S)); 1496 } 1497 1498 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1499 /// array for the given ObjCEncodeExpr node. 1500 llvm::Constant * 1501 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1502 std::string Str; 1503 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1504 1505 return GetAddrOfConstantCString(Str); 1506 } 1507 1508 1509 /// GenerateWritableString -- Creates storage for a string literal. 1510 static llvm::Constant *GenerateStringLiteral(const std::string &str, 1511 bool constant, 1512 CodeGenModule &CGM, 1513 const char *GlobalName) { 1514 // Create Constant for this string literal. Don't add a '\0'. 1515 llvm::Constant *C = 1516 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 1517 1518 // Create a global variable for this string 1519 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 1520 llvm::GlobalValue::PrivateLinkage, 1521 C, GlobalName); 1522 } 1523 1524 /// GetAddrOfConstantString - Returns a pointer to a character array 1525 /// containing the literal. This contents are exactly that of the 1526 /// given string, i.e. it will not be null terminated automatically; 1527 /// see GetAddrOfConstantCString. Note that whether the result is 1528 /// actually a pointer to an LLVM constant depends on 1529 /// Feature.WriteableStrings. 1530 /// 1531 /// The result has pointer to array type. 1532 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1533 const char *GlobalName) { 1534 bool IsConstant = !Features.WritableStrings; 1535 1536 // Get the default prefix if a name wasn't specified. 1537 if (!GlobalName) 1538 GlobalName = ".str"; 1539 1540 // Don't share any string literals if strings aren't constant. 1541 if (!IsConstant) 1542 return GenerateStringLiteral(str, false, *this, GlobalName); 1543 1544 llvm::StringMapEntry<llvm::Constant *> &Entry = 1545 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1546 1547 if (Entry.getValue()) 1548 return Entry.getValue(); 1549 1550 // Create a global variable for this. 1551 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1552 Entry.setValue(C); 1553 return C; 1554 } 1555 1556 /// GetAddrOfConstantCString - Returns a pointer to a character 1557 /// array containing the literal and a terminating '\-' 1558 /// character. The result has pointer to array type. 1559 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1560 const char *GlobalName){ 1561 return GetAddrOfConstantString(str + '\0', GlobalName); 1562 } 1563 1564 /// EmitObjCPropertyImplementations - Emit information for synthesized 1565 /// properties for an implementation. 1566 void CodeGenModule::EmitObjCPropertyImplementations(const 1567 ObjCImplementationDecl *D) { 1568 for (ObjCImplementationDecl::propimpl_iterator 1569 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 1570 ObjCPropertyImplDecl *PID = *i; 1571 1572 // Dynamic is just for type-checking. 1573 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1574 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1575 1576 // Determine which methods need to be implemented, some may have 1577 // been overridden. Note that ::isSynthesized is not the method 1578 // we want, that just indicates if the decl came from a 1579 // property. What we want to know is if the method is defined in 1580 // this implementation. 1581 if (!D->getInstanceMethod(PD->getGetterName())) 1582 CodeGenFunction(*this).GenerateObjCGetter( 1583 const_cast<ObjCImplementationDecl *>(D), PID); 1584 if (!PD->isReadOnly() && 1585 !D->getInstanceMethod(PD->getSetterName())) 1586 CodeGenFunction(*this).GenerateObjCSetter( 1587 const_cast<ObjCImplementationDecl *>(D), PID); 1588 } 1589 } 1590 } 1591 1592 /// EmitNamespace - Emit all declarations in a namespace. 1593 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 1594 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 1595 I != E; ++I) 1596 EmitTopLevelDecl(*I); 1597 } 1598 1599 // EmitLinkageSpec - Emit all declarations in a linkage spec. 1600 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 1601 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 1602 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 1603 ErrorUnsupported(LSD, "linkage spec"); 1604 return; 1605 } 1606 1607 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 1608 I != E; ++I) 1609 EmitTopLevelDecl(*I); 1610 } 1611 1612 /// EmitTopLevelDecl - Emit code for a single top level declaration. 1613 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1614 // If an error has occurred, stop code generation, but continue 1615 // parsing and semantic analysis (to ensure all warnings and errors 1616 // are emitted). 1617 if (Diags.hasErrorOccurred()) 1618 return; 1619 1620 // Ignore dependent declarations. 1621 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 1622 return; 1623 1624 switch (D->getKind()) { 1625 case Decl::CXXConversion: 1626 case Decl::CXXMethod: 1627 case Decl::Function: 1628 // Skip function templates 1629 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1630 return; 1631 1632 EmitGlobal(cast<FunctionDecl>(D)); 1633 break; 1634 1635 case Decl::Var: 1636 EmitGlobal(cast<VarDecl>(D)); 1637 break; 1638 1639 // C++ Decls 1640 case Decl::Namespace: 1641 EmitNamespace(cast<NamespaceDecl>(D)); 1642 break; 1643 // No code generation needed. 1644 case Decl::Using: 1645 case Decl::UsingDirective: 1646 case Decl::ClassTemplate: 1647 case Decl::FunctionTemplate: 1648 case Decl::NamespaceAlias: 1649 break; 1650 case Decl::CXXConstructor: 1651 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 1652 break; 1653 case Decl::CXXDestructor: 1654 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 1655 break; 1656 1657 case Decl::StaticAssert: 1658 // Nothing to do. 1659 break; 1660 1661 // Objective-C Decls 1662 1663 // Forward declarations, no (immediate) code generation. 1664 case Decl::ObjCClass: 1665 case Decl::ObjCForwardProtocol: 1666 case Decl::ObjCCategory: 1667 case Decl::ObjCInterface: 1668 break; 1669 1670 case Decl::ObjCProtocol: 1671 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 1672 break; 1673 1674 case Decl::ObjCCategoryImpl: 1675 // Categories have properties but don't support synthesize so we 1676 // can ignore them here. 1677 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 1678 break; 1679 1680 case Decl::ObjCImplementation: { 1681 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 1682 EmitObjCPropertyImplementations(OMD); 1683 Runtime->GenerateClass(OMD); 1684 break; 1685 } 1686 case Decl::ObjCMethod: { 1687 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 1688 // If this is not a prototype, emit the body. 1689 if (OMD->getBody()) 1690 CodeGenFunction(*this).GenerateObjCMethod(OMD); 1691 break; 1692 } 1693 case Decl::ObjCCompatibleAlias: 1694 // compatibility-alias is a directive and has no code gen. 1695 break; 1696 1697 case Decl::LinkageSpec: 1698 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 1699 break; 1700 1701 case Decl::FileScopeAsm: { 1702 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 1703 std::string AsmString(AD->getAsmString()->getStrData(), 1704 AD->getAsmString()->getByteLength()); 1705 1706 const std::string &S = getModule().getModuleInlineAsm(); 1707 if (S.empty()) 1708 getModule().setModuleInlineAsm(AsmString); 1709 else 1710 getModule().setModuleInlineAsm(S + '\n' + AsmString); 1711 break; 1712 } 1713 1714 default: 1715 // Make sure we handled everything we should, every other kind is a 1716 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 1717 // function. Need to recode Decl::Kind to do that easily. 1718 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 1719 } 1720 } 1721