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