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 "CodeGenTBAA.h" 18 #include "CGCall.h" 19 #include "CGCXXABI.h" 20 #include "CGObjCRuntime.h" 21 #include "TargetInfo.h" 22 #include "clang/Frontend/CodeGenOptions.h" 23 #include "clang/AST/ASTContext.h" 24 #include "clang/AST/CharUnits.h" 25 #include "clang/AST/DeclObjC.h" 26 #include "clang/AST/DeclCXX.h" 27 #include "clang/AST/DeclTemplate.h" 28 #include "clang/AST/Mangle.h" 29 #include "clang/AST/RecordLayout.h" 30 #include "clang/Basic/Builtins.h" 31 #include "clang/Basic/Diagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Basic/ConvertUTF.h" 35 #include "llvm/CallingConv.h" 36 #include "llvm/Module.h" 37 #include "llvm/Intrinsics.h" 38 #include "llvm/LLVMContext.h" 39 #include "llvm/ADT/Triple.h" 40 #include "llvm/Target/Mangler.h" 41 #include "llvm/Target/TargetData.h" 42 #include "llvm/Support/CallSite.h" 43 #include "llvm/Support/ErrorHandling.h" 44 using namespace clang; 45 using namespace CodeGen; 46 47 static CGCXXABI &createCXXABI(CodeGenModule &CGM) { 48 switch (CGM.getContext().Target.getCXXABI()) { 49 case CXXABI_ARM: return *CreateARMCXXABI(CGM); 50 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM); 51 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM); 52 } 53 54 llvm_unreachable("invalid C++ ABI kind"); 55 return *CreateItaniumCXXABI(CGM); 56 } 57 58 59 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 60 llvm::Module &M, const llvm::TargetData &TD, 61 Diagnostic &diags) 62 : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M), 63 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags), 64 ABI(createCXXABI(*this)), 65 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI), 66 TBAA(0), 67 VTables(*this), Runtime(0), 68 CFConstantStringClassRef(0), ConstantStringClassRef(0), 69 VMContext(M.getContext()), 70 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0), 71 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), 72 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0), 73 BlockObjectAssign(0), BlockObjectDispose(0), 74 BlockDescriptorType(0), GenericBlockLiteralType(0) { 75 if (!Features.ObjC1) 76 Runtime = 0; 77 else if (!Features.NeXTRuntime) 78 Runtime = CreateGNUObjCRuntime(*this); 79 else if (Features.ObjCNonFragileABI) 80 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 81 else 82 Runtime = CreateMacObjCRuntime(*this); 83 84 // Enable TBAA unless it's suppressed. 85 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0) 86 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(), 87 ABI.getMangleContext()); 88 89 // If debug info generation is enabled, create the CGDebugInfo object. 90 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0; 91 92 Block.GlobalUniqueCount = 0; 93 Int8PtrTy = llvm::Type::getInt8PtrTy(M.getContext()); 94 } 95 96 CodeGenModule::~CodeGenModule() { 97 delete Runtime; 98 delete &ABI; 99 delete TBAA; 100 delete DebugInfo; 101 } 102 103 void CodeGenModule::createObjCRuntime() { 104 if (!Features.NeXTRuntime) 105 Runtime = CreateGNUObjCRuntime(*this); 106 else if (Features.ObjCNonFragileABI) 107 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 108 else 109 Runtime = CreateMacObjCRuntime(*this); 110 } 111 112 void CodeGenModule::Release() { 113 EmitDeferred(); 114 EmitCXXGlobalInitFunc(); 115 EmitCXXGlobalDtorFunc(); 116 if (Runtime) 117 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 118 AddGlobalCtor(ObjCInitFunction); 119 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 120 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 121 EmitAnnotations(); 122 EmitLLVMUsed(); 123 124 SimplifyPersonality(); 125 126 if (getCodeGenOpts().EmitDeclMetadata) 127 EmitDeclMetadata(); 128 } 129 130 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 131 if (!TBAA) 132 return 0; 133 return TBAA->getTBAAInfo(QTy); 134 } 135 136 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 137 llvm::MDNode *TBAAInfo) { 138 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 139 } 140 141 bool CodeGenModule::isTargetDarwin() const { 142 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin; 143 } 144 145 /// ErrorUnsupported - Print out an error that codegen doesn't support the 146 /// specified stmt yet. 147 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 148 bool OmitOnError) { 149 if (OmitOnError && getDiags().hasErrorOccurred()) 150 return; 151 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 152 "cannot compile this %0 yet"); 153 std::string Msg = Type; 154 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 155 << Msg << S->getSourceRange(); 156 } 157 158 /// ErrorUnsupported - Print out an error that codegen doesn't support the 159 /// specified decl yet. 160 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 161 bool OmitOnError) { 162 if (OmitOnError && getDiags().hasErrorOccurred()) 163 return; 164 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 165 "cannot compile this %0 yet"); 166 std::string Msg = Type; 167 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 168 } 169 170 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 171 const NamedDecl *D) const { 172 // Internal definitions always have default visibility. 173 if (GV->hasLocalLinkage()) { 174 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 175 return; 176 } 177 178 // Set visibility for definitions. 179 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility(); 180 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 181 GV->setVisibility(GetLLVMVisibility(LV.visibility())); 182 } 183 184 /// Set the symbol visibility of type information (vtable and RTTI) 185 /// associated with the given type. 186 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV, 187 const CXXRecordDecl *RD, 188 TypeVisibilityKind TVK) const { 189 setGlobalVisibility(GV, RD); 190 191 if (!CodeGenOpts.HiddenWeakVTables) 192 return; 193 194 // We never want to drop the visibility for RTTI names. 195 if (TVK == TVK_ForRTTIName) 196 return; 197 198 // We want to drop the visibility to hidden for weak type symbols. 199 // This isn't possible if there might be unresolved references 200 // elsewhere that rely on this symbol being visible. 201 202 // This should be kept roughly in sync with setThunkVisibility 203 // in CGVTables.cpp. 204 205 // Preconditions. 206 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage || 207 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility) 208 return; 209 210 // Don't override an explicit visibility attribute. 211 if (RD->hasAttr<VisibilityAttr>()) 212 return; 213 214 switch (RD->getTemplateSpecializationKind()) { 215 // We have to disable the optimization if this is an EI definition 216 // because there might be EI declarations in other shared objects. 217 case TSK_ExplicitInstantiationDefinition: 218 case TSK_ExplicitInstantiationDeclaration: 219 return; 220 221 // Every use of a non-template class's type information has to emit it. 222 case TSK_Undeclared: 223 break; 224 225 // In theory, implicit instantiations can ignore the possibility of 226 // an explicit instantiation declaration because there necessarily 227 // must be an EI definition somewhere with default visibility. In 228 // practice, it's possible to have an explicit instantiation for 229 // an arbitrary template class, and linkers aren't necessarily able 230 // to deal with mixed-visibility symbols. 231 case TSK_ExplicitSpecialization: 232 case TSK_ImplicitInstantiation: 233 if (!CodeGenOpts.HiddenWeakTemplateVTables) 234 return; 235 break; 236 } 237 238 // If there's a key function, there may be translation units 239 // that don't have the key function's definition. But ignore 240 // this if we're emitting RTTI under -fno-rtti. 241 if (!(TVK != TVK_ForRTTI) || Features.RTTI) { 242 if (Context.getKeyFunction(RD)) 243 return; 244 } 245 246 // Otherwise, drop the visibility to hidden. 247 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 248 GV->setUnnamedAddr(true); 249 } 250 251 llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 252 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 253 254 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 255 if (!Str.empty()) 256 return Str; 257 258 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 259 IdentifierInfo *II = ND->getIdentifier(); 260 assert(II && "Attempt to mangle unnamed decl."); 261 262 Str = II->getName(); 263 return Str; 264 } 265 266 llvm::SmallString<256> Buffer; 267 llvm::raw_svector_ostream Out(Buffer); 268 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 269 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 270 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 271 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 272 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND)) 273 getCXXABI().getMangleContext().mangleBlock(BD, Out); 274 else 275 getCXXABI().getMangleContext().mangleName(ND, Out); 276 277 // Allocate space for the mangled name. 278 Out.flush(); 279 size_t Length = Buffer.size(); 280 char *Name = MangledNamesAllocator.Allocate<char>(Length); 281 std::copy(Buffer.begin(), Buffer.end(), Name); 282 283 Str = llvm::StringRef(Name, Length); 284 285 return Str; 286 } 287 288 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 289 const BlockDecl *BD) { 290 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 291 const Decl *D = GD.getDecl(); 292 llvm::raw_svector_ostream Out(Buffer.getBuffer()); 293 if (D == 0) 294 MangleCtx.mangleGlobalBlock(BD, Out); 295 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 296 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 297 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 298 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 299 else 300 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 301 } 302 303 llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) { 304 return getModule().getNamedValue(Name); 305 } 306 307 /// AddGlobalCtor - Add a function to the list that will be called before 308 /// main() runs. 309 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 310 // FIXME: Type coercion of void()* types. 311 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 312 } 313 314 /// AddGlobalDtor - Add a function to the list that will be called 315 /// when the module is unloaded. 316 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 317 // FIXME: Type coercion of void()* types. 318 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 319 } 320 321 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 322 // Ctor function type is void()*. 323 llvm::FunctionType* CtorFTy = 324 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false); 325 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 326 327 // Get the type of a ctor entry, { i32, void ()* }. 328 llvm::StructType* CtorStructTy = 329 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext), 330 llvm::PointerType::getUnqual(CtorFTy), NULL); 331 332 // Construct the constructor and destructor arrays. 333 std::vector<llvm::Constant*> Ctors; 334 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 335 std::vector<llvm::Constant*> S; 336 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 337 I->second, false)); 338 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 339 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 340 } 341 342 if (!Ctors.empty()) { 343 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 344 new llvm::GlobalVariable(TheModule, AT, false, 345 llvm::GlobalValue::AppendingLinkage, 346 llvm::ConstantArray::get(AT, Ctors), 347 GlobalName); 348 } 349 } 350 351 void CodeGenModule::EmitAnnotations() { 352 if (Annotations.empty()) 353 return; 354 355 // Create a new global variable for the ConstantStruct in the Module. 356 llvm::Constant *Array = 357 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 358 Annotations.size()), 359 Annotations); 360 llvm::GlobalValue *gv = 361 new llvm::GlobalVariable(TheModule, Array->getType(), false, 362 llvm::GlobalValue::AppendingLinkage, Array, 363 "llvm.global.annotations"); 364 gv->setSection("llvm.metadata"); 365 } 366 367 llvm::GlobalValue::LinkageTypes 368 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) { 369 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 370 371 if (Linkage == GVA_Internal) 372 return llvm::Function::InternalLinkage; 373 374 if (D->hasAttr<DLLExportAttr>()) 375 return llvm::Function::DLLExportLinkage; 376 377 if (D->hasAttr<WeakAttr>()) 378 return llvm::Function::WeakAnyLinkage; 379 380 // In C99 mode, 'inline' functions are guaranteed to have a strong 381 // definition somewhere else, so we can use available_externally linkage. 382 if (Linkage == GVA_C99Inline) 383 return llvm::Function::AvailableExternallyLinkage; 384 385 // In C++, the compiler has to emit a definition in every translation unit 386 // that references the function. We should use linkonce_odr because 387 // a) if all references in this translation unit are optimized away, we 388 // don't need to codegen it. b) if the function persists, it needs to be 389 // merged with other definitions. c) C++ has the ODR, so we know the 390 // definition is dependable. 391 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 392 return !Context.getLangOptions().AppleKext 393 ? llvm::Function::LinkOnceODRLinkage 394 : llvm::Function::InternalLinkage; 395 396 // An explicit instantiation of a template has weak linkage, since 397 // explicit instantiations can occur in multiple translation units 398 // and must all be equivalent. However, we are not allowed to 399 // throw away these explicit instantiations. 400 if (Linkage == GVA_ExplicitTemplateInstantiation) 401 return !Context.getLangOptions().AppleKext 402 ? llvm::Function::WeakODRLinkage 403 : llvm::Function::InternalLinkage; 404 405 // Otherwise, we have strong external linkage. 406 assert(Linkage == GVA_StrongExternal); 407 return llvm::Function::ExternalLinkage; 408 } 409 410 411 /// SetFunctionDefinitionAttributes - Set attributes for a global. 412 /// 413 /// FIXME: This is currently only done for aliases and functions, but not for 414 /// variables (these details are set in EmitGlobalVarDefinition for variables). 415 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 416 llvm::GlobalValue *GV) { 417 SetCommonAttributes(D, GV); 418 } 419 420 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 421 const CGFunctionInfo &Info, 422 llvm::Function *F) { 423 unsigned CallingConv; 424 AttributeListType AttributeList; 425 ConstructAttributeList(Info, D, AttributeList, CallingConv); 426 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 427 AttributeList.size())); 428 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 429 } 430 431 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 432 llvm::Function *F) { 433 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 434 F->addFnAttr(llvm::Attribute::NoUnwind); 435 436 if (D->hasAttr<AlwaysInlineAttr>()) 437 F->addFnAttr(llvm::Attribute::AlwaysInline); 438 439 if (D->hasAttr<NakedAttr>()) 440 F->addFnAttr(llvm::Attribute::Naked); 441 442 if (D->hasAttr<NoInlineAttr>()) 443 F->addFnAttr(llvm::Attribute::NoInline); 444 445 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 446 F->setUnnamedAddr(true); 447 448 if (Features.getStackProtectorMode() == LangOptions::SSPOn) 449 F->addFnAttr(llvm::Attribute::StackProtect); 450 else if (Features.getStackProtectorMode() == LangOptions::SSPReq) 451 F->addFnAttr(llvm::Attribute::StackProtectReq); 452 453 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 454 if (alignment) 455 F->setAlignment(alignment); 456 457 // C++ ABI requires 2-byte alignment for member functions. 458 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 459 F->setAlignment(2); 460 } 461 462 void CodeGenModule::SetCommonAttributes(const Decl *D, 463 llvm::GlobalValue *GV) { 464 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 465 setGlobalVisibility(GV, ND); 466 else 467 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 468 469 if (D->hasAttr<UsedAttr>()) 470 AddUsedGlobal(GV); 471 472 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 473 GV->setSection(SA->getName()); 474 475 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 476 } 477 478 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 479 llvm::Function *F, 480 const CGFunctionInfo &FI) { 481 SetLLVMFunctionAttributes(D, FI, F); 482 SetLLVMFunctionAttributesForDefinition(D, F); 483 484 F->setLinkage(llvm::Function::InternalLinkage); 485 486 SetCommonAttributes(D, F); 487 } 488 489 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 490 llvm::Function *F, 491 bool IsIncompleteFunction) { 492 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 493 494 if (!IsIncompleteFunction) 495 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F); 496 497 // Only a few attributes are set on declarations; these may later be 498 // overridden by a definition. 499 500 if (FD->hasAttr<DLLImportAttr>()) { 501 F->setLinkage(llvm::Function::DLLImportLinkage); 502 } else if (FD->hasAttr<WeakAttr>() || 503 FD->hasAttr<WeakImportAttr>()) { 504 // "extern_weak" is overloaded in LLVM; we probably should have 505 // separate linkage types for this. 506 F->setLinkage(llvm::Function::ExternalWeakLinkage); 507 } else { 508 F->setLinkage(llvm::Function::ExternalLinkage); 509 510 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility(); 511 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) { 512 F->setVisibility(GetLLVMVisibility(LV.visibility())); 513 } 514 } 515 516 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 517 F->setSection(SA->getName()); 518 } 519 520 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 521 assert(!GV->isDeclaration() && 522 "Only globals with definition can force usage."); 523 LLVMUsed.push_back(GV); 524 } 525 526 void CodeGenModule::EmitLLVMUsed() { 527 // Don't create llvm.used if there is no need. 528 if (LLVMUsed.empty()) 529 return; 530 531 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 532 533 // Convert LLVMUsed to what ConstantArray needs. 534 std::vector<llvm::Constant*> UsedArray; 535 UsedArray.resize(LLVMUsed.size()); 536 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 537 UsedArray[i] = 538 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 539 i8PTy); 540 } 541 542 if (UsedArray.empty()) 543 return; 544 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); 545 546 llvm::GlobalVariable *GV = 547 new llvm::GlobalVariable(getModule(), ATy, false, 548 llvm::GlobalValue::AppendingLinkage, 549 llvm::ConstantArray::get(ATy, UsedArray), 550 "llvm.used"); 551 552 GV->setSection("llvm.metadata"); 553 } 554 555 void CodeGenModule::EmitDeferred() { 556 // Emit code for any potentially referenced deferred decls. Since a 557 // previously unused static decl may become used during the generation of code 558 // for a static function, iterate until no changes are made. 559 560 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) { 561 if (!DeferredVTables.empty()) { 562 const CXXRecordDecl *RD = DeferredVTables.back(); 563 DeferredVTables.pop_back(); 564 getVTables().GenerateClassData(getVTableLinkage(RD), RD); 565 continue; 566 } 567 568 GlobalDecl D = DeferredDeclsToEmit.back(); 569 DeferredDeclsToEmit.pop_back(); 570 571 // Check to see if we've already emitted this. This is necessary 572 // for a couple of reasons: first, decls can end up in the 573 // deferred-decls queue multiple times, and second, decls can end 574 // up with definitions in unusual ways (e.g. by an extern inline 575 // function acquiring a strong function redefinition). Just 576 // ignore these cases. 577 // 578 // TODO: That said, looking this up multiple times is very wasteful. 579 llvm::StringRef Name = getMangledName(D); 580 llvm::GlobalValue *CGRef = GetGlobalValue(Name); 581 assert(CGRef && "Deferred decl wasn't referenced?"); 582 583 if (!CGRef->isDeclaration()) 584 continue; 585 586 // GlobalAlias::isDeclaration() defers to the aliasee, but for our 587 // purposes an alias counts as a definition. 588 if (isa<llvm::GlobalAlias>(CGRef)) 589 continue; 590 591 // Otherwise, emit the definition and move on to the next one. 592 EmitGlobalDefinition(D); 593 } 594 } 595 596 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 597 /// annotation information for a given GlobalValue. The annotation struct is 598 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 599 /// GlobalValue being annotated. The second field is the constant string 600 /// created from the AnnotateAttr's annotation. The third field is a constant 601 /// string containing the name of the translation unit. The fourth field is 602 /// the line number in the file of the annotated value declaration. 603 /// 604 /// FIXME: this does not unique the annotation string constants, as llvm-gcc 605 /// appears to. 606 /// 607 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 608 const AnnotateAttr *AA, 609 unsigned LineNo) { 610 llvm::Module *M = &getModule(); 611 612 // get [N x i8] constants for the annotation string, and the filename string 613 // which are the 2nd and 3rd elements of the global annotation structure. 614 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext); 615 llvm::Constant *anno = llvm::ConstantArray::get(VMContext, 616 AA->getAnnotation(), true); 617 llvm::Constant *unit = llvm::ConstantArray::get(VMContext, 618 M->getModuleIdentifier(), 619 true); 620 621 // Get the two global values corresponding to the ConstantArrays we just 622 // created to hold the bytes of the strings. 623 llvm::GlobalValue *annoGV = 624 new llvm::GlobalVariable(*M, anno->getType(), false, 625 llvm::GlobalValue::PrivateLinkage, anno, 626 GV->getName()); 627 // translation unit name string, emitted into the llvm.metadata section. 628 llvm::GlobalValue *unitGV = 629 new llvm::GlobalVariable(*M, unit->getType(), false, 630 llvm::GlobalValue::PrivateLinkage, unit, 631 ".str"); 632 unitGV->setUnnamedAddr(true); 633 634 // Create the ConstantStruct for the global annotation. 635 llvm::Constant *Fields[4] = { 636 llvm::ConstantExpr::getBitCast(GV, SBP), 637 llvm::ConstantExpr::getBitCast(annoGV, SBP), 638 llvm::ConstantExpr::getBitCast(unitGV, SBP), 639 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo) 640 }; 641 return llvm::ConstantStruct::get(VMContext, Fields, 4, false); 642 } 643 644 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 645 // Never defer when EmitAllDecls is specified. 646 if (Features.EmitAllDecls) 647 return false; 648 649 return !getContext().DeclMustBeEmitted(Global); 650 } 651 652 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 653 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 654 assert(AA && "No alias?"); 655 656 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 657 658 // See if there is already something with the target's name in the module. 659 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 660 661 llvm::Constant *Aliasee; 662 if (isa<llvm::FunctionType>(DeclTy)) 663 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(), 664 /*ForVTable=*/false); 665 else 666 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 667 llvm::PointerType::getUnqual(DeclTy), 0); 668 if (!Entry) { 669 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 670 F->setLinkage(llvm::Function::ExternalWeakLinkage); 671 WeakRefReferences.insert(F); 672 } 673 674 return Aliasee; 675 } 676 677 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 678 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 679 680 // Weak references don't produce any output by themselves. 681 if (Global->hasAttr<WeakRefAttr>()) 682 return; 683 684 // If this is an alias definition (which otherwise looks like a declaration) 685 // emit it now. 686 if (Global->hasAttr<AliasAttr>()) 687 return EmitAliasDefinition(GD); 688 689 // Ignore declarations, they will be emitted on their first use. 690 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 691 if (FD->getIdentifier()) { 692 llvm::StringRef Name = FD->getName(); 693 if (Name == "_Block_object_assign") { 694 BlockObjectAssignDecl = FD; 695 } else if (Name == "_Block_object_dispose") { 696 BlockObjectDisposeDecl = FD; 697 } 698 } 699 700 // Forward declarations are emitted lazily on first use. 701 if (!FD->isThisDeclarationADefinition()) 702 return; 703 } else { 704 const VarDecl *VD = cast<VarDecl>(Global); 705 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 706 707 if (VD->getIdentifier()) { 708 llvm::StringRef Name = VD->getName(); 709 if (Name == "_NSConcreteGlobalBlock") { 710 NSConcreteGlobalBlockDecl = VD; 711 } else if (Name == "_NSConcreteStackBlock") { 712 NSConcreteStackBlockDecl = VD; 713 } 714 } 715 716 717 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 718 return; 719 } 720 721 // Defer code generation when possible if this is a static definition, inline 722 // function etc. These we only want to emit if they are used. 723 if (!MayDeferGeneration(Global)) { 724 // Emit the definition if it can't be deferred. 725 EmitGlobalDefinition(GD); 726 return; 727 } 728 729 // If we're deferring emission of a C++ variable with an 730 // initializer, remember the order in which it appeared in the file. 731 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) && 732 cast<VarDecl>(Global)->hasInit()) { 733 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 734 CXXGlobalInits.push_back(0); 735 } 736 737 // If the value has already been used, add it directly to the 738 // DeferredDeclsToEmit list. 739 llvm::StringRef MangledName = getMangledName(GD); 740 if (GetGlobalValue(MangledName)) 741 DeferredDeclsToEmit.push_back(GD); 742 else { 743 // Otherwise, remember that we saw a deferred decl with this name. The 744 // first use of the mangled name will cause it to move into 745 // DeferredDeclsToEmit. 746 DeferredDecls[MangledName] = GD; 747 } 748 } 749 750 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 751 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 752 753 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 754 Context.getSourceManager(), 755 "Generating code for declaration"); 756 757 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 758 // At -O0, don't generate IR for functions with available_externally 759 // linkage. 760 if (CodeGenOpts.OptimizationLevel == 0 && 761 !Function->hasAttr<AlwaysInlineAttr>() && 762 getFunctionLinkage(Function) 763 == llvm::Function::AvailableExternallyLinkage) 764 return; 765 766 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 767 if (Method->isVirtual()) 768 getVTables().EmitThunks(GD); 769 770 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 771 return EmitCXXConstructor(CD, GD.getCtorType()); 772 773 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method)) 774 return EmitCXXDestructor(DD, GD.getDtorType()); 775 } 776 777 return EmitGlobalFunctionDefinition(GD); 778 } 779 780 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 781 return EmitGlobalVarDefinition(VD); 782 783 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 784 } 785 786 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 787 /// module, create and return an llvm Function with the specified type. If there 788 /// is something in the module with the specified name, return it potentially 789 /// bitcasted to the right type. 790 /// 791 /// If D is non-null, it specifies a decl that correspond to this. This is used 792 /// to set the attributes on the function when it is first created. 793 llvm::Constant * 794 CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName, 795 const llvm::Type *Ty, 796 GlobalDecl D, bool ForVTable) { 797 // Lookup the entry, lazily creating it if necessary. 798 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 799 if (Entry) { 800 if (WeakRefReferences.count(Entry)) { 801 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 802 if (FD && !FD->hasAttr<WeakAttr>()) 803 Entry->setLinkage(llvm::Function::ExternalLinkage); 804 805 WeakRefReferences.erase(Entry); 806 } 807 808 if (Entry->getType()->getElementType() == Ty) 809 return Entry; 810 811 // Make sure the result is of the correct type. 812 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 813 return llvm::ConstantExpr::getBitCast(Entry, PTy); 814 } 815 816 // This function doesn't have a complete type (for example, the return 817 // type is an incomplete struct). Use a fake type instead, and make 818 // sure not to try to set attributes. 819 bool IsIncompleteFunction = false; 820 821 const llvm::FunctionType *FTy; 822 if (isa<llvm::FunctionType>(Ty)) { 823 FTy = cast<llvm::FunctionType>(Ty); 824 } else { 825 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false); 826 IsIncompleteFunction = true; 827 } 828 829 llvm::Function *F = llvm::Function::Create(FTy, 830 llvm::Function::ExternalLinkage, 831 MangledName, &getModule()); 832 assert(F->getName() == MangledName && "name was uniqued!"); 833 if (D.getDecl()) 834 SetFunctionAttributes(D, F, IsIncompleteFunction); 835 836 // This is the first use or definition of a mangled name. If there is a 837 // deferred decl with this name, remember that we need to emit it at the end 838 // of the file. 839 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 840 if (DDI != DeferredDecls.end()) { 841 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 842 // list, and remove it from DeferredDecls (since we don't need it anymore). 843 DeferredDeclsToEmit.push_back(DDI->second); 844 DeferredDecls.erase(DDI); 845 846 // Otherwise, there are cases we have to worry about where we're 847 // using a declaration for which we must emit a definition but where 848 // we might not find a top-level definition: 849 // - member functions defined inline in their classes 850 // - friend functions defined inline in some class 851 // - special member functions with implicit definitions 852 // If we ever change our AST traversal to walk into class methods, 853 // this will be unnecessary. 854 // 855 // We also don't emit a definition for a function if it's going to be an entry 856 // in a vtable, unless it's already marked as used. 857 } else if (getLangOptions().CPlusPlus && D.getDecl()) { 858 // Look for a declaration that's lexically in a record. 859 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl()); 860 do { 861 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 862 if (FD->isImplicit() && !ForVTable) { 863 assert(FD->isUsed() && "Sema didn't mark implicit function as used!"); 864 DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 865 break; 866 } else if (FD->isThisDeclarationADefinition()) { 867 DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 868 break; 869 } 870 } 871 FD = FD->getPreviousDeclaration(); 872 } while (FD); 873 } 874 875 // Make sure the result is of the requested type. 876 if (!IsIncompleteFunction) { 877 assert(F->getType()->getElementType() == Ty); 878 return F; 879 } 880 881 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 882 return llvm::ConstantExpr::getBitCast(F, PTy); 883 } 884 885 /// GetAddrOfFunction - Return the address of the given function. If Ty is 886 /// non-null, then this function will use the specified type if it has to 887 /// create it (this occurs when we see a definition of the function). 888 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 889 const llvm::Type *Ty, 890 bool ForVTable) { 891 // If there was no specific requested type, just convert it now. 892 if (!Ty) 893 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 894 895 llvm::StringRef MangledName = getMangledName(GD); 896 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable); 897 } 898 899 /// CreateRuntimeFunction - Create a new runtime function with the specified 900 /// type and name. 901 llvm::Constant * 902 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 903 llvm::StringRef Name) { 904 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false); 905 } 906 907 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) { 908 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType()) 909 return false; 910 if (Context.getLangOptions().CPlusPlus && 911 Context.getBaseElementType(D->getType())->getAs<RecordType>()) { 912 // FIXME: We should do something fancier here! 913 return false; 914 } 915 return true; 916 } 917 918 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 919 /// create and return an llvm GlobalVariable with the specified type. If there 920 /// is something in the module with the specified name, return it potentially 921 /// bitcasted to the right type. 922 /// 923 /// If D is non-null, it specifies a decl that correspond to this. This is used 924 /// to set the attributes on the global when it is first created. 925 llvm::Constant * 926 CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName, 927 const llvm::PointerType *Ty, 928 const VarDecl *D, 929 bool UnnamedAddr) { 930 // Lookup the entry, lazily creating it if necessary. 931 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 932 if (Entry) { 933 if (WeakRefReferences.count(Entry)) { 934 if (D && !D->hasAttr<WeakAttr>()) 935 Entry->setLinkage(llvm::Function::ExternalLinkage); 936 937 WeakRefReferences.erase(Entry); 938 } 939 940 if (UnnamedAddr) 941 Entry->setUnnamedAddr(true); 942 943 if (Entry->getType() == Ty) 944 return Entry; 945 946 // Make sure the result is of the correct type. 947 return llvm::ConstantExpr::getBitCast(Entry, Ty); 948 } 949 950 // This is the first use or definition of a mangled name. If there is a 951 // deferred decl with this name, remember that we need to emit it at the end 952 // of the file. 953 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 954 if (DDI != DeferredDecls.end()) { 955 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 956 // list, and remove it from DeferredDecls (since we don't need it anymore). 957 DeferredDeclsToEmit.push_back(DDI->second); 958 DeferredDecls.erase(DDI); 959 } 960 961 llvm::GlobalVariable *GV = 962 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 963 llvm::GlobalValue::ExternalLinkage, 964 0, MangledName, 0, 965 false, Ty->getAddressSpace()); 966 967 // Handle things which are present even on external declarations. 968 if (D) { 969 // FIXME: This code is overly simple and should be merged with other global 970 // handling. 971 GV->setConstant(DeclIsConstantGlobal(Context, D)); 972 973 // Set linkage and visibility in case we never see a definition. 974 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility(); 975 if (LV.linkage() != ExternalLinkage) { 976 GV->setLinkage(llvm::GlobalValue::InternalLinkage); 977 } else { 978 if (D->hasAttr<DLLImportAttr>()) 979 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage); 980 else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>()) 981 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 982 983 // Set visibility on a declaration only if it's explicit. 984 if (LV.visibilityExplicit()) 985 GV->setVisibility(GetLLVMVisibility(LV.visibility())); 986 } 987 988 GV->setThreadLocal(D->isThreadSpecified()); 989 } 990 991 return GV; 992 } 993 994 995 llvm::GlobalVariable * 996 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name, 997 const llvm::Type *Ty, 998 llvm::GlobalValue::LinkageTypes Linkage) { 999 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 1000 llvm::GlobalVariable *OldGV = 0; 1001 1002 1003 if (GV) { 1004 // Check if the variable has the right type. 1005 if (GV->getType()->getElementType() == Ty) 1006 return GV; 1007 1008 // Because C++ name mangling, the only way we can end up with an already 1009 // existing global with the same name is if it has been declared extern "C". 1010 assert(GV->isDeclaration() && "Declaration has wrong type!"); 1011 OldGV = GV; 1012 } 1013 1014 // Create a new variable. 1015 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 1016 Linkage, 0, Name); 1017 1018 if (OldGV) { 1019 // Replace occurrences of the old variable if needed. 1020 GV->takeName(OldGV); 1021 1022 if (!OldGV->use_empty()) { 1023 llvm::Constant *NewPtrForOldDecl = 1024 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 1025 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 1026 } 1027 1028 OldGV->eraseFromParent(); 1029 } 1030 1031 return GV; 1032 } 1033 1034 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1035 /// given global variable. If Ty is non-null and if the global doesn't exist, 1036 /// then it will be greated with the specified type instead of whatever the 1037 /// normal requested type would be. 1038 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 1039 const llvm::Type *Ty) { 1040 assert(D->hasGlobalStorage() && "Not a global variable"); 1041 QualType ASTTy = D->getType(); 1042 if (Ty == 0) 1043 Ty = getTypes().ConvertTypeForMem(ASTTy); 1044 1045 const llvm::PointerType *PTy = 1046 llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 1047 1048 llvm::StringRef MangledName = getMangledName(D); 1049 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1050 } 1051 1052 /// CreateRuntimeVariable - Create a new runtime global variable with the 1053 /// specified type and name. 1054 llvm::Constant * 1055 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 1056 llvm::StringRef Name) { 1057 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0, 1058 true); 1059 } 1060 1061 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1062 assert(!D->getInit() && "Cannot emit definite definitions here!"); 1063 1064 if (MayDeferGeneration(D)) { 1065 // If we have not seen a reference to this variable yet, place it 1066 // into the deferred declarations table to be emitted if needed 1067 // later. 1068 llvm::StringRef MangledName = getMangledName(D); 1069 if (!GetGlobalValue(MangledName)) { 1070 DeferredDecls[MangledName] = D; 1071 return; 1072 } 1073 } 1074 1075 // The tentative definition is the only definition. 1076 EmitGlobalVarDefinition(D); 1077 } 1078 1079 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) { 1080 if (DefinitionRequired) 1081 getVTables().GenerateClassData(getVTableLinkage(Class), Class); 1082 } 1083 1084 llvm::GlobalVariable::LinkageTypes 1085 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) { 1086 if (RD->isInAnonymousNamespace() || !RD->hasLinkage()) 1087 return llvm::GlobalVariable::InternalLinkage; 1088 1089 if (const CXXMethodDecl *KeyFunction 1090 = RD->getASTContext().getKeyFunction(RD)) { 1091 // If this class has a key function, use that to determine the linkage of 1092 // the vtable. 1093 const FunctionDecl *Def = 0; 1094 if (KeyFunction->hasBody(Def)) 1095 KeyFunction = cast<CXXMethodDecl>(Def); 1096 1097 switch (KeyFunction->getTemplateSpecializationKind()) { 1098 case TSK_Undeclared: 1099 case TSK_ExplicitSpecialization: 1100 // When compiling with optimizations turned on, we emit all vtables, 1101 // even if the key function is not defined in the current translation 1102 // unit. If this is the case, use available_externally linkage. 1103 if (!Def && CodeGenOpts.OptimizationLevel) 1104 return llvm::GlobalVariable::AvailableExternallyLinkage; 1105 1106 if (KeyFunction->isInlined()) 1107 return !Context.getLangOptions().AppleKext ? 1108 llvm::GlobalVariable::LinkOnceODRLinkage : 1109 llvm::Function::InternalLinkage; 1110 1111 return llvm::GlobalVariable::ExternalLinkage; 1112 1113 case TSK_ImplicitInstantiation: 1114 return !Context.getLangOptions().AppleKext ? 1115 llvm::GlobalVariable::LinkOnceODRLinkage : 1116 llvm::Function::InternalLinkage; 1117 1118 case TSK_ExplicitInstantiationDefinition: 1119 return !Context.getLangOptions().AppleKext ? 1120 llvm::GlobalVariable::WeakODRLinkage : 1121 llvm::Function::InternalLinkage; 1122 1123 case TSK_ExplicitInstantiationDeclaration: 1124 // FIXME: Use available_externally linkage. However, this currently 1125 // breaks LLVM's build due to undefined symbols. 1126 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1127 return !Context.getLangOptions().AppleKext ? 1128 llvm::GlobalVariable::LinkOnceODRLinkage : 1129 llvm::Function::InternalLinkage; 1130 } 1131 } 1132 1133 if (Context.getLangOptions().AppleKext) 1134 return llvm::Function::InternalLinkage; 1135 1136 switch (RD->getTemplateSpecializationKind()) { 1137 case TSK_Undeclared: 1138 case TSK_ExplicitSpecialization: 1139 case TSK_ImplicitInstantiation: 1140 // FIXME: Use available_externally linkage. However, this currently 1141 // breaks LLVM's build due to undefined symbols. 1142 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1143 case TSK_ExplicitInstantiationDeclaration: 1144 return llvm::GlobalVariable::LinkOnceODRLinkage; 1145 1146 case TSK_ExplicitInstantiationDefinition: 1147 return llvm::GlobalVariable::WeakODRLinkage; 1148 } 1149 1150 // Silence GCC warning. 1151 return llvm::GlobalVariable::LinkOnceODRLinkage; 1152 } 1153 1154 CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const { 1155 return Context.toCharUnitsFromBits( 1156 TheTargetData.getTypeStoreSizeInBits(Ty)); 1157 } 1158 1159 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1160 llvm::Constant *Init = 0; 1161 QualType ASTTy = D->getType(); 1162 bool NonConstInit = false; 1163 1164 const Expr *InitExpr = D->getAnyInitializer(); 1165 1166 if (!InitExpr) { 1167 // This is a tentative definition; tentative definitions are 1168 // implicitly initialized with { 0 }. 1169 // 1170 // Note that tentative definitions are only emitted at the end of 1171 // a translation unit, so they should never have incomplete 1172 // type. In addition, EmitTentativeDefinition makes sure that we 1173 // never attempt to emit a tentative definition if a real one 1174 // exists. A use may still exists, however, so we still may need 1175 // to do a RAUW. 1176 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1177 Init = EmitNullConstant(D->getType()); 1178 } else { 1179 Init = EmitConstantExpr(InitExpr, D->getType()); 1180 if (!Init) { 1181 QualType T = InitExpr->getType(); 1182 if (D->getType()->isReferenceType()) 1183 T = D->getType(); 1184 1185 if (getLangOptions().CPlusPlus) { 1186 Init = EmitNullConstant(T); 1187 NonConstInit = true; 1188 } else { 1189 ErrorUnsupported(D, "static initializer"); 1190 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1191 } 1192 } else { 1193 // We don't need an initializer, so remove the entry for the delayed 1194 // initializer position (just in case this entry was delayed). 1195 if (getLangOptions().CPlusPlus) 1196 DelayedCXXInitPosition.erase(D); 1197 } 1198 } 1199 1200 const llvm::Type* InitType = Init->getType(); 1201 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1202 1203 // Strip off a bitcast if we got one back. 1204 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1205 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1206 // all zero index gep. 1207 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1208 Entry = CE->getOperand(0); 1209 } 1210 1211 // Entry is now either a Function or GlobalVariable. 1212 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1213 1214 // We have a definition after a declaration with the wrong type. 1215 // We must make a new GlobalVariable* and update everything that used OldGV 1216 // (a declaration or tentative definition) with the new GlobalVariable* 1217 // (which will be a definition). 1218 // 1219 // This happens if there is a prototype for a global (e.g. 1220 // "extern int x[];") and then a definition of a different type (e.g. 1221 // "int x[10];"). This also happens when an initializer has a different type 1222 // from the type of the global (this happens with unions). 1223 if (GV == 0 || 1224 GV->getType()->getElementType() != InitType || 1225 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 1226 1227 // Move the old entry aside so that we'll create a new one. 1228 Entry->setName(llvm::StringRef()); 1229 1230 // Make a new global with the correct type, this is now guaranteed to work. 1231 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1232 1233 // Replace all uses of the old global with the new global 1234 llvm::Constant *NewPtrForOldDecl = 1235 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1236 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1237 1238 // Erase the old global, since it is no longer used. 1239 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1240 } 1241 1242 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 1243 SourceManager &SM = Context.getSourceManager(); 1244 AddAnnotation(EmitAnnotateAttr(GV, AA, 1245 SM.getInstantiationLineNumber(D->getLocation()))); 1246 } 1247 1248 GV->setInitializer(Init); 1249 1250 // If it is safe to mark the global 'constant', do so now. 1251 GV->setConstant(false); 1252 if (!NonConstInit && DeclIsConstantGlobal(Context, D)) 1253 GV->setConstant(true); 1254 1255 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1256 1257 // Set the llvm linkage type as appropriate. 1258 llvm::GlobalValue::LinkageTypes Linkage = 1259 GetLLVMLinkageVarDefinition(D, GV); 1260 GV->setLinkage(Linkage); 1261 if (Linkage == llvm::GlobalVariable::CommonLinkage) 1262 // common vars aren't constant even if declared const. 1263 GV->setConstant(false); 1264 1265 SetCommonAttributes(D, GV); 1266 1267 // Emit the initializer function if necessary. 1268 if (NonConstInit) 1269 EmitCXXGlobalVarDeclInitFunc(D, GV); 1270 1271 // Emit global variable debug information. 1272 if (CGDebugInfo *DI = getDebugInfo()) { 1273 DI->setLocation(D->getLocation()); 1274 DI->EmitGlobalVariable(GV, D); 1275 } 1276 } 1277 1278 llvm::GlobalValue::LinkageTypes 1279 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, 1280 llvm::GlobalVariable *GV) { 1281 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 1282 if (Linkage == GVA_Internal) 1283 return llvm::Function::InternalLinkage; 1284 else if (D->hasAttr<DLLImportAttr>()) 1285 return llvm::Function::DLLImportLinkage; 1286 else if (D->hasAttr<DLLExportAttr>()) 1287 return llvm::Function::DLLExportLinkage; 1288 else if (D->hasAttr<WeakAttr>()) { 1289 if (GV->isConstant()) 1290 return llvm::GlobalVariable::WeakODRLinkage; 1291 else 1292 return llvm::GlobalVariable::WeakAnyLinkage; 1293 } else if (Linkage == GVA_TemplateInstantiation || 1294 Linkage == GVA_ExplicitTemplateInstantiation) 1295 // FIXME: It seems like we can provide more specific linkage here 1296 // (LinkOnceODR, WeakODR). 1297 return llvm::GlobalVariable::WeakAnyLinkage; 1298 else if (!getLangOptions().CPlusPlus && 1299 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) || 1300 D->getAttr<CommonAttr>()) && 1301 !D->hasExternalStorage() && !D->getInit() && 1302 !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) { 1303 // Thread local vars aren't considered common linkage. 1304 return llvm::GlobalVariable::CommonLinkage; 1305 } 1306 return llvm::GlobalVariable::ExternalLinkage; 1307 } 1308 1309 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1310 /// implement a function with no prototype, e.g. "int foo() {}". If there are 1311 /// existing call uses of the old function in the module, this adjusts them to 1312 /// call the new function directly. 1313 /// 1314 /// This is not just a cleanup: the always_inline pass requires direct calls to 1315 /// functions to be able to inline them. If there is a bitcast in the way, it 1316 /// won't inline them. Instcombine normally deletes these calls, but it isn't 1317 /// run at -O0. 1318 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1319 llvm::Function *NewFn) { 1320 // If we're redefining a global as a function, don't transform it. 1321 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1322 if (OldFn == 0) return; 1323 1324 const llvm::Type *NewRetTy = NewFn->getReturnType(); 1325 llvm::SmallVector<llvm::Value*, 4> ArgList; 1326 1327 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1328 UI != E; ) { 1329 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1330 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased. 1331 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I); 1332 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I) 1333 llvm::CallSite CS(CI); 1334 if (!CI || !CS.isCallee(I)) continue; 1335 1336 // If the return types don't match exactly, and if the call isn't dead, then 1337 // we can't transform this call. 1338 if (CI->getType() != NewRetTy && !CI->use_empty()) 1339 continue; 1340 1341 // If the function was passed too few arguments, don't transform. If extra 1342 // arguments were passed, we silently drop them. If any of the types 1343 // mismatch, we don't transform. 1344 unsigned ArgNo = 0; 1345 bool DontTransform = false; 1346 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1347 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1348 if (CS.arg_size() == ArgNo || 1349 CS.getArgument(ArgNo)->getType() != AI->getType()) { 1350 DontTransform = true; 1351 break; 1352 } 1353 } 1354 if (DontTransform) 1355 continue; 1356 1357 // Okay, we can transform this. Create the new call instruction and copy 1358 // over the required information. 1359 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo); 1360 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(), 1361 ArgList.end(), "", CI); 1362 ArgList.clear(); 1363 if (!NewCall->getType()->isVoidTy()) 1364 NewCall->takeName(CI); 1365 NewCall->setAttributes(CI->getAttributes()); 1366 NewCall->setCallingConv(CI->getCallingConv()); 1367 1368 // Finally, remove the old call, replacing any uses with the new one. 1369 if (!CI->use_empty()) 1370 CI->replaceAllUsesWith(NewCall); 1371 1372 // Copy debug location attached to CI. 1373 if (!CI->getDebugLoc().isUnknown()) 1374 NewCall->setDebugLoc(CI->getDebugLoc()); 1375 CI->eraseFromParent(); 1376 } 1377 } 1378 1379 1380 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1381 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1382 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD); 1383 // Get or create the prototype for the function. 1384 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1385 1386 // Strip off a bitcast if we got one back. 1387 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1388 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1389 Entry = CE->getOperand(0); 1390 } 1391 1392 1393 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1394 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1395 1396 // If the types mismatch then we have to rewrite the definition. 1397 assert(OldFn->isDeclaration() && 1398 "Shouldn't replace non-declaration"); 1399 1400 // F is the Function* for the one with the wrong type, we must make a new 1401 // Function* and update everything that used F (a declaration) with the new 1402 // Function* (which will be a definition). 1403 // 1404 // This happens if there is a prototype for a function 1405 // (e.g. "int f()") and then a definition of a different type 1406 // (e.g. "int f(int x)"). Move the old function aside so that it 1407 // doesn't interfere with GetAddrOfFunction. 1408 OldFn->setName(llvm::StringRef()); 1409 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1410 1411 // If this is an implementation of a function without a prototype, try to 1412 // replace any existing uses of the function (which may be calls) with uses 1413 // of the new function 1414 if (D->getType()->isFunctionNoProtoType()) { 1415 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1416 OldFn->removeDeadConstantUsers(); 1417 } 1418 1419 // Replace uses of F with the Function we will endow with a body. 1420 if (!Entry->use_empty()) { 1421 llvm::Constant *NewPtrForOldDecl = 1422 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1423 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1424 } 1425 1426 // Ok, delete the old function now, which is dead. 1427 OldFn->eraseFromParent(); 1428 1429 Entry = NewFn; 1430 } 1431 1432 // We need to set linkage and visibility on the function before 1433 // generating code for it because various parts of IR generation 1434 // want to propagate this information down (e.g. to local static 1435 // declarations). 1436 llvm::Function *Fn = cast<llvm::Function>(Entry); 1437 setFunctionLinkage(D, Fn); 1438 1439 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes 1440 setGlobalVisibility(Fn, D); 1441 1442 CodeGenFunction(*this).GenerateCode(D, Fn); 1443 1444 SetFunctionDefinitionAttributes(D, Fn); 1445 SetLLVMFunctionAttributesForDefinition(D, Fn); 1446 1447 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1448 AddGlobalCtor(Fn, CA->getPriority()); 1449 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1450 AddGlobalDtor(Fn, DA->getPriority()); 1451 } 1452 1453 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 1454 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1455 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1456 assert(AA && "Not an alias?"); 1457 1458 llvm::StringRef MangledName = getMangledName(GD); 1459 1460 // If there is a definition in the module, then it wins over the alias. 1461 // This is dubious, but allow it to be safe. Just ignore the alias. 1462 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1463 if (Entry && !Entry->isDeclaration()) 1464 return; 1465 1466 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1467 1468 // Create a reference to the named value. This ensures that it is emitted 1469 // if a deferred decl. 1470 llvm::Constant *Aliasee; 1471 if (isa<llvm::FunctionType>(DeclTy)) 1472 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(), 1473 /*ForVTable=*/false); 1474 else 1475 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1476 llvm::PointerType::getUnqual(DeclTy), 0); 1477 1478 // Create the new alias itself, but don't set a name yet. 1479 llvm::GlobalValue *GA = 1480 new llvm::GlobalAlias(Aliasee->getType(), 1481 llvm::Function::ExternalLinkage, 1482 "", Aliasee, &getModule()); 1483 1484 if (Entry) { 1485 assert(Entry->isDeclaration()); 1486 1487 // If there is a declaration in the module, then we had an extern followed 1488 // by the alias, as in: 1489 // extern int test6(); 1490 // ... 1491 // int test6() __attribute__((alias("test7"))); 1492 // 1493 // Remove it and replace uses of it with the alias. 1494 GA->takeName(Entry); 1495 1496 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1497 Entry->getType())); 1498 Entry->eraseFromParent(); 1499 } else { 1500 GA->setName(MangledName); 1501 } 1502 1503 // Set attributes which are particular to an alias; this is a 1504 // specialization of the attributes which may be set on a global 1505 // variable/function. 1506 if (D->hasAttr<DLLExportAttr>()) { 1507 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1508 // The dllexport attribute is ignored for undefined symbols. 1509 if (FD->hasBody()) 1510 GA->setLinkage(llvm::Function::DLLExportLinkage); 1511 } else { 1512 GA->setLinkage(llvm::Function::DLLExportLinkage); 1513 } 1514 } else if (D->hasAttr<WeakAttr>() || 1515 D->hasAttr<WeakRefAttr>() || 1516 D->hasAttr<WeakImportAttr>()) { 1517 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1518 } 1519 1520 SetCommonAttributes(D, GA); 1521 } 1522 1523 /// getBuiltinLibFunction - Given a builtin id for a function like 1524 /// "__builtin_fabsf", return a Function* for "fabsf". 1525 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD, 1526 unsigned BuiltinID) { 1527 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 1528 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 1529 "isn't a lib fn"); 1530 1531 // Get the name, skip over the __builtin_ prefix (if necessary). 1532 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 1533 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 1534 Name += 10; 1535 1536 const llvm::FunctionType *Ty = 1537 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType())); 1538 1539 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD), /*ForVTable=*/false); 1540 } 1541 1542 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 1543 unsigned NumTys) { 1544 return llvm::Intrinsic::getDeclaration(&getModule(), 1545 (llvm::Intrinsic::ID)IID, Tys, NumTys); 1546 } 1547 1548 static llvm::StringMapEntry<llvm::Constant*> & 1549 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1550 const StringLiteral *Literal, 1551 bool TargetIsLSB, 1552 bool &IsUTF16, 1553 unsigned &StringLength) { 1554 llvm::StringRef String = Literal->getString(); 1555 unsigned NumBytes = String.size(); 1556 1557 // Check for simple case. 1558 if (!Literal->containsNonAsciiOrNull()) { 1559 StringLength = NumBytes; 1560 return Map.GetOrCreateValue(String); 1561 } 1562 1563 // Otherwise, convert the UTF8 literals into a byte string. 1564 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 1565 const UTF8 *FromPtr = (UTF8 *)String.data(); 1566 UTF16 *ToPtr = &ToBuf[0]; 1567 1568 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1569 &ToPtr, ToPtr + NumBytes, 1570 strictConversion); 1571 1572 // ConvertUTF8toUTF16 returns the length in ToPtr. 1573 StringLength = ToPtr - &ToBuf[0]; 1574 1575 // Render the UTF-16 string into a byte array and convert to the target byte 1576 // order. 1577 // 1578 // FIXME: This isn't something we should need to do here. 1579 llvm::SmallString<128> AsBytes; 1580 AsBytes.reserve(StringLength * 2); 1581 for (unsigned i = 0; i != StringLength; ++i) { 1582 unsigned short Val = ToBuf[i]; 1583 if (TargetIsLSB) { 1584 AsBytes.push_back(Val & 0xFF); 1585 AsBytes.push_back(Val >> 8); 1586 } else { 1587 AsBytes.push_back(Val >> 8); 1588 AsBytes.push_back(Val & 0xFF); 1589 } 1590 } 1591 // Append one extra null character, the second is automatically added by our 1592 // caller. 1593 AsBytes.push_back(0); 1594 1595 IsUTF16 = true; 1596 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size())); 1597 } 1598 1599 llvm::Constant * 1600 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1601 unsigned StringLength = 0; 1602 bool isUTF16 = false; 1603 llvm::StringMapEntry<llvm::Constant*> &Entry = 1604 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1605 getTargetData().isLittleEndian(), 1606 isUTF16, StringLength); 1607 1608 if (llvm::Constant *C = Entry.getValue()) 1609 return C; 1610 1611 llvm::Constant *Zero = 1612 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1613 llvm::Constant *Zeros[] = { Zero, Zero }; 1614 1615 // If we don't already have it, get __CFConstantStringClassReference. 1616 if (!CFConstantStringClassRef) { 1617 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1618 Ty = llvm::ArrayType::get(Ty, 0); 1619 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1620 "__CFConstantStringClassReference"); 1621 // Decay array -> ptr 1622 CFConstantStringClassRef = 1623 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1624 } 1625 1626 QualType CFTy = getContext().getCFConstantStringType(); 1627 1628 const llvm::StructType *STy = 1629 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1630 1631 std::vector<llvm::Constant*> Fields(4); 1632 1633 // Class pointer. 1634 Fields[0] = CFConstantStringClassRef; 1635 1636 // Flags. 1637 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1638 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1639 llvm::ConstantInt::get(Ty, 0x07C8); 1640 1641 // String pointer. 1642 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1643 1644 llvm::GlobalValue::LinkageTypes Linkage; 1645 bool isConstant; 1646 if (isUTF16) { 1647 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1648 Linkage = llvm::GlobalValue::InternalLinkage; 1649 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1650 // does make plain ascii ones writable. 1651 isConstant = true; 1652 } else { 1653 Linkage = llvm::GlobalValue::PrivateLinkage; 1654 isConstant = !Features.WritableStrings; 1655 } 1656 1657 llvm::GlobalVariable *GV = 1658 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1659 ".str"); 1660 GV->setUnnamedAddr(true); 1661 if (isUTF16) { 1662 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1663 GV->setAlignment(Align.getQuantity()); 1664 } 1665 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1666 1667 // String length. 1668 Ty = getTypes().ConvertType(getContext().LongTy); 1669 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1670 1671 // The struct. 1672 C = llvm::ConstantStruct::get(STy, Fields); 1673 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1674 llvm::GlobalVariable::PrivateLinkage, C, 1675 "_unnamed_cfstring_"); 1676 if (const char *Sect = getContext().Target.getCFStringSection()) 1677 GV->setSection(Sect); 1678 Entry.setValue(GV); 1679 1680 return GV; 1681 } 1682 1683 llvm::Constant * 1684 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 1685 unsigned StringLength = 0; 1686 bool isUTF16 = false; 1687 llvm::StringMapEntry<llvm::Constant*> &Entry = 1688 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1689 getTargetData().isLittleEndian(), 1690 isUTF16, StringLength); 1691 1692 if (llvm::Constant *C = Entry.getValue()) 1693 return C; 1694 1695 llvm::Constant *Zero = 1696 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1697 llvm::Constant *Zeros[] = { Zero, Zero }; 1698 1699 // If we don't already have it, get _NSConstantStringClassReference. 1700 if (!ConstantStringClassRef) { 1701 std::string StringClass(getLangOptions().ObjCConstantStringClass); 1702 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1703 Ty = llvm::ArrayType::get(Ty, 0); 1704 llvm::Constant *GV; 1705 if (StringClass.empty()) 1706 GV = CreateRuntimeVariable(Ty, 1707 Features.ObjCNonFragileABI ? 1708 "OBJC_CLASS_$_NSConstantString" : 1709 "_NSConstantStringClassReference"); 1710 else { 1711 std::string str; 1712 if (Features.ObjCNonFragileABI) 1713 str = "OBJC_CLASS_$_" + StringClass; 1714 else 1715 str = "_" + StringClass + "ClassReference"; 1716 GV = CreateRuntimeVariable(Ty, str); 1717 } 1718 // Decay array -> ptr 1719 ConstantStringClassRef = 1720 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1721 } 1722 1723 QualType NSTy = getContext().getNSConstantStringType(); 1724 1725 const llvm::StructType *STy = 1726 cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 1727 1728 std::vector<llvm::Constant*> Fields(3); 1729 1730 // Class pointer. 1731 Fields[0] = ConstantStringClassRef; 1732 1733 // String pointer. 1734 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1735 1736 llvm::GlobalValue::LinkageTypes Linkage; 1737 bool isConstant; 1738 if (isUTF16) { 1739 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1740 Linkage = llvm::GlobalValue::InternalLinkage; 1741 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but 1742 // does make plain ascii ones writable. 1743 isConstant = true; 1744 } else { 1745 Linkage = llvm::GlobalValue::PrivateLinkage; 1746 isConstant = !Features.WritableStrings; 1747 } 1748 1749 llvm::GlobalVariable *GV = 1750 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1751 ".str"); 1752 GV->setUnnamedAddr(true); 1753 if (isUTF16) { 1754 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1755 GV->setAlignment(Align.getQuantity()); 1756 } 1757 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1758 1759 // String length. 1760 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1761 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 1762 1763 // The struct. 1764 C = llvm::ConstantStruct::get(STy, Fields); 1765 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1766 llvm::GlobalVariable::PrivateLinkage, C, 1767 "_unnamed_nsstring_"); 1768 // FIXME. Fix section. 1769 if (const char *Sect = 1770 Features.ObjCNonFragileABI 1771 ? getContext().Target.getNSStringNonFragileABISection() 1772 : getContext().Target.getNSStringSection()) 1773 GV->setSection(Sect); 1774 Entry.setValue(GV); 1775 1776 return GV; 1777 } 1778 1779 /// GetStringForStringLiteral - Return the appropriate bytes for a 1780 /// string literal, properly padded to match the literal type. 1781 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1782 const ASTContext &Context = getContext(); 1783 const ConstantArrayType *CAT = 1784 Context.getAsConstantArrayType(E->getType()); 1785 assert(CAT && "String isn't pointer or array!"); 1786 1787 // Resize the string to the right size. 1788 uint64_t RealLen = CAT->getSize().getZExtValue(); 1789 1790 if (E->isWide()) 1791 RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth(); 1792 1793 std::string Str = E->getString().str(); 1794 Str.resize(RealLen, '\0'); 1795 1796 return Str; 1797 } 1798 1799 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1800 /// constant array for the given string literal. 1801 llvm::Constant * 1802 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1803 // FIXME: This can be more efficient. 1804 // FIXME: We shouldn't need to bitcast the constant in the wide string case. 1805 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S)); 1806 if (S->isWide()) { 1807 llvm::Type *DestTy = 1808 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType())); 1809 C = llvm::ConstantExpr::getBitCast(C, DestTy); 1810 } 1811 return C; 1812 } 1813 1814 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1815 /// array for the given ObjCEncodeExpr node. 1816 llvm::Constant * 1817 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1818 std::string Str; 1819 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1820 1821 return GetAddrOfConstantCString(Str); 1822 } 1823 1824 1825 /// GenerateWritableString -- Creates storage for a string literal. 1826 static llvm::Constant *GenerateStringLiteral(const std::string &str, 1827 bool constant, 1828 CodeGenModule &CGM, 1829 const char *GlobalName) { 1830 // Create Constant for this string literal. Don't add a '\0'. 1831 llvm::Constant *C = 1832 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 1833 1834 // Create a global variable for this string 1835 llvm::GlobalVariable *GV = 1836 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 1837 llvm::GlobalValue::PrivateLinkage, 1838 C, GlobalName); 1839 GV->setUnnamedAddr(true); 1840 return GV; 1841 } 1842 1843 /// GetAddrOfConstantString - Returns a pointer to a character array 1844 /// containing the literal. This contents are exactly that of the 1845 /// given string, i.e. it will not be null terminated automatically; 1846 /// see GetAddrOfConstantCString. Note that whether the result is 1847 /// actually a pointer to an LLVM constant depends on 1848 /// Feature.WriteableStrings. 1849 /// 1850 /// The result has pointer to array type. 1851 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1852 const char *GlobalName) { 1853 bool IsConstant = !Features.WritableStrings; 1854 1855 // Get the default prefix if a name wasn't specified. 1856 if (!GlobalName) 1857 GlobalName = ".str"; 1858 1859 // Don't share any string literals if strings aren't constant. 1860 if (!IsConstant) 1861 return GenerateStringLiteral(str, false, *this, GlobalName); 1862 1863 llvm::StringMapEntry<llvm::Constant *> &Entry = 1864 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1865 1866 if (Entry.getValue()) 1867 return Entry.getValue(); 1868 1869 // Create a global variable for this. 1870 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1871 Entry.setValue(C); 1872 return C; 1873 } 1874 1875 /// GetAddrOfConstantCString - Returns a pointer to a character 1876 /// array containing the literal and a terminating '\-' 1877 /// character. The result has pointer to array type. 1878 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1879 const char *GlobalName){ 1880 return GetAddrOfConstantString(str + '\0', GlobalName); 1881 } 1882 1883 /// EmitObjCPropertyImplementations - Emit information for synthesized 1884 /// properties for an implementation. 1885 void CodeGenModule::EmitObjCPropertyImplementations(const 1886 ObjCImplementationDecl *D) { 1887 for (ObjCImplementationDecl::propimpl_iterator 1888 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 1889 ObjCPropertyImplDecl *PID = *i; 1890 1891 // Dynamic is just for type-checking. 1892 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1893 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1894 1895 // Determine which methods need to be implemented, some may have 1896 // been overridden. Note that ::isSynthesized is not the method 1897 // we want, that just indicates if the decl came from a 1898 // property. What we want to know is if the method is defined in 1899 // this implementation. 1900 if (!D->getInstanceMethod(PD->getGetterName())) 1901 CodeGenFunction(*this).GenerateObjCGetter( 1902 const_cast<ObjCImplementationDecl *>(D), PID); 1903 if (!PD->isReadOnly() && 1904 !D->getInstanceMethod(PD->getSetterName())) 1905 CodeGenFunction(*this).GenerateObjCSetter( 1906 const_cast<ObjCImplementationDecl *>(D), PID); 1907 } 1908 } 1909 } 1910 1911 /// EmitObjCIvarInitializations - Emit information for ivar initialization 1912 /// for an implementation. 1913 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 1914 if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0) 1915 return; 1916 DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D)); 1917 assert(DC && "EmitObjCIvarInitializations - null DeclContext"); 1918 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 1919 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 1920 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(), 1921 D->getLocation(), 1922 D->getLocation(), cxxSelector, 1923 getContext().VoidTy, 0, 1924 DC, true, false, true, false, 1925 ObjCMethodDecl::Required); 1926 D->addInstanceMethod(DTORMethod); 1927 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 1928 1929 II = &getContext().Idents.get(".cxx_construct"); 1930 cxxSelector = getContext().Selectors.getSelector(0, &II); 1931 // The constructor returns 'self'. 1932 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 1933 D->getLocation(), 1934 D->getLocation(), cxxSelector, 1935 getContext().getObjCIdType(), 0, 1936 DC, true, false, true, false, 1937 ObjCMethodDecl::Required); 1938 D->addInstanceMethod(CTORMethod); 1939 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 1940 1941 1942 } 1943 1944 /// EmitNamespace - Emit all declarations in a namespace. 1945 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 1946 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 1947 I != E; ++I) 1948 EmitTopLevelDecl(*I); 1949 } 1950 1951 // EmitLinkageSpec - Emit all declarations in a linkage spec. 1952 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 1953 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 1954 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 1955 ErrorUnsupported(LSD, "linkage spec"); 1956 return; 1957 } 1958 1959 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 1960 I != E; ++I) 1961 EmitTopLevelDecl(*I); 1962 } 1963 1964 /// EmitTopLevelDecl - Emit code for a single top level declaration. 1965 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1966 // If an error has occurred, stop code generation, but continue 1967 // parsing and semantic analysis (to ensure all warnings and errors 1968 // are emitted). 1969 if (Diags.hasErrorOccurred()) 1970 return; 1971 1972 // Ignore dependent declarations. 1973 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 1974 return; 1975 1976 switch (D->getKind()) { 1977 case Decl::CXXConversion: 1978 case Decl::CXXMethod: 1979 case Decl::Function: 1980 // Skip function templates 1981 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1982 return; 1983 1984 EmitGlobal(cast<FunctionDecl>(D)); 1985 break; 1986 1987 case Decl::Var: 1988 EmitGlobal(cast<VarDecl>(D)); 1989 break; 1990 1991 // C++ Decls 1992 case Decl::Namespace: 1993 EmitNamespace(cast<NamespaceDecl>(D)); 1994 break; 1995 // No code generation needed. 1996 case Decl::UsingShadow: 1997 case Decl::Using: 1998 case Decl::UsingDirective: 1999 case Decl::ClassTemplate: 2000 case Decl::FunctionTemplate: 2001 case Decl::NamespaceAlias: 2002 break; 2003 case Decl::CXXConstructor: 2004 // Skip function templates 2005 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 2006 return; 2007 2008 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 2009 break; 2010 case Decl::CXXDestructor: 2011 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 2012 break; 2013 2014 case Decl::StaticAssert: 2015 // Nothing to do. 2016 break; 2017 2018 // Objective-C Decls 2019 2020 // Forward declarations, no (immediate) code generation. 2021 case Decl::ObjCClass: 2022 case Decl::ObjCForwardProtocol: 2023 case Decl::ObjCInterface: 2024 break; 2025 2026 case Decl::ObjCCategory: { 2027 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D); 2028 if (CD->IsClassExtension() && CD->hasSynthBitfield()) 2029 Context.ResetObjCLayout(CD->getClassInterface()); 2030 break; 2031 } 2032 2033 2034 case Decl::ObjCProtocol: 2035 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 2036 break; 2037 2038 case Decl::ObjCCategoryImpl: 2039 // Categories have properties but don't support synthesize so we 2040 // can ignore them here. 2041 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 2042 break; 2043 2044 case Decl::ObjCImplementation: { 2045 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 2046 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield()) 2047 Context.ResetObjCLayout(OMD->getClassInterface()); 2048 EmitObjCPropertyImplementations(OMD); 2049 EmitObjCIvarInitializations(OMD); 2050 Runtime->GenerateClass(OMD); 2051 break; 2052 } 2053 case Decl::ObjCMethod: { 2054 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 2055 // If this is not a prototype, emit the body. 2056 if (OMD->getBody()) 2057 CodeGenFunction(*this).GenerateObjCMethod(OMD); 2058 break; 2059 } 2060 case Decl::ObjCCompatibleAlias: 2061 // compatibility-alias is a directive and has no code gen. 2062 break; 2063 2064 case Decl::LinkageSpec: 2065 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 2066 break; 2067 2068 case Decl::FileScopeAsm: { 2069 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 2070 llvm::StringRef AsmString = AD->getAsmString()->getString(); 2071 2072 const std::string &S = getModule().getModuleInlineAsm(); 2073 if (S.empty()) 2074 getModule().setModuleInlineAsm(AsmString); 2075 else 2076 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 2077 break; 2078 } 2079 2080 default: 2081 // Make sure we handled everything we should, every other kind is a 2082 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 2083 // function. Need to recode Decl::Kind to do that easily. 2084 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 2085 } 2086 } 2087 2088 /// Turns the given pointer into a constant. 2089 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 2090 const void *Ptr) { 2091 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 2092 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 2093 return llvm::ConstantInt::get(i64, PtrInt); 2094 } 2095 2096 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 2097 llvm::NamedMDNode *&GlobalMetadata, 2098 GlobalDecl D, 2099 llvm::GlobalValue *Addr) { 2100 if (!GlobalMetadata) 2101 GlobalMetadata = 2102 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 2103 2104 // TODO: should we report variant information for ctors/dtors? 2105 llvm::Value *Ops[] = { 2106 Addr, 2107 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 2108 }; 2109 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2)); 2110 } 2111 2112 /// Emits metadata nodes associating all the global values in the 2113 /// current module with the Decls they came from. This is useful for 2114 /// projects using IR gen as a subroutine. 2115 /// 2116 /// Since there's currently no way to associate an MDNode directly 2117 /// with an llvm::GlobalValue, we create a global named metadata 2118 /// with the name 'clang.global.decl.ptrs'. 2119 void CodeGenModule::EmitDeclMetadata() { 2120 llvm::NamedMDNode *GlobalMetadata = 0; 2121 2122 // StaticLocalDeclMap 2123 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator 2124 I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 2125 I != E; ++I) { 2126 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 2127 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 2128 } 2129 } 2130 2131 /// Emits metadata nodes for all the local variables in the current 2132 /// function. 2133 void CodeGenFunction::EmitDeclMetadata() { 2134 if (LocalDeclMap.empty()) return; 2135 2136 llvm::LLVMContext &Context = getLLVMContext(); 2137 2138 // Find the unique metadata ID for this name. 2139 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 2140 2141 llvm::NamedMDNode *GlobalMetadata = 0; 2142 2143 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 2144 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 2145 const Decl *D = I->first; 2146 llvm::Value *Addr = I->second; 2147 2148 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 2149 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 2150 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1)); 2151 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 2152 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 2153 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 2154 } 2155 } 2156 } 2157 2158 ///@name Custom Runtime Function Interfaces 2159 ///@{ 2160 // 2161 // FIXME: These can be eliminated once we can have clients just get the required 2162 // AST nodes from the builtin tables. 2163 2164 llvm::Constant *CodeGenModule::getBlockObjectDispose() { 2165 if (BlockObjectDispose) 2166 return BlockObjectDispose; 2167 2168 // If we saw an explicit decl, use that. 2169 if (BlockObjectDisposeDecl) { 2170 return BlockObjectDispose = GetAddrOfFunction( 2171 BlockObjectDisposeDecl, 2172 getTypes().GetFunctionType(BlockObjectDisposeDecl)); 2173 } 2174 2175 // Otherwise construct the function by hand. 2176 const llvm::FunctionType *FTy; 2177 std::vector<const llvm::Type*> ArgTys; 2178 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext); 2179 ArgTys.push_back(Int8PtrTy); 2180 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext)); 2181 FTy = llvm::FunctionType::get(ResultType, ArgTys, false); 2182 return BlockObjectDispose = 2183 CreateRuntimeFunction(FTy, "_Block_object_dispose"); 2184 } 2185 2186 llvm::Constant *CodeGenModule::getBlockObjectAssign() { 2187 if (BlockObjectAssign) 2188 return BlockObjectAssign; 2189 2190 // If we saw an explicit decl, use that. 2191 if (BlockObjectAssignDecl) { 2192 return BlockObjectAssign = GetAddrOfFunction( 2193 BlockObjectAssignDecl, 2194 getTypes().GetFunctionType(BlockObjectAssignDecl)); 2195 } 2196 2197 // Otherwise construct the function by hand. 2198 const llvm::FunctionType *FTy; 2199 std::vector<const llvm::Type*> ArgTys; 2200 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext); 2201 ArgTys.push_back(Int8PtrTy); 2202 ArgTys.push_back(Int8PtrTy); 2203 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext)); 2204 FTy = llvm::FunctionType::get(ResultType, ArgTys, false); 2205 return BlockObjectAssign = 2206 CreateRuntimeFunction(FTy, "_Block_object_assign"); 2207 } 2208 2209 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() { 2210 if (NSConcreteGlobalBlock) 2211 return NSConcreteGlobalBlock; 2212 2213 // If we saw an explicit decl, use that. 2214 if (NSConcreteGlobalBlockDecl) { 2215 return NSConcreteGlobalBlock = GetAddrOfGlobalVar( 2216 NSConcreteGlobalBlockDecl, 2217 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType())); 2218 } 2219 2220 // Otherwise construct the variable by hand. 2221 return NSConcreteGlobalBlock = 2222 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteGlobalBlock"); 2223 } 2224 2225 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() { 2226 if (NSConcreteStackBlock) 2227 return NSConcreteStackBlock; 2228 2229 // If we saw an explicit decl, use that. 2230 if (NSConcreteStackBlockDecl) { 2231 return NSConcreteStackBlock = GetAddrOfGlobalVar( 2232 NSConcreteStackBlockDecl, 2233 getTypes().ConvertType(NSConcreteStackBlockDecl->getType())); 2234 } 2235 2236 // Otherwise construct the variable by hand. 2237 return NSConcreteStackBlock = 2238 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteStackBlock"); 2239 } 2240 2241 ///@} 2242