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