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