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