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