CodeGenModule.cpp revision dd851595cb9123558c9029efdadb1b4be9881a3d
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 "CGCUDARuntime.h" 20#include "CGCXXABI.h" 21#include "CGObjCRuntime.h" 22#include "CGOpenCLRuntime.h" 23#include "TargetInfo.h" 24#include "clang/Frontend/CodeGenOptions.h" 25#include "clang/AST/ASTContext.h" 26#include "clang/AST/CharUnits.h" 27#include "clang/AST/DeclObjC.h" 28#include "clang/AST/DeclCXX.h" 29#include "clang/AST/DeclTemplate.h" 30#include "clang/AST/Mangle.h" 31#include "clang/AST/RecordLayout.h" 32#include "clang/AST/RecursiveASTVisitor.h" 33#include "clang/Basic/Builtins.h" 34#include "clang/Basic/Diagnostic.h" 35#include "clang/Basic/SourceManager.h" 36#include "clang/Basic/TargetInfo.h" 37#include "clang/Basic/ConvertUTF.h" 38#include "llvm/CallingConv.h" 39#include "llvm/Module.h" 40#include "llvm/Intrinsics.h" 41#include "llvm/LLVMContext.h" 42#include "llvm/ADT/APSInt.h" 43#include "llvm/ADT/Triple.h" 44#include "llvm/Target/Mangler.h" 45#include "llvm/DataLayout.h" 46#include "llvm/Support/CallSite.h" 47#include "llvm/Support/ErrorHandling.h" 48using namespace clang; 49using namespace CodeGen; 50 51static const char AnnotationSection[] = "llvm.metadata"; 52 53static CGCXXABI &createCXXABI(CodeGenModule &CGM) { 54 switch (CGM.getContext().getTargetInfo().getCXXABI()) { 55 case CXXABI_ARM: return *CreateARMCXXABI(CGM); 56 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM); 57 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM); 58 } 59 60 llvm_unreachable("invalid C++ ABI kind"); 61} 62 63 64CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 65 llvm::Module &M, const llvm::DataLayout &TD, 66 DiagnosticsEngine &diags) 67 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M), 68 TheDataLayout(TD), TheTargetCodeGenInfo(0), Diags(diags), 69 ABI(createCXXABI(*this)), 70 Types(*this), 71 TBAA(0), 72 VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0), 73 DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0), 74 RRData(0), CFConstantStringClassRef(0), 75 ConstantStringClassRef(0), NSConstantStringType(0), 76 VMContext(M.getContext()), 77 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), 78 BlockObjectAssign(0), BlockObjectDispose(0), 79 BlockDescriptorType(0), GenericBlockLiteralType(0) { 80 81 // Initialize the type cache. 82 llvm::LLVMContext &LLVMContext = M.getContext(); 83 VoidTy = llvm::Type::getVoidTy(LLVMContext); 84 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 85 Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 86 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 87 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 88 FloatTy = llvm::Type::getFloatTy(LLVMContext); 89 DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 90 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 91 PointerAlignInBytes = 92 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 93 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 94 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 95 Int8PtrTy = Int8Ty->getPointerTo(0); 96 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 97 98 if (LangOpts.ObjC1) 99 createObjCRuntime(); 100 if (LangOpts.OpenCL) 101 createOpenCLRuntime(); 102 if (LangOpts.CUDA) 103 createCUDARuntime(); 104 105 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 106 if (LangOpts.SanitizeThread || 107 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 108 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 109 ABI.getMangleContext()); 110 111 // If debug info or coverage generation is enabled, create the CGDebugInfo 112 // object. 113 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo || 114 CodeGenOpts.EmitGcovArcs || 115 CodeGenOpts.EmitGcovNotes) 116 DebugInfo = new CGDebugInfo(*this); 117 118 Block.GlobalUniqueCount = 0; 119 120 if (C.getLangOpts().ObjCAutoRefCount) 121 ARCData = new ARCEntrypoints(); 122 RRData = new RREntrypoints(); 123} 124 125CodeGenModule::~CodeGenModule() { 126 delete ObjCRuntime; 127 delete OpenCLRuntime; 128 delete CUDARuntime; 129 delete TheTargetCodeGenInfo; 130 delete &ABI; 131 delete TBAA; 132 delete DebugInfo; 133 delete ARCData; 134 delete RRData; 135} 136 137void CodeGenModule::createObjCRuntime() { 138 // This is just isGNUFamily(), but we want to force implementors of 139 // new ABIs to decide how best to do this. 140 switch (LangOpts.ObjCRuntime.getKind()) { 141 case ObjCRuntime::GNUstep: 142 case ObjCRuntime::GCC: 143 case ObjCRuntime::ObjFW: 144 ObjCRuntime = CreateGNUObjCRuntime(*this); 145 return; 146 147 case ObjCRuntime::FragileMacOSX: 148 case ObjCRuntime::MacOSX: 149 case ObjCRuntime::iOS: 150 ObjCRuntime = CreateMacObjCRuntime(*this); 151 return; 152 } 153 llvm_unreachable("bad runtime kind"); 154} 155 156void CodeGenModule::createOpenCLRuntime() { 157 OpenCLRuntime = new CGOpenCLRuntime(*this); 158} 159 160void CodeGenModule::createCUDARuntime() { 161 CUDARuntime = CreateNVCUDARuntime(*this); 162} 163 164void CodeGenModule::Release() { 165 EmitDeferred(); 166 EmitCXXGlobalInitFunc(); 167 EmitCXXGlobalDtorFunc(); 168 if (ObjCRuntime) 169 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 170 AddGlobalCtor(ObjCInitFunction); 171 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 172 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 173 EmitGlobalAnnotations(); 174 EmitLLVMUsed(); 175 176 SimplifyPersonality(); 177 178 if (getCodeGenOpts().EmitDeclMetadata) 179 EmitDeclMetadata(); 180 181 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 182 EmitCoverageFile(); 183 184 if (DebugInfo) 185 DebugInfo->finalize(); 186} 187 188void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 189 // Make sure that this type is translated. 190 Types.UpdateCompletedType(TD); 191} 192 193llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 194 if (!TBAA) 195 return 0; 196 return TBAA->getTBAAInfo(QTy); 197} 198 199llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 200 if (!TBAA) 201 return 0; 202 return TBAA->getTBAAInfoForVTablePtr(); 203} 204 205llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 206 if (!TBAA) 207 return 0; 208 return TBAA->getTBAAStructInfo(QTy); 209} 210 211void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 212 llvm::MDNode *TBAAInfo) { 213 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 214} 215 216bool CodeGenModule::isTargetDarwin() const { 217 return getContext().getTargetInfo().getTriple().isOSDarwin(); 218} 219 220void CodeGenModule::Error(SourceLocation loc, StringRef error) { 221 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error); 222 getDiags().Report(Context.getFullLoc(loc), diagID); 223} 224 225/// ErrorUnsupported - Print out an error that codegen doesn't support the 226/// specified stmt yet. 227void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 228 bool OmitOnError) { 229 if (OmitOnError && getDiags().hasErrorOccurred()) 230 return; 231 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 232 "cannot compile this %0 yet"); 233 std::string Msg = Type; 234 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 235 << Msg << S->getSourceRange(); 236} 237 238/// ErrorUnsupported - Print out an error that codegen doesn't support the 239/// specified decl yet. 240void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 241 bool OmitOnError) { 242 if (OmitOnError && getDiags().hasErrorOccurred()) 243 return; 244 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 245 "cannot compile this %0 yet"); 246 std::string Msg = Type; 247 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 248} 249 250llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 251 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 252} 253 254void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 255 const NamedDecl *D) const { 256 // Internal definitions always have default visibility. 257 if (GV->hasLocalLinkage()) { 258 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 259 return; 260 } 261 262 // Set visibility for definitions. 263 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility(); 264 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 265 GV->setVisibility(GetLLVMVisibility(LV.visibility())); 266} 267 268static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 269 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 270 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 271 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 272 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 273 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 274} 275 276static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 277 CodeGenOptions::TLSModel M) { 278 switch (M) { 279 case CodeGenOptions::GeneralDynamicTLSModel: 280 return llvm::GlobalVariable::GeneralDynamicTLSModel; 281 case CodeGenOptions::LocalDynamicTLSModel: 282 return llvm::GlobalVariable::LocalDynamicTLSModel; 283 case CodeGenOptions::InitialExecTLSModel: 284 return llvm::GlobalVariable::InitialExecTLSModel; 285 case CodeGenOptions::LocalExecTLSModel: 286 return llvm::GlobalVariable::LocalExecTLSModel; 287 } 288 llvm_unreachable("Invalid TLS model!"); 289} 290 291void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV, 292 const VarDecl &D) const { 293 assert(D.isThreadSpecified() && "setting TLS mode on non-TLS var!"); 294 295 llvm::GlobalVariable::ThreadLocalMode TLM; 296 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 297 298 // Override the TLS model if it is explicitly specified. 299 if (D.hasAttr<TLSModelAttr>()) { 300 const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>(); 301 TLM = GetLLVMTLSModel(Attr->getModel()); 302 } 303 304 GV->setThreadLocalMode(TLM); 305} 306 307/// Set the symbol visibility of type information (vtable and RTTI) 308/// associated with the given type. 309void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV, 310 const CXXRecordDecl *RD, 311 TypeVisibilityKind TVK) const { 312 setGlobalVisibility(GV, RD); 313 314 if (!CodeGenOpts.HiddenWeakVTables) 315 return; 316 317 // We never want to drop the visibility for RTTI names. 318 if (TVK == TVK_ForRTTIName) 319 return; 320 321 // We want to drop the visibility to hidden for weak type symbols. 322 // This isn't possible if there might be unresolved references 323 // elsewhere that rely on this symbol being visible. 324 325 // This should be kept roughly in sync with setThunkVisibility 326 // in CGVTables.cpp. 327 328 // Preconditions. 329 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage || 330 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility) 331 return; 332 333 // Don't override an explicit visibility attribute. 334 if (RD->getExplicitVisibility()) 335 return; 336 337 switch (RD->getTemplateSpecializationKind()) { 338 // We have to disable the optimization if this is an EI definition 339 // because there might be EI declarations in other shared objects. 340 case TSK_ExplicitInstantiationDefinition: 341 case TSK_ExplicitInstantiationDeclaration: 342 return; 343 344 // Every use of a non-template class's type information has to emit it. 345 case TSK_Undeclared: 346 break; 347 348 // In theory, implicit instantiations can ignore the possibility of 349 // an explicit instantiation declaration because there necessarily 350 // must be an EI definition somewhere with default visibility. In 351 // practice, it's possible to have an explicit instantiation for 352 // an arbitrary template class, and linkers aren't necessarily able 353 // to deal with mixed-visibility symbols. 354 case TSK_ExplicitSpecialization: 355 case TSK_ImplicitInstantiation: 356 return; 357 } 358 359 // If there's a key function, there may be translation units 360 // that don't have the key function's definition. But ignore 361 // this if we're emitting RTTI under -fno-rtti. 362 if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) { 363 if (Context.getKeyFunction(RD)) 364 return; 365 } 366 367 // Otherwise, drop the visibility to hidden. 368 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 369 GV->setUnnamedAddr(true); 370} 371 372StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 373 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 374 375 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 376 if (!Str.empty()) 377 return Str; 378 379 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 380 IdentifierInfo *II = ND->getIdentifier(); 381 assert(II && "Attempt to mangle unnamed decl."); 382 383 Str = II->getName(); 384 return Str; 385 } 386 387 SmallString<256> Buffer; 388 llvm::raw_svector_ostream Out(Buffer); 389 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 390 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 391 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 392 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 393 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND)) 394 getCXXABI().getMangleContext().mangleBlock(BD, Out, 395 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl())); 396 else 397 getCXXABI().getMangleContext().mangleName(ND, Out); 398 399 // Allocate space for the mangled name. 400 Out.flush(); 401 size_t Length = Buffer.size(); 402 char *Name = MangledNamesAllocator.Allocate<char>(Length); 403 std::copy(Buffer.begin(), Buffer.end(), Name); 404 405 Str = StringRef(Name, Length); 406 407 return Str; 408} 409 410void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 411 const BlockDecl *BD) { 412 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 413 const Decl *D = GD.getDecl(); 414 llvm::raw_svector_ostream Out(Buffer.getBuffer()); 415 if (D == 0) 416 MangleCtx.mangleGlobalBlock(BD, 417 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 418 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 419 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 420 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 421 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 422 else 423 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 424} 425 426llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 427 return getModule().getNamedValue(Name); 428} 429 430/// AddGlobalCtor - Add a function to the list that will be called before 431/// main() runs. 432void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 433 // FIXME: Type coercion of void()* types. 434 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 435} 436 437/// AddGlobalDtor - Add a function to the list that will be called 438/// when the module is unloaded. 439void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 440 // FIXME: Type coercion of void()* types. 441 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 442} 443 444void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 445 // Ctor function type is void()*. 446 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 447 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 448 449 // Get the type of a ctor entry, { i32, void ()* }. 450 llvm::StructType *CtorStructTy = 451 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL); 452 453 // Construct the constructor and destructor arrays. 454 SmallVector<llvm::Constant*, 8> Ctors; 455 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 456 llvm::Constant *S[] = { 457 llvm::ConstantInt::get(Int32Ty, I->second, false), 458 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy) 459 }; 460 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 461 } 462 463 if (!Ctors.empty()) { 464 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 465 new llvm::GlobalVariable(TheModule, AT, false, 466 llvm::GlobalValue::AppendingLinkage, 467 llvm::ConstantArray::get(AT, Ctors), 468 GlobalName); 469 } 470} 471 472llvm::GlobalValue::LinkageTypes 473CodeGenModule::getFunctionLinkage(const FunctionDecl *D) { 474 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 475 476 if (Linkage == GVA_Internal) 477 return llvm::Function::InternalLinkage; 478 479 if (D->hasAttr<DLLExportAttr>()) 480 return llvm::Function::DLLExportLinkage; 481 482 if (D->hasAttr<WeakAttr>()) 483 return llvm::Function::WeakAnyLinkage; 484 485 // In C99 mode, 'inline' functions are guaranteed to have a strong 486 // definition somewhere else, so we can use available_externally linkage. 487 if (Linkage == GVA_C99Inline) 488 return llvm::Function::AvailableExternallyLinkage; 489 490 // Note that Apple's kernel linker doesn't support symbol 491 // coalescing, so we need to avoid linkonce and weak linkages there. 492 // Normally, this means we just map to internal, but for explicit 493 // instantiations we'll map to external. 494 495 // In C++, the compiler has to emit a definition in every translation unit 496 // that references the function. We should use linkonce_odr because 497 // a) if all references in this translation unit are optimized away, we 498 // don't need to codegen it. b) if the function persists, it needs to be 499 // merged with other definitions. c) C++ has the ODR, so we know the 500 // definition is dependable. 501 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 502 return !Context.getLangOpts().AppleKext 503 ? llvm::Function::LinkOnceODRLinkage 504 : llvm::Function::InternalLinkage; 505 506 // An explicit instantiation of a template has weak linkage, since 507 // explicit instantiations can occur in multiple translation units 508 // and must all be equivalent. However, we are not allowed to 509 // throw away these explicit instantiations. 510 if (Linkage == GVA_ExplicitTemplateInstantiation) 511 return !Context.getLangOpts().AppleKext 512 ? llvm::Function::WeakODRLinkage 513 : llvm::Function::ExternalLinkage; 514 515 // Otherwise, we have strong external linkage. 516 assert(Linkage == GVA_StrongExternal); 517 return llvm::Function::ExternalLinkage; 518} 519 520 521/// SetFunctionDefinitionAttributes - Set attributes for a global. 522/// 523/// FIXME: This is currently only done for aliases and functions, but not for 524/// variables (these details are set in EmitGlobalVarDefinition for variables). 525void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 526 llvm::GlobalValue *GV) { 527 SetCommonAttributes(D, GV); 528} 529 530void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 531 const CGFunctionInfo &Info, 532 llvm::Function *F) { 533 unsigned CallingConv; 534 AttributeListType AttributeList; 535 ConstructAttributeList(Info, D, AttributeList, CallingConv); 536 F->setAttributes(llvm::AttrListPtr::get(getLLVMContext(), AttributeList)); 537 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 538} 539 540/// Determines whether the language options require us to model 541/// unwind exceptions. We treat -fexceptions as mandating this 542/// except under the fragile ObjC ABI with only ObjC exceptions 543/// enabled. This means, for example, that C with -fexceptions 544/// enables this. 545static bool hasUnwindExceptions(const LangOptions &LangOpts) { 546 // If exceptions are completely disabled, obviously this is false. 547 if (!LangOpts.Exceptions) return false; 548 549 // If C++ exceptions are enabled, this is true. 550 if (LangOpts.CXXExceptions) return true; 551 552 // If ObjC exceptions are enabled, this depends on the ABI. 553 if (LangOpts.ObjCExceptions) { 554 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 555 } 556 557 return true; 558} 559 560void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 561 llvm::Function *F) { 562 if (CodeGenOpts.UnwindTables) 563 F->setHasUWTable(); 564 565 if (!hasUnwindExceptions(LangOpts)) 566 F->addFnAttr(llvm::Attributes::NoUnwind); 567 568 if (D->hasAttr<NakedAttr>()) { 569 // Naked implies noinline: we should not be inlining such functions. 570 F->addFnAttr(llvm::Attributes::Naked); 571 F->addFnAttr(llvm::Attributes::NoInline); 572 } 573 574 if (D->hasAttr<NoInlineAttr>()) 575 F->addFnAttr(llvm::Attributes::NoInline); 576 577 // (noinline wins over always_inline, and we can't specify both in IR) 578 if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) && 579 !F->getFnAttributes().hasAttribute(llvm::Attributes::NoInline)) 580 F->addFnAttr(llvm::Attributes::AlwaysInline); 581 582 // FIXME: Communicate hot and cold attributes to LLVM more directly. 583 if (D->hasAttr<ColdAttr>()) 584 F->addFnAttr(llvm::Attributes::OptimizeForSize); 585 586 if (D->hasAttr<MinSizeAttr>()) 587 F->addFnAttr(llvm::Attributes::MinSize); 588 589 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 590 F->setUnnamedAddr(true); 591 592 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 593 if (MD->isVirtual()) 594 F->setUnnamedAddr(true); 595 596 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 597 F->addFnAttr(llvm::Attributes::StackProtect); 598 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 599 F->addFnAttr(llvm::Attributes::StackProtectReq); 600 601 if (LangOpts.SanitizeAddress) { 602 // When AddressSanitizer is enabled, set AddressSafety attribute 603 // unless __attribute__((no_address_safety_analysis)) is used. 604 if (!D->hasAttr<NoAddressSafetyAnalysisAttr>()) 605 F->addFnAttr(llvm::Attributes::AddressSafety); 606 } 607 608 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 609 if (alignment) 610 F->setAlignment(alignment); 611 612 // C++ ABI requires 2-byte alignment for member functions. 613 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 614 F->setAlignment(2); 615} 616 617void CodeGenModule::SetCommonAttributes(const Decl *D, 618 llvm::GlobalValue *GV) { 619 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 620 setGlobalVisibility(GV, ND); 621 else 622 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 623 624 if (D->hasAttr<UsedAttr>()) 625 AddUsedGlobal(GV); 626 627 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 628 GV->setSection(SA->getName()); 629 630 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 631} 632 633void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 634 llvm::Function *F, 635 const CGFunctionInfo &FI) { 636 SetLLVMFunctionAttributes(D, FI, F); 637 SetLLVMFunctionAttributesForDefinition(D, F); 638 639 F->setLinkage(llvm::Function::InternalLinkage); 640 641 SetCommonAttributes(D, F); 642} 643 644void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 645 llvm::Function *F, 646 bool IsIncompleteFunction) { 647 if (unsigned IID = F->getIntrinsicID()) { 648 // If this is an intrinsic function, set the function's attributes 649 // to the intrinsic's attributes. 650 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), 651 (llvm::Intrinsic::ID)IID)); 652 return; 653 } 654 655 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 656 657 if (!IsIncompleteFunction) 658 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 659 660 // Only a few attributes are set on declarations; these may later be 661 // overridden by a definition. 662 663 if (FD->hasAttr<DLLImportAttr>()) { 664 F->setLinkage(llvm::Function::DLLImportLinkage); 665 } else if (FD->hasAttr<WeakAttr>() || 666 FD->isWeakImported()) { 667 // "extern_weak" is overloaded in LLVM; we probably should have 668 // separate linkage types for this. 669 F->setLinkage(llvm::Function::ExternalWeakLinkage); 670 } else { 671 F->setLinkage(llvm::Function::ExternalLinkage); 672 673 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility(); 674 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) { 675 F->setVisibility(GetLLVMVisibility(LV.visibility())); 676 } 677 } 678 679 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 680 F->setSection(SA->getName()); 681} 682 683void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 684 assert(!GV->isDeclaration() && 685 "Only globals with definition can force usage."); 686 LLVMUsed.push_back(GV); 687} 688 689void CodeGenModule::EmitLLVMUsed() { 690 // Don't create llvm.used if there is no need. 691 if (LLVMUsed.empty()) 692 return; 693 694 // Convert LLVMUsed to what ConstantArray needs. 695 SmallVector<llvm::Constant*, 8> UsedArray; 696 UsedArray.resize(LLVMUsed.size()); 697 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 698 UsedArray[i] = 699 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 700 Int8PtrTy); 701 } 702 703 if (UsedArray.empty()) 704 return; 705 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size()); 706 707 llvm::GlobalVariable *GV = 708 new llvm::GlobalVariable(getModule(), ATy, false, 709 llvm::GlobalValue::AppendingLinkage, 710 llvm::ConstantArray::get(ATy, UsedArray), 711 "llvm.used"); 712 713 GV->setSection("llvm.metadata"); 714} 715 716void CodeGenModule::EmitDeferred() { 717 // Emit code for any potentially referenced deferred decls. Since a 718 // previously unused static decl may become used during the generation of code 719 // for a static function, iterate until no changes are made. 720 721 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) { 722 if (!DeferredVTables.empty()) { 723 const CXXRecordDecl *RD = DeferredVTables.back(); 724 DeferredVTables.pop_back(); 725 getCXXABI().EmitVTables(RD); 726 continue; 727 } 728 729 GlobalDecl D = DeferredDeclsToEmit.back(); 730 DeferredDeclsToEmit.pop_back(); 731 732 // Check to see if we've already emitted this. This is necessary 733 // for a couple of reasons: first, decls can end up in the 734 // deferred-decls queue multiple times, and second, decls can end 735 // up with definitions in unusual ways (e.g. by an extern inline 736 // function acquiring a strong function redefinition). Just 737 // ignore these cases. 738 // 739 // TODO: That said, looking this up multiple times is very wasteful. 740 StringRef Name = getMangledName(D); 741 llvm::GlobalValue *CGRef = GetGlobalValue(Name); 742 assert(CGRef && "Deferred decl wasn't referenced?"); 743 744 if (!CGRef->isDeclaration()) 745 continue; 746 747 // GlobalAlias::isDeclaration() defers to the aliasee, but for our 748 // purposes an alias counts as a definition. 749 if (isa<llvm::GlobalAlias>(CGRef)) 750 continue; 751 752 // Otherwise, emit the definition and move on to the next one. 753 EmitGlobalDefinition(D); 754 } 755} 756 757void CodeGenModule::EmitGlobalAnnotations() { 758 if (Annotations.empty()) 759 return; 760 761 // Create a new global variable for the ConstantStruct in the Module. 762 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 763 Annotations[0]->getType(), Annotations.size()), Annotations); 764 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), 765 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array, 766 "llvm.global.annotations"); 767 gv->setSection(AnnotationSection); 768} 769 770llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) { 771 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str); 772 if (i != AnnotationStrings.end()) 773 return i->second; 774 775 // Not found yet, create a new global. 776 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 777 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(), 778 true, llvm::GlobalValue::PrivateLinkage, s, ".str"); 779 gv->setSection(AnnotationSection); 780 gv->setUnnamedAddr(true); 781 AnnotationStrings[Str] = gv; 782 return gv; 783} 784 785llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 786 SourceManager &SM = getContext().getSourceManager(); 787 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 788 if (PLoc.isValid()) 789 return EmitAnnotationString(PLoc.getFilename()); 790 return EmitAnnotationString(SM.getBufferName(Loc)); 791} 792 793llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 794 SourceManager &SM = getContext().getSourceManager(); 795 PresumedLoc PLoc = SM.getPresumedLoc(L); 796 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 797 SM.getExpansionLineNumber(L); 798 return llvm::ConstantInt::get(Int32Ty, LineNo); 799} 800 801llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 802 const AnnotateAttr *AA, 803 SourceLocation L) { 804 // Get the globals for file name, annotation, and the line number. 805 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 806 *UnitGV = EmitAnnotationUnit(L), 807 *LineNoCst = EmitAnnotationLineNo(L); 808 809 // Create the ConstantStruct for the global annotation. 810 llvm::Constant *Fields[4] = { 811 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 812 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 813 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 814 LineNoCst 815 }; 816 return llvm::ConstantStruct::getAnon(Fields); 817} 818 819void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 820 llvm::GlobalValue *GV) { 821 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 822 // Get the struct elements for these annotations. 823 for (specific_attr_iterator<AnnotateAttr> 824 ai = D->specific_attr_begin<AnnotateAttr>(), 825 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) 826 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation())); 827} 828 829bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 830 // Never defer when EmitAllDecls is specified. 831 if (LangOpts.EmitAllDecls) 832 return false; 833 834 return !getContext().DeclMustBeEmitted(Global); 835} 836 837llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor( 838 const CXXUuidofExpr* E) { 839 // Sema has verified that IIDSource has a __declspec(uuid()), and that its 840 // well-formed. 841 StringRef Uuid; 842 if (E->isTypeOperand()) 843 Uuid = CXXUuidofExpr::GetUuidAttrOfType(E->getTypeOperand())->getGuid(); 844 else { 845 // Special case: __uuidof(0) means an all-zero GUID. 846 Expr *Op = E->getExprOperand(); 847 if (!Op->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 848 Uuid = CXXUuidofExpr::GetUuidAttrOfType(Op->getType())->getGuid(); 849 else 850 Uuid = "00000000-0000-0000-0000-000000000000"; 851 } 852 std::string Name = "__uuid_" + Uuid.str(); 853 854 // Look for an existing global. 855 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 856 return GV; 857 858 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType()); 859 assert(Init && "failed to initialize as constant"); 860 861 // GUIDs are assumed to be 16 bytes, spread over 4-2-2-8 bytes. However, the 862 // first field is declared as "long", which for many targets is 8 bytes. 863 // Those architectures are not supported. (With the MS abi, long is always 4 864 // bytes.) 865 llvm::Type *GuidType = getTypes().ConvertType(E->getType()); 866 if (Init->getType() != GuidType) { 867 DiagnosticsEngine &Diags = getDiags(); 868 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 869 "__uuidof codegen is not supported on this architecture"); 870 Diags.Report(E->getExprLoc(), DiagID) << E->getSourceRange(); 871 Init = llvm::UndefValue::get(GuidType); 872 } 873 874 llvm::GlobalVariable *GV = new llvm::GlobalVariable(getModule(), GuidType, 875 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Init, Name); 876 GV->setUnnamedAddr(true); 877 return GV; 878} 879 880llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 881 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 882 assert(AA && "No alias?"); 883 884 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 885 886 // See if there is already something with the target's name in the module. 887 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 888 if (Entry) { 889 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 890 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 891 } 892 893 llvm::Constant *Aliasee; 894 if (isa<llvm::FunctionType>(DeclTy)) 895 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 896 GlobalDecl(cast<FunctionDecl>(VD)), 897 /*ForVTable=*/false); 898 else 899 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 900 llvm::PointerType::getUnqual(DeclTy), 0); 901 902 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 903 F->setLinkage(llvm::Function::ExternalWeakLinkage); 904 WeakRefReferences.insert(F); 905 906 return Aliasee; 907} 908 909void CodeGenModule::EmitGlobal(GlobalDecl GD) { 910 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 911 912 // Weak references don't produce any output by themselves. 913 if (Global->hasAttr<WeakRefAttr>()) 914 return; 915 916 // If this is an alias definition (which otherwise looks like a declaration) 917 // emit it now. 918 if (Global->hasAttr<AliasAttr>()) 919 return EmitAliasDefinition(GD); 920 921 // If this is CUDA, be selective about which declarations we emit. 922 if (LangOpts.CUDA) { 923 if (CodeGenOpts.CUDAIsDevice) { 924 if (!Global->hasAttr<CUDADeviceAttr>() && 925 !Global->hasAttr<CUDAGlobalAttr>() && 926 !Global->hasAttr<CUDAConstantAttr>() && 927 !Global->hasAttr<CUDASharedAttr>()) 928 return; 929 } else { 930 if (!Global->hasAttr<CUDAHostAttr>() && ( 931 Global->hasAttr<CUDADeviceAttr>() || 932 Global->hasAttr<CUDAConstantAttr>() || 933 Global->hasAttr<CUDASharedAttr>())) 934 return; 935 } 936 } 937 938 // Ignore declarations, they will be emitted on their first use. 939 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 940 // Forward declarations are emitted lazily on first use. 941 if (!FD->doesThisDeclarationHaveABody()) { 942 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 943 return; 944 945 const FunctionDecl *InlineDefinition = 0; 946 FD->getBody(InlineDefinition); 947 948 StringRef MangledName = getMangledName(GD); 949 DeferredDecls.erase(MangledName); 950 EmitGlobalDefinition(InlineDefinition); 951 return; 952 } 953 } else { 954 const VarDecl *VD = cast<VarDecl>(Global); 955 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 956 957 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 958 return; 959 } 960 961 // Defer code generation when possible if this is a static definition, inline 962 // function etc. These we only want to emit if they are used. 963 if (!MayDeferGeneration(Global)) { 964 // Emit the definition if it can't be deferred. 965 EmitGlobalDefinition(GD); 966 return; 967 } 968 969 // If we're deferring emission of a C++ variable with an 970 // initializer, remember the order in which it appeared in the file. 971 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 972 cast<VarDecl>(Global)->hasInit()) { 973 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 974 CXXGlobalInits.push_back(0); 975 } 976 977 // If the value has already been used, add it directly to the 978 // DeferredDeclsToEmit list. 979 StringRef MangledName = getMangledName(GD); 980 if (GetGlobalValue(MangledName)) 981 DeferredDeclsToEmit.push_back(GD); 982 else { 983 // Otherwise, remember that we saw a deferred decl with this name. The 984 // first use of the mangled name will cause it to move into 985 // DeferredDeclsToEmit. 986 DeferredDecls[MangledName] = GD; 987 } 988} 989 990namespace { 991 struct FunctionIsDirectlyRecursive : 992 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 993 const StringRef Name; 994 const Builtin::Context &BI; 995 bool Result; 996 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 997 Name(N), BI(C), Result(false) { 998 } 999 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1000 1001 bool TraverseCallExpr(CallExpr *E) { 1002 const FunctionDecl *FD = E->getDirectCallee(); 1003 if (!FD) 1004 return true; 1005 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1006 if (Attr && Name == Attr->getLabel()) { 1007 Result = true; 1008 return false; 1009 } 1010 unsigned BuiltinID = FD->getBuiltinID(); 1011 if (!BuiltinID) 1012 return true; 1013 StringRef BuiltinName = BI.GetName(BuiltinID); 1014 if (BuiltinName.startswith("__builtin_") && 1015 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1016 Result = true; 1017 return false; 1018 } 1019 return true; 1020 } 1021 }; 1022} 1023 1024// isTriviallyRecursive - Check if this function calls another 1025// decl that, because of the asm attribute or the other decl being a builtin, 1026// ends up pointing to itself. 1027bool 1028CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1029 StringRef Name; 1030 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1031 // asm labels are a special kind of mangling we have to support. 1032 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1033 if (!Attr) 1034 return false; 1035 Name = Attr->getLabel(); 1036 } else { 1037 Name = FD->getName(); 1038 } 1039 1040 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1041 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1042 return Walker.Result; 1043} 1044 1045bool 1046CodeGenModule::shouldEmitFunction(const FunctionDecl *F) { 1047 if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage) 1048 return true; 1049 if (CodeGenOpts.OptimizationLevel == 0 && 1050 !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>()) 1051 return false; 1052 // PR9614. Avoid cases where the source code is lying to us. An available 1053 // externally function should have an equivalent function somewhere else, 1054 // but a function that calls itself is clearly not equivalent to the real 1055 // implementation. 1056 // This happens in glibc's btowc and in some configure checks. 1057 return !isTriviallyRecursive(F); 1058} 1059 1060void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 1061 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1062 1063 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1064 Context.getSourceManager(), 1065 "Generating code for declaration"); 1066 1067 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 1068 // At -O0, don't generate IR for functions with available_externally 1069 // linkage. 1070 if (!shouldEmitFunction(Function)) 1071 return; 1072 1073 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 1074 // Make sure to emit the definition(s) before we emit the thunks. 1075 // This is necessary for the generation of certain thunks. 1076 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 1077 EmitCXXConstructor(CD, GD.getCtorType()); 1078 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method)) 1079 EmitCXXDestructor(DD, GD.getDtorType()); 1080 else 1081 EmitGlobalFunctionDefinition(GD); 1082 1083 if (Method->isVirtual()) 1084 getVTables().EmitThunks(GD); 1085 1086 return; 1087 } 1088 1089 return EmitGlobalFunctionDefinition(GD); 1090 } 1091 1092 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1093 return EmitGlobalVarDefinition(VD); 1094 1095 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1096} 1097 1098/// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1099/// module, create and return an llvm Function with the specified type. If there 1100/// is something in the module with the specified name, return it potentially 1101/// bitcasted to the right type. 1102/// 1103/// If D is non-null, it specifies a decl that correspond to this. This is used 1104/// to set the attributes on the function when it is first created. 1105llvm::Constant * 1106CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 1107 llvm::Type *Ty, 1108 GlobalDecl D, bool ForVTable, 1109 llvm::Attributes ExtraAttrs) { 1110 // Lookup the entry, lazily creating it if necessary. 1111 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1112 if (Entry) { 1113 if (WeakRefReferences.erase(Entry)) { 1114 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 1115 if (FD && !FD->hasAttr<WeakAttr>()) 1116 Entry->setLinkage(llvm::Function::ExternalLinkage); 1117 } 1118 1119 if (Entry->getType()->getElementType() == Ty) 1120 return Entry; 1121 1122 // Make sure the result is of the correct type. 1123 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1124 } 1125 1126 // This function doesn't have a complete type (for example, the return 1127 // type is an incomplete struct). Use a fake type instead, and make 1128 // sure not to try to set attributes. 1129 bool IsIncompleteFunction = false; 1130 1131 llvm::FunctionType *FTy; 1132 if (isa<llvm::FunctionType>(Ty)) { 1133 FTy = cast<llvm::FunctionType>(Ty); 1134 } else { 1135 FTy = llvm::FunctionType::get(VoidTy, false); 1136 IsIncompleteFunction = true; 1137 } 1138 1139 llvm::Function *F = llvm::Function::Create(FTy, 1140 llvm::Function::ExternalLinkage, 1141 MangledName, &getModule()); 1142 assert(F->getName() == MangledName && "name was uniqued!"); 1143 if (D.getDecl()) 1144 SetFunctionAttributes(D, F, IsIncompleteFunction); 1145 if (ExtraAttrs.hasAttributes()) 1146 F->addAttribute(llvm::AttrListPtr::FunctionIndex, ExtraAttrs); 1147 1148 // This is the first use or definition of a mangled name. If there is a 1149 // deferred decl with this name, remember that we need to emit it at the end 1150 // of the file. 1151 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1152 if (DDI != DeferredDecls.end()) { 1153 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1154 // list, and remove it from DeferredDecls (since we don't need it anymore). 1155 DeferredDeclsToEmit.push_back(DDI->second); 1156 DeferredDecls.erase(DDI); 1157 1158 // Otherwise, there are cases we have to worry about where we're 1159 // using a declaration for which we must emit a definition but where 1160 // we might not find a top-level definition: 1161 // - member functions defined inline in their classes 1162 // - friend functions defined inline in some class 1163 // - special member functions with implicit definitions 1164 // If we ever change our AST traversal to walk into class methods, 1165 // this will be unnecessary. 1166 // 1167 // We also don't emit a definition for a function if it's going to be an entry 1168 // in a vtable, unless it's already marked as used. 1169 } else if (getLangOpts().CPlusPlus && D.getDecl()) { 1170 // Look for a declaration that's lexically in a record. 1171 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl()); 1172 FD = FD->getMostRecentDecl(); 1173 do { 1174 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 1175 if (FD->isImplicit() && !ForVTable) { 1176 assert(FD->isUsed() && "Sema didn't mark implicit function as used!"); 1177 DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 1178 break; 1179 } else if (FD->doesThisDeclarationHaveABody()) { 1180 DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 1181 break; 1182 } 1183 } 1184 FD = FD->getPreviousDecl(); 1185 } while (FD); 1186 } 1187 1188 // Make sure the result is of the requested type. 1189 if (!IsIncompleteFunction) { 1190 assert(F->getType()->getElementType() == Ty); 1191 return F; 1192 } 1193 1194 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1195 return llvm::ConstantExpr::getBitCast(F, PTy); 1196} 1197 1198/// GetAddrOfFunction - Return the address of the given function. If Ty is 1199/// non-null, then this function will use the specified type if it has to 1200/// create it (this occurs when we see a definition of the function). 1201llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 1202 llvm::Type *Ty, 1203 bool ForVTable) { 1204 // If there was no specific requested type, just convert it now. 1205 if (!Ty) 1206 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 1207 1208 StringRef MangledName = getMangledName(GD); 1209 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable); 1210} 1211 1212/// CreateRuntimeFunction - Create a new runtime function with the specified 1213/// type and name. 1214llvm::Constant * 1215CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 1216 StringRef Name, 1217 llvm::Attributes ExtraAttrs) { 1218 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 1219 ExtraAttrs); 1220} 1221 1222/// isTypeConstant - Determine whether an object of this type can be emitted 1223/// as a constant. 1224/// 1225/// If ExcludeCtor is true, the duration when the object's constructor runs 1226/// will not be considered. The caller will need to verify that the object is 1227/// not written to during its construction. 1228bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 1229 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 1230 return false; 1231 1232 if (Context.getLangOpts().CPlusPlus) { 1233 if (const CXXRecordDecl *Record 1234 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 1235 return ExcludeCtor && !Record->hasMutableFields() && 1236 Record->hasTrivialDestructor(); 1237 } 1238 1239 return true; 1240} 1241 1242/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1243/// create and return an llvm GlobalVariable with the specified type. If there 1244/// is something in the module with the specified name, return it potentially 1245/// bitcasted to the right type. 1246/// 1247/// If D is non-null, it specifies a decl that correspond to this. This is used 1248/// to set the attributes on the global when it is first created. 1249llvm::Constant * 1250CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 1251 llvm::PointerType *Ty, 1252 const VarDecl *D, 1253 bool UnnamedAddr) { 1254 // Lookup the entry, lazily creating it if necessary. 1255 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1256 if (Entry) { 1257 if (WeakRefReferences.erase(Entry)) { 1258 if (D && !D->hasAttr<WeakAttr>()) 1259 Entry->setLinkage(llvm::Function::ExternalLinkage); 1260 } 1261 1262 if (UnnamedAddr) 1263 Entry->setUnnamedAddr(true); 1264 1265 if (Entry->getType() == Ty) 1266 return Entry; 1267 1268 // Make sure the result is of the correct type. 1269 return llvm::ConstantExpr::getBitCast(Entry, Ty); 1270 } 1271 1272 // This is the first use or definition of a mangled name. If there is a 1273 // deferred decl with this name, remember that we need to emit it at the end 1274 // of the file. 1275 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1276 if (DDI != DeferredDecls.end()) { 1277 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1278 // list, and remove it from DeferredDecls (since we don't need it anymore). 1279 DeferredDeclsToEmit.push_back(DDI->second); 1280 DeferredDecls.erase(DDI); 1281 } 1282 1283 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 1284 llvm::GlobalVariable *GV = 1285 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 1286 llvm::GlobalValue::ExternalLinkage, 1287 0, MangledName, 0, 1288 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 1289 1290 // Handle things which are present even on external declarations. 1291 if (D) { 1292 // FIXME: This code is overly simple and should be merged with other global 1293 // handling. 1294 GV->setConstant(isTypeConstant(D->getType(), false)); 1295 1296 // Set linkage and visibility in case we never see a definition. 1297 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility(); 1298 if (LV.linkage() != ExternalLinkage) { 1299 // Don't set internal linkage on declarations. 1300 } else { 1301 if (D->hasAttr<DLLImportAttr>()) 1302 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage); 1303 else if (D->hasAttr<WeakAttr>() || D->isWeakImported()) 1304 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 1305 1306 // Set visibility on a declaration only if it's explicit. 1307 if (LV.visibilityExplicit()) 1308 GV->setVisibility(GetLLVMVisibility(LV.visibility())); 1309 } 1310 1311 if (D->isThreadSpecified()) 1312 setTLSMode(GV, *D); 1313 } 1314 1315 if (AddrSpace != Ty->getAddressSpace()) 1316 return llvm::ConstantExpr::getBitCast(GV, Ty); 1317 else 1318 return GV; 1319} 1320 1321 1322llvm::GlobalVariable * 1323CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 1324 llvm::Type *Ty, 1325 llvm::GlobalValue::LinkageTypes Linkage) { 1326 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 1327 llvm::GlobalVariable *OldGV = 0; 1328 1329 1330 if (GV) { 1331 // Check if the variable has the right type. 1332 if (GV->getType()->getElementType() == Ty) 1333 return GV; 1334 1335 // Because C++ name mangling, the only way we can end up with an already 1336 // existing global with the same name is if it has been declared extern "C". 1337 assert(GV->isDeclaration() && "Declaration has wrong type!"); 1338 OldGV = GV; 1339 } 1340 1341 // Create a new variable. 1342 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 1343 Linkage, 0, Name); 1344 1345 if (OldGV) { 1346 // Replace occurrences of the old variable if needed. 1347 GV->takeName(OldGV); 1348 1349 if (!OldGV->use_empty()) { 1350 llvm::Constant *NewPtrForOldDecl = 1351 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 1352 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 1353 } 1354 1355 OldGV->eraseFromParent(); 1356 } 1357 1358 return GV; 1359} 1360 1361/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1362/// given global variable. If Ty is non-null and if the global doesn't exist, 1363/// then it will be created with the specified type instead of whatever the 1364/// normal requested type would be. 1365llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 1366 llvm::Type *Ty) { 1367 assert(D->hasGlobalStorage() && "Not a global variable"); 1368 QualType ASTTy = D->getType(); 1369 if (Ty == 0) 1370 Ty = getTypes().ConvertTypeForMem(ASTTy); 1371 1372 llvm::PointerType *PTy = 1373 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 1374 1375 StringRef MangledName = getMangledName(D); 1376 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1377} 1378 1379/// CreateRuntimeVariable - Create a new runtime global variable with the 1380/// specified type and name. 1381llvm::Constant * 1382CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 1383 StringRef Name) { 1384 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0, 1385 true); 1386} 1387 1388void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1389 assert(!D->getInit() && "Cannot emit definite definitions here!"); 1390 1391 if (MayDeferGeneration(D)) { 1392 // If we have not seen a reference to this variable yet, place it 1393 // into the deferred declarations table to be emitted if needed 1394 // later. 1395 StringRef MangledName = getMangledName(D); 1396 if (!GetGlobalValue(MangledName)) { 1397 DeferredDecls[MangledName] = D; 1398 return; 1399 } 1400 } 1401 1402 // The tentative definition is the only definition. 1403 EmitGlobalVarDefinition(D); 1404} 1405 1406void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) { 1407 if (DefinitionRequired) 1408 getCXXABI().EmitVTables(Class); 1409} 1410 1411llvm::GlobalVariable::LinkageTypes 1412CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) { 1413 if (RD->getLinkage() != ExternalLinkage) 1414 return llvm::GlobalVariable::InternalLinkage; 1415 1416 if (const CXXMethodDecl *KeyFunction 1417 = RD->getASTContext().getKeyFunction(RD)) { 1418 // If this class has a key function, use that to determine the linkage of 1419 // the vtable. 1420 const FunctionDecl *Def = 0; 1421 if (KeyFunction->hasBody(Def)) 1422 KeyFunction = cast<CXXMethodDecl>(Def); 1423 1424 switch (KeyFunction->getTemplateSpecializationKind()) { 1425 case TSK_Undeclared: 1426 case TSK_ExplicitSpecialization: 1427 // When compiling with optimizations turned on, we emit all vtables, 1428 // even if the key function is not defined in the current translation 1429 // unit. If this is the case, use available_externally linkage. 1430 if (!Def && CodeGenOpts.OptimizationLevel) 1431 return llvm::GlobalVariable::AvailableExternallyLinkage; 1432 1433 if (KeyFunction->isInlined()) 1434 return !Context.getLangOpts().AppleKext ? 1435 llvm::GlobalVariable::LinkOnceODRLinkage : 1436 llvm::Function::InternalLinkage; 1437 1438 return llvm::GlobalVariable::ExternalLinkage; 1439 1440 case TSK_ImplicitInstantiation: 1441 return !Context.getLangOpts().AppleKext ? 1442 llvm::GlobalVariable::LinkOnceODRLinkage : 1443 llvm::Function::InternalLinkage; 1444 1445 case TSK_ExplicitInstantiationDefinition: 1446 return !Context.getLangOpts().AppleKext ? 1447 llvm::GlobalVariable::WeakODRLinkage : 1448 llvm::Function::InternalLinkage; 1449 1450 case TSK_ExplicitInstantiationDeclaration: 1451 // FIXME: Use available_externally linkage. However, this currently 1452 // breaks LLVM's build due to undefined symbols. 1453 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1454 return !Context.getLangOpts().AppleKext ? 1455 llvm::GlobalVariable::LinkOnceODRLinkage : 1456 llvm::Function::InternalLinkage; 1457 } 1458 } 1459 1460 if (Context.getLangOpts().AppleKext) 1461 return llvm::Function::InternalLinkage; 1462 1463 switch (RD->getTemplateSpecializationKind()) { 1464 case TSK_Undeclared: 1465 case TSK_ExplicitSpecialization: 1466 case TSK_ImplicitInstantiation: 1467 // FIXME: Use available_externally linkage. However, this currently 1468 // breaks LLVM's build due to undefined symbols. 1469 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1470 case TSK_ExplicitInstantiationDeclaration: 1471 return llvm::GlobalVariable::LinkOnceODRLinkage; 1472 1473 case TSK_ExplicitInstantiationDefinition: 1474 return llvm::GlobalVariable::WeakODRLinkage; 1475 } 1476 1477 llvm_unreachable("Invalid TemplateSpecializationKind!"); 1478} 1479 1480CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 1481 return Context.toCharUnitsFromBits( 1482 TheDataLayout.getTypeStoreSizeInBits(Ty)); 1483} 1484 1485llvm::Constant * 1486CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D, 1487 const Expr *rawInit) { 1488 ArrayRef<ExprWithCleanups::CleanupObject> cleanups; 1489 if (const ExprWithCleanups *withCleanups = 1490 dyn_cast<ExprWithCleanups>(rawInit)) { 1491 cleanups = withCleanups->getObjects(); 1492 rawInit = withCleanups->getSubExpr(); 1493 } 1494 1495 const InitListExpr *init = dyn_cast<InitListExpr>(rawInit); 1496 if (!init || !init->initializesStdInitializerList() || 1497 init->getNumInits() == 0) 1498 return 0; 1499 1500 ASTContext &ctx = getContext(); 1501 unsigned numInits = init->getNumInits(); 1502 // FIXME: This check is here because we would otherwise silently miscompile 1503 // nested global std::initializer_lists. Better would be to have a real 1504 // implementation. 1505 for (unsigned i = 0; i < numInits; ++i) { 1506 const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i)); 1507 if (inner && inner->initializesStdInitializerList()) { 1508 ErrorUnsupported(inner, "nested global std::initializer_list"); 1509 return 0; 1510 } 1511 } 1512 1513 // Synthesize a fake VarDecl for the array and initialize that. 1514 QualType elementType = init->getInit(0)->getType(); 1515 llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits); 1516 QualType arrayType = ctx.getConstantArrayType(elementType, numElements, 1517 ArrayType::Normal, 0); 1518 1519 IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist"); 1520 TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo( 1521 arrayType, D->getLocation()); 1522 VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>( 1523 D->getDeclContext()), 1524 D->getLocStart(), D->getLocation(), 1525 name, arrayType, sourceInfo, 1526 SC_Static, SC_Static); 1527 1528 // Now clone the InitListExpr to initialize the array instead. 1529 // Incredible hack: we want to use the existing InitListExpr here, so we need 1530 // to tell it that it no longer initializes a std::initializer_list. 1531 ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(), 1532 init->getNumInits()); 1533 Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits, 1534 init->getRBraceLoc()); 1535 arrayInit->setType(arrayType); 1536 1537 if (!cleanups.empty()) 1538 arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups); 1539 1540 backingArray->setInit(arrayInit); 1541 1542 // Emit the definition of the array. 1543 EmitGlobalVarDefinition(backingArray); 1544 1545 // Inspect the initializer list to validate it and determine its type. 1546 // FIXME: doing this every time is probably inefficient; caching would be nice 1547 RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl(); 1548 RecordDecl::field_iterator field = record->field_begin(); 1549 if (field == record->field_end()) { 1550 ErrorUnsupported(D, "weird std::initializer_list"); 1551 return 0; 1552 } 1553 QualType elementPtr = ctx.getPointerType(elementType.withConst()); 1554 // Start pointer. 1555 if (!ctx.hasSameType(field->getType(), elementPtr)) { 1556 ErrorUnsupported(D, "weird std::initializer_list"); 1557 return 0; 1558 } 1559 ++field; 1560 if (field == record->field_end()) { 1561 ErrorUnsupported(D, "weird std::initializer_list"); 1562 return 0; 1563 } 1564 bool isStartEnd = false; 1565 if (ctx.hasSameType(field->getType(), elementPtr)) { 1566 // End pointer. 1567 isStartEnd = true; 1568 } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) { 1569 ErrorUnsupported(D, "weird std::initializer_list"); 1570 return 0; 1571 } 1572 1573 // Now build an APValue representing the std::initializer_list. 1574 APValue initListValue(APValue::UninitStruct(), 0, 2); 1575 APValue &startField = initListValue.getStructField(0); 1576 APValue::LValuePathEntry startOffsetPathEntry; 1577 startOffsetPathEntry.ArrayIndex = 0; 1578 startField = APValue(APValue::LValueBase(backingArray), 1579 CharUnits::fromQuantity(0), 1580 llvm::makeArrayRef(startOffsetPathEntry), 1581 /*IsOnePastTheEnd=*/false, 0); 1582 1583 if (isStartEnd) { 1584 APValue &endField = initListValue.getStructField(1); 1585 APValue::LValuePathEntry endOffsetPathEntry; 1586 endOffsetPathEntry.ArrayIndex = numInits; 1587 endField = APValue(APValue::LValueBase(backingArray), 1588 ctx.getTypeSizeInChars(elementType) * numInits, 1589 llvm::makeArrayRef(endOffsetPathEntry), 1590 /*IsOnePastTheEnd=*/true, 0); 1591 } else { 1592 APValue &sizeField = initListValue.getStructField(1); 1593 sizeField = APValue(llvm::APSInt(numElements)); 1594 } 1595 1596 // Emit the constant for the initializer_list. 1597 llvm::Constant *llvmInit = 1598 EmitConstantValueForMemory(initListValue, D->getType()); 1599 assert(llvmInit && "failed to initialize as constant"); 1600 return llvmInit; 1601} 1602 1603unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 1604 unsigned AddrSpace) { 1605 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) { 1606 if (D->hasAttr<CUDAConstantAttr>()) 1607 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 1608 else if (D->hasAttr<CUDASharedAttr>()) 1609 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 1610 else 1611 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 1612 } 1613 1614 return AddrSpace; 1615} 1616 1617void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1618 llvm::Constant *Init = 0; 1619 QualType ASTTy = D->getType(); 1620 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1621 bool NeedsGlobalCtor = false; 1622 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 1623 1624 const VarDecl *InitDecl; 1625 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 1626 1627 if (!InitExpr) { 1628 // This is a tentative definition; tentative definitions are 1629 // implicitly initialized with { 0 }. 1630 // 1631 // Note that tentative definitions are only emitted at the end of 1632 // a translation unit, so they should never have incomplete 1633 // type. In addition, EmitTentativeDefinition makes sure that we 1634 // never attempt to emit a tentative definition if a real one 1635 // exists. A use may still exists, however, so we still may need 1636 // to do a RAUW. 1637 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1638 Init = EmitNullConstant(D->getType()); 1639 } else { 1640 // If this is a std::initializer_list, emit the special initializer. 1641 Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr); 1642 // An empty init list will perform zero-initialization, which happens 1643 // to be exactly what we want. 1644 // FIXME: It does so in a global constructor, which is *not* what we 1645 // want. 1646 1647 if (!Init) { 1648 initializedGlobalDecl = GlobalDecl(D); 1649 Init = EmitConstantInit(*InitDecl); 1650 } 1651 if (!Init) { 1652 QualType T = InitExpr->getType(); 1653 if (D->getType()->isReferenceType()) 1654 T = D->getType(); 1655 1656 if (getLangOpts().CPlusPlus) { 1657 Init = EmitNullConstant(T); 1658 NeedsGlobalCtor = true; 1659 } else { 1660 ErrorUnsupported(D, "static initializer"); 1661 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1662 } 1663 } else { 1664 // We don't need an initializer, so remove the entry for the delayed 1665 // initializer position (just in case this entry was delayed) if we 1666 // also don't need to register a destructor. 1667 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 1668 DelayedCXXInitPosition.erase(D); 1669 } 1670 } 1671 1672 llvm::Type* InitType = Init->getType(); 1673 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1674 1675 // Strip off a bitcast if we got one back. 1676 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1677 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1678 // all zero index gep. 1679 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1680 Entry = CE->getOperand(0); 1681 } 1682 1683 // Entry is now either a Function or GlobalVariable. 1684 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1685 1686 // We have a definition after a declaration with the wrong type. 1687 // We must make a new GlobalVariable* and update everything that used OldGV 1688 // (a declaration or tentative definition) with the new GlobalVariable* 1689 // (which will be a definition). 1690 // 1691 // This happens if there is a prototype for a global (e.g. 1692 // "extern int x[];") and then a definition of a different type (e.g. 1693 // "int x[10];"). This also happens when an initializer has a different type 1694 // from the type of the global (this happens with unions). 1695 if (GV == 0 || 1696 GV->getType()->getElementType() != InitType || 1697 GV->getType()->getAddressSpace() != 1698 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 1699 1700 // Move the old entry aside so that we'll create a new one. 1701 Entry->setName(StringRef()); 1702 1703 // Make a new global with the correct type, this is now guaranteed to work. 1704 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1705 1706 // Replace all uses of the old global with the new global 1707 llvm::Constant *NewPtrForOldDecl = 1708 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1709 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1710 1711 // Erase the old global, since it is no longer used. 1712 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1713 } 1714 1715 if (D->hasAttr<AnnotateAttr>()) 1716 AddGlobalAnnotations(D, GV); 1717 1718 GV->setInitializer(Init); 1719 1720 // If it is safe to mark the global 'constant', do so now. 1721 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 1722 isTypeConstant(D->getType(), true)); 1723 1724 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1725 1726 // Set the llvm linkage type as appropriate. 1727 llvm::GlobalValue::LinkageTypes Linkage = 1728 GetLLVMLinkageVarDefinition(D, GV); 1729 GV->setLinkage(Linkage); 1730 if (Linkage == llvm::GlobalVariable::CommonLinkage) 1731 // common vars aren't constant even if declared const. 1732 GV->setConstant(false); 1733 1734 SetCommonAttributes(D, GV); 1735 1736 // Emit the initializer function if necessary. 1737 if (NeedsGlobalCtor || NeedsGlobalDtor) 1738 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 1739 1740 // If we are compiling with ASan, add metadata indicating dynamically 1741 // initialized globals. 1742 if (LangOpts.SanitizeAddress && NeedsGlobalCtor) { 1743 llvm::Module &M = getModule(); 1744 1745 llvm::NamedMDNode *DynamicInitializers = 1746 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals"); 1747 llvm::Value *GlobalToAdd[] = { GV }; 1748 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd); 1749 DynamicInitializers->addOperand(ThisGlobal); 1750 } 1751 1752 // Emit global variable debug information. 1753 if (CGDebugInfo *DI = getModuleDebugInfo()) 1754 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 1755 DI->EmitGlobalVariable(GV, D); 1756} 1757 1758llvm::GlobalValue::LinkageTypes 1759CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, 1760 llvm::GlobalVariable *GV) { 1761 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 1762 if (Linkage == GVA_Internal) 1763 return llvm::Function::InternalLinkage; 1764 else if (D->hasAttr<DLLImportAttr>()) 1765 return llvm::Function::DLLImportLinkage; 1766 else if (D->hasAttr<DLLExportAttr>()) 1767 return llvm::Function::DLLExportLinkage; 1768 else if (D->hasAttr<WeakAttr>()) { 1769 if (GV->isConstant()) 1770 return llvm::GlobalVariable::WeakODRLinkage; 1771 else 1772 return llvm::GlobalVariable::WeakAnyLinkage; 1773 } else if (Linkage == GVA_TemplateInstantiation || 1774 Linkage == GVA_ExplicitTemplateInstantiation) 1775 return llvm::GlobalVariable::WeakODRLinkage; 1776 else if (!getLangOpts().CPlusPlus && 1777 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) || 1778 D->getAttr<CommonAttr>()) && 1779 !D->hasExternalStorage() && !D->getInit() && 1780 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() && 1781 !D->getAttr<WeakImportAttr>()) { 1782 // Thread local vars aren't considered common linkage. 1783 return llvm::GlobalVariable::CommonLinkage; 1784 } 1785 return llvm::GlobalVariable::ExternalLinkage; 1786} 1787 1788/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1789/// implement a function with no prototype, e.g. "int foo() {}". If there are 1790/// existing call uses of the old function in the module, this adjusts them to 1791/// call the new function directly. 1792/// 1793/// This is not just a cleanup: the always_inline pass requires direct calls to 1794/// functions to be able to inline them. If there is a bitcast in the way, it 1795/// won't inline them. Instcombine normally deletes these calls, but it isn't 1796/// run at -O0. 1797static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1798 llvm::Function *NewFn) { 1799 // If we're redefining a global as a function, don't transform it. 1800 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1801 if (OldFn == 0) return; 1802 1803 llvm::Type *NewRetTy = NewFn->getReturnType(); 1804 SmallVector<llvm::Value*, 4> ArgList; 1805 1806 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1807 UI != E; ) { 1808 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1809 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased. 1810 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I); 1811 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I) 1812 llvm::CallSite CS(CI); 1813 if (!CI || !CS.isCallee(I)) continue; 1814 1815 // If the return types don't match exactly, and if the call isn't dead, then 1816 // we can't transform this call. 1817 if (CI->getType() != NewRetTy && !CI->use_empty()) 1818 continue; 1819 1820 // Get the attribute list. 1821 llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec; 1822 llvm::AttrListPtr AttrList = CI->getAttributes(); 1823 1824 // Get any return attributes. 1825 llvm::Attributes RAttrs = AttrList.getRetAttributes(); 1826 1827 // Add the return attributes. 1828 if (RAttrs.hasAttributes()) 1829 AttrVec.push_back(llvm:: 1830 AttributeWithIndex::get(llvm::AttrListPtr::ReturnIndex, 1831 RAttrs)); 1832 1833 // If the function was passed too few arguments, don't transform. If extra 1834 // arguments were passed, we silently drop them. If any of the types 1835 // mismatch, we don't transform. 1836 unsigned ArgNo = 0; 1837 bool DontTransform = false; 1838 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1839 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1840 if (CS.arg_size() == ArgNo || 1841 CS.getArgument(ArgNo)->getType() != AI->getType()) { 1842 DontTransform = true; 1843 break; 1844 } 1845 1846 // Add any parameter attributes. 1847 llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1); 1848 if (PAttrs.hasAttributes()) 1849 AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs)); 1850 } 1851 if (DontTransform) 1852 continue; 1853 1854 llvm::Attributes FnAttrs = AttrList.getFnAttributes(); 1855 if (FnAttrs.hasAttributes()) 1856 AttrVec.push_back(llvm:: 1857 AttributeWithIndex::get(llvm::AttrListPtr::FunctionIndex, 1858 FnAttrs)); 1859 1860 // Okay, we can transform this. Create the new call instruction and copy 1861 // over the required information. 1862 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo); 1863 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI); 1864 ArgList.clear(); 1865 if (!NewCall->getType()->isVoidTy()) 1866 NewCall->takeName(CI); 1867 NewCall->setAttributes(llvm::AttrListPtr::get(OldFn->getContext(), AttrVec)); 1868 NewCall->setCallingConv(CI->getCallingConv()); 1869 1870 // Finally, remove the old call, replacing any uses with the new one. 1871 if (!CI->use_empty()) 1872 CI->replaceAllUsesWith(NewCall); 1873 1874 // Copy debug location attached to CI. 1875 if (!CI->getDebugLoc().isUnknown()) 1876 NewCall->setDebugLoc(CI->getDebugLoc()); 1877 CI->eraseFromParent(); 1878 } 1879} 1880 1881void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 1882 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 1883 // If we have a definition, this might be a deferred decl. If the 1884 // instantiation is explicit, make sure we emit it at the end. 1885 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 1886 GetAddrOfGlobalVar(VD); 1887} 1888 1889void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1890 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1891 1892 // Compute the function info and LLVM type. 1893 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 1894 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 1895 1896 // Get or create the prototype for the function. 1897 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1898 1899 // Strip off a bitcast if we got one back. 1900 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1901 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1902 Entry = CE->getOperand(0); 1903 } 1904 1905 1906 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1907 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1908 1909 // If the types mismatch then we have to rewrite the definition. 1910 assert(OldFn->isDeclaration() && 1911 "Shouldn't replace non-declaration"); 1912 1913 // F is the Function* for the one with the wrong type, we must make a new 1914 // Function* and update everything that used F (a declaration) with the new 1915 // Function* (which will be a definition). 1916 // 1917 // This happens if there is a prototype for a function 1918 // (e.g. "int f()") and then a definition of a different type 1919 // (e.g. "int f(int x)"). Move the old function aside so that it 1920 // doesn't interfere with GetAddrOfFunction. 1921 OldFn->setName(StringRef()); 1922 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1923 1924 // If this is an implementation of a function without a prototype, try to 1925 // replace any existing uses of the function (which may be calls) with uses 1926 // of the new function 1927 if (D->getType()->isFunctionNoProtoType()) { 1928 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1929 OldFn->removeDeadConstantUsers(); 1930 } 1931 1932 // Replace uses of F with the Function we will endow with a body. 1933 if (!Entry->use_empty()) { 1934 llvm::Constant *NewPtrForOldDecl = 1935 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1936 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1937 } 1938 1939 // Ok, delete the old function now, which is dead. 1940 OldFn->eraseFromParent(); 1941 1942 Entry = NewFn; 1943 } 1944 1945 // We need to set linkage and visibility on the function before 1946 // generating code for it because various parts of IR generation 1947 // want to propagate this information down (e.g. to local static 1948 // declarations). 1949 llvm::Function *Fn = cast<llvm::Function>(Entry); 1950 setFunctionLinkage(D, Fn); 1951 1952 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes 1953 setGlobalVisibility(Fn, D); 1954 1955 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 1956 1957 SetFunctionDefinitionAttributes(D, Fn); 1958 SetLLVMFunctionAttributesForDefinition(D, Fn); 1959 1960 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1961 AddGlobalCtor(Fn, CA->getPriority()); 1962 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1963 AddGlobalDtor(Fn, DA->getPriority()); 1964 if (D->hasAttr<AnnotateAttr>()) 1965 AddGlobalAnnotations(D, Fn); 1966} 1967 1968void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 1969 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1970 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1971 assert(AA && "Not an alias?"); 1972 1973 StringRef MangledName = getMangledName(GD); 1974 1975 // If there is a definition in the module, then it wins over the alias. 1976 // This is dubious, but allow it to be safe. Just ignore the alias. 1977 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1978 if (Entry && !Entry->isDeclaration()) 1979 return; 1980 1981 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1982 1983 // Create a reference to the named value. This ensures that it is emitted 1984 // if a deferred decl. 1985 llvm::Constant *Aliasee; 1986 if (isa<llvm::FunctionType>(DeclTy)) 1987 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 1988 /*ForVTable=*/false); 1989 else 1990 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1991 llvm::PointerType::getUnqual(DeclTy), 0); 1992 1993 // Create the new alias itself, but don't set a name yet. 1994 llvm::GlobalValue *GA = 1995 new llvm::GlobalAlias(Aliasee->getType(), 1996 llvm::Function::ExternalLinkage, 1997 "", Aliasee, &getModule()); 1998 1999 if (Entry) { 2000 assert(Entry->isDeclaration()); 2001 2002 // If there is a declaration in the module, then we had an extern followed 2003 // by the alias, as in: 2004 // extern int test6(); 2005 // ... 2006 // int test6() __attribute__((alias("test7"))); 2007 // 2008 // Remove it and replace uses of it with the alias. 2009 GA->takeName(Entry); 2010 2011 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2012 Entry->getType())); 2013 Entry->eraseFromParent(); 2014 } else { 2015 GA->setName(MangledName); 2016 } 2017 2018 // Set attributes which are particular to an alias; this is a 2019 // specialization of the attributes which may be set on a global 2020 // variable/function. 2021 if (D->hasAttr<DLLExportAttr>()) { 2022 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2023 // The dllexport attribute is ignored for undefined symbols. 2024 if (FD->hasBody()) 2025 GA->setLinkage(llvm::Function::DLLExportLinkage); 2026 } else { 2027 GA->setLinkage(llvm::Function::DLLExportLinkage); 2028 } 2029 } else if (D->hasAttr<WeakAttr>() || 2030 D->hasAttr<WeakRefAttr>() || 2031 D->isWeakImported()) { 2032 GA->setLinkage(llvm::Function::WeakAnyLinkage); 2033 } 2034 2035 SetCommonAttributes(D, GA); 2036} 2037 2038llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 2039 ArrayRef<llvm::Type*> Tys) { 2040 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 2041 Tys); 2042} 2043 2044static llvm::StringMapEntry<llvm::Constant*> & 2045GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2046 const StringLiteral *Literal, 2047 bool TargetIsLSB, 2048 bool &IsUTF16, 2049 unsigned &StringLength) { 2050 StringRef String = Literal->getString(); 2051 unsigned NumBytes = String.size(); 2052 2053 // Check for simple case. 2054 if (!Literal->containsNonAsciiOrNull()) { 2055 StringLength = NumBytes; 2056 return Map.GetOrCreateValue(String); 2057 } 2058 2059 // Otherwise, convert the UTF8 literals into a string of shorts. 2060 IsUTF16 = true; 2061 2062 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 2063 const UTF8 *FromPtr = (const UTF8 *)String.data(); 2064 UTF16 *ToPtr = &ToBuf[0]; 2065 2066 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2067 &ToPtr, ToPtr + NumBytes, 2068 strictConversion); 2069 2070 // ConvertUTF8toUTF16 returns the length in ToPtr. 2071 StringLength = ToPtr - &ToBuf[0]; 2072 2073 // Add an explicit null. 2074 *ToPtr = 0; 2075 return Map. 2076 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()), 2077 (StringLength + 1) * 2)); 2078} 2079 2080static llvm::StringMapEntry<llvm::Constant*> & 2081GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2082 const StringLiteral *Literal, 2083 unsigned &StringLength) { 2084 StringRef String = Literal->getString(); 2085 StringLength = String.size(); 2086 return Map.GetOrCreateValue(String); 2087} 2088 2089llvm::Constant * 2090CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2091 unsigned StringLength = 0; 2092 bool isUTF16 = false; 2093 llvm::StringMapEntry<llvm::Constant*> &Entry = 2094 GetConstantCFStringEntry(CFConstantStringMap, Literal, 2095 getDataLayout().isLittleEndian(), 2096 isUTF16, StringLength); 2097 2098 if (llvm::Constant *C = Entry.getValue()) 2099 return C; 2100 2101 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2102 llvm::Constant *Zeros[] = { Zero, Zero }; 2103 2104 // If we don't already have it, get __CFConstantStringClassReference. 2105 if (!CFConstantStringClassRef) { 2106 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2107 Ty = llvm::ArrayType::get(Ty, 0); 2108 llvm::Constant *GV = CreateRuntimeVariable(Ty, 2109 "__CFConstantStringClassReference"); 2110 // Decay array -> ptr 2111 CFConstantStringClassRef = 2112 llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2113 } 2114 2115 QualType CFTy = getContext().getCFConstantStringType(); 2116 2117 llvm::StructType *STy = 2118 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2119 2120 llvm::Constant *Fields[4]; 2121 2122 // Class pointer. 2123 Fields[0] = CFConstantStringClassRef; 2124 2125 // Flags. 2126 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2127 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2128 llvm::ConstantInt::get(Ty, 0x07C8); 2129 2130 // String pointer. 2131 llvm::Constant *C = 0; 2132 if (isUTF16) { 2133 ArrayRef<uint16_t> Arr = 2134 llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(), 2135 Entry.getKey().size() / 2); 2136 C = llvm::ConstantDataArray::get(VMContext, Arr); 2137 } else { 2138 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2139 } 2140 2141 llvm::GlobalValue::LinkageTypes Linkage; 2142 if (isUTF16) 2143 // FIXME: why do utf strings get "_" labels instead of "L" labels? 2144 Linkage = llvm::GlobalValue::InternalLinkage; 2145 else 2146 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error 2147 // when using private linkage. It is not clear if this is a bug in ld 2148 // or a reasonable new restriction. 2149 Linkage = llvm::GlobalValue::LinkerPrivateLinkage; 2150 2151 // Note: -fwritable-strings doesn't make the backing store strings of 2152 // CFStrings writable. (See <rdar://problem/10657500>) 2153 llvm::GlobalVariable *GV = 2154 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 2155 Linkage, C, ".str"); 2156 GV->setUnnamedAddr(true); 2157 if (isUTF16) { 2158 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2159 GV->setAlignment(Align.getQuantity()); 2160 } else { 2161 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2162 GV->setAlignment(Align.getQuantity()); 2163 } 2164 2165 // String. 2166 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2167 2168 if (isUTF16) 2169 // Cast the UTF16 string to the correct type. 2170 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2171 2172 // String length. 2173 Ty = getTypes().ConvertType(getContext().LongTy); 2174 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2175 2176 // The struct. 2177 C = llvm::ConstantStruct::get(STy, Fields); 2178 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2179 llvm::GlobalVariable::PrivateLinkage, C, 2180 "_unnamed_cfstring_"); 2181 if (const char *Sect = getContext().getTargetInfo().getCFStringSection()) 2182 GV->setSection(Sect); 2183 Entry.setValue(GV); 2184 2185 return GV; 2186} 2187 2188static RecordDecl * 2189CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 2190 DeclContext *DC, IdentifierInfo *Id) { 2191 SourceLocation Loc; 2192 if (Ctx.getLangOpts().CPlusPlus) 2193 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 2194 else 2195 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 2196} 2197 2198llvm::Constant * 2199CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2200 unsigned StringLength = 0; 2201 llvm::StringMapEntry<llvm::Constant*> &Entry = 2202 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2203 2204 if (llvm::Constant *C = Entry.getValue()) 2205 return C; 2206 2207 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2208 llvm::Constant *Zeros[] = { Zero, Zero }; 2209 2210 // If we don't already have it, get _NSConstantStringClassReference. 2211 if (!ConstantStringClassRef) { 2212 std::string StringClass(getLangOpts().ObjCConstantStringClass); 2213 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2214 llvm::Constant *GV; 2215 if (LangOpts.ObjCRuntime.isNonFragile()) { 2216 std::string str = 2217 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2218 : "OBJC_CLASS_$_" + StringClass; 2219 GV = getObjCRuntime().GetClassGlobal(str); 2220 // Make sure the result is of the correct type. 2221 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2222 ConstantStringClassRef = 2223 llvm::ConstantExpr::getBitCast(GV, PTy); 2224 } else { 2225 std::string str = 2226 StringClass.empty() ? "_NSConstantStringClassReference" 2227 : "_" + StringClass + "ClassReference"; 2228 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 2229 GV = CreateRuntimeVariable(PTy, str); 2230 // Decay array -> ptr 2231 ConstantStringClassRef = 2232 llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2233 } 2234 } 2235 2236 if (!NSConstantStringType) { 2237 // Construct the type for a constant NSString. 2238 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 2239 Context.getTranslationUnitDecl(), 2240 &Context.Idents.get("__builtin_NSString")); 2241 D->startDefinition(); 2242 2243 QualType FieldTypes[3]; 2244 2245 // const int *isa; 2246 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 2247 // const char *str; 2248 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 2249 // unsigned int length; 2250 FieldTypes[2] = Context.UnsignedIntTy; 2251 2252 // Create fields 2253 for (unsigned i = 0; i < 3; ++i) { 2254 FieldDecl *Field = FieldDecl::Create(Context, D, 2255 SourceLocation(), 2256 SourceLocation(), 0, 2257 FieldTypes[i], /*TInfo=*/0, 2258 /*BitWidth=*/0, 2259 /*Mutable=*/false, 2260 ICIS_NoInit); 2261 Field->setAccess(AS_public); 2262 D->addDecl(Field); 2263 } 2264 2265 D->completeDefinition(); 2266 QualType NSTy = Context.getTagDeclType(D); 2267 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 2268 } 2269 2270 llvm::Constant *Fields[3]; 2271 2272 // Class pointer. 2273 Fields[0] = ConstantStringClassRef; 2274 2275 // String pointer. 2276 llvm::Constant *C = 2277 llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2278 2279 llvm::GlobalValue::LinkageTypes Linkage; 2280 bool isConstant; 2281 Linkage = llvm::GlobalValue::PrivateLinkage; 2282 isConstant = !LangOpts.WritableStrings; 2283 2284 llvm::GlobalVariable *GV = 2285 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 2286 ".str"); 2287 GV->setUnnamedAddr(true); 2288 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2289 GV->setAlignment(Align.getQuantity()); 2290 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2291 2292 // String length. 2293 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2294 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 2295 2296 // The struct. 2297 C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 2298 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2299 llvm::GlobalVariable::PrivateLinkage, C, 2300 "_unnamed_nsstring_"); 2301 // FIXME. Fix section. 2302 if (const char *Sect = 2303 LangOpts.ObjCRuntime.isNonFragile() 2304 ? getContext().getTargetInfo().getNSStringNonFragileABISection() 2305 : getContext().getTargetInfo().getNSStringSection()) 2306 GV->setSection(Sect); 2307 Entry.setValue(GV); 2308 2309 return GV; 2310} 2311 2312QualType CodeGenModule::getObjCFastEnumerationStateType() { 2313 if (ObjCFastEnumerationStateType.isNull()) { 2314 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 2315 Context.getTranslationUnitDecl(), 2316 &Context.Idents.get("__objcFastEnumerationState")); 2317 D->startDefinition(); 2318 2319 QualType FieldTypes[] = { 2320 Context.UnsignedLongTy, 2321 Context.getPointerType(Context.getObjCIdType()), 2322 Context.getPointerType(Context.UnsignedLongTy), 2323 Context.getConstantArrayType(Context.UnsignedLongTy, 2324 llvm::APInt(32, 5), ArrayType::Normal, 0) 2325 }; 2326 2327 for (size_t i = 0; i < 4; ++i) { 2328 FieldDecl *Field = FieldDecl::Create(Context, 2329 D, 2330 SourceLocation(), 2331 SourceLocation(), 0, 2332 FieldTypes[i], /*TInfo=*/0, 2333 /*BitWidth=*/0, 2334 /*Mutable=*/false, 2335 ICIS_NoInit); 2336 Field->setAccess(AS_public); 2337 D->addDecl(Field); 2338 } 2339 2340 D->completeDefinition(); 2341 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 2342 } 2343 2344 return ObjCFastEnumerationStateType; 2345} 2346 2347llvm::Constant * 2348CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 2349 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 2350 2351 // Don't emit it as the address of the string, emit the string data itself 2352 // as an inline array. 2353 if (E->getCharByteWidth() == 1) { 2354 SmallString<64> Str(E->getString()); 2355 2356 // Resize the string to the right size, which is indicated by its type. 2357 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 2358 Str.resize(CAT->getSize().getZExtValue()); 2359 return llvm::ConstantDataArray::getString(VMContext, Str, false); 2360 } 2361 2362 llvm::ArrayType *AType = 2363 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 2364 llvm::Type *ElemTy = AType->getElementType(); 2365 unsigned NumElements = AType->getNumElements(); 2366 2367 // Wide strings have either 2-byte or 4-byte elements. 2368 if (ElemTy->getPrimitiveSizeInBits() == 16) { 2369 SmallVector<uint16_t, 32> Elements; 2370 Elements.reserve(NumElements); 2371 2372 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2373 Elements.push_back(E->getCodeUnit(i)); 2374 Elements.resize(NumElements); 2375 return llvm::ConstantDataArray::get(VMContext, Elements); 2376 } 2377 2378 assert(ElemTy->getPrimitiveSizeInBits() == 32); 2379 SmallVector<uint32_t, 32> Elements; 2380 Elements.reserve(NumElements); 2381 2382 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2383 Elements.push_back(E->getCodeUnit(i)); 2384 Elements.resize(NumElements); 2385 return llvm::ConstantDataArray::get(VMContext, Elements); 2386} 2387 2388/// GetAddrOfConstantStringFromLiteral - Return a pointer to a 2389/// constant array for the given string literal. 2390llvm::Constant * 2391CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 2392 CharUnits Align = getContext().getTypeAlignInChars(S->getType()); 2393 if (S->isAscii() || S->isUTF8()) { 2394 SmallString<64> Str(S->getString()); 2395 2396 // Resize the string to the right size, which is indicated by its type. 2397 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType()); 2398 Str.resize(CAT->getSize().getZExtValue()); 2399 return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity()); 2400 } 2401 2402 // FIXME: the following does not memoize wide strings. 2403 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 2404 llvm::GlobalVariable *GV = 2405 new llvm::GlobalVariable(getModule(),C->getType(), 2406 !LangOpts.WritableStrings, 2407 llvm::GlobalValue::PrivateLinkage, 2408 C,".str"); 2409 2410 GV->setAlignment(Align.getQuantity()); 2411 GV->setUnnamedAddr(true); 2412 return GV; 2413} 2414 2415/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 2416/// array for the given ObjCEncodeExpr node. 2417llvm::Constant * 2418CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 2419 std::string Str; 2420 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 2421 2422 return GetAddrOfConstantCString(Str); 2423} 2424 2425 2426/// GenerateWritableString -- Creates storage for a string literal. 2427static llvm::GlobalVariable *GenerateStringLiteral(StringRef str, 2428 bool constant, 2429 CodeGenModule &CGM, 2430 const char *GlobalName, 2431 unsigned Alignment) { 2432 // Create Constant for this string literal. Don't add a '\0'. 2433 llvm::Constant *C = 2434 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false); 2435 2436 // Create a global variable for this string 2437 llvm::GlobalVariable *GV = 2438 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 2439 llvm::GlobalValue::PrivateLinkage, 2440 C, GlobalName); 2441 GV->setAlignment(Alignment); 2442 GV->setUnnamedAddr(true); 2443 return GV; 2444} 2445 2446/// GetAddrOfConstantString - Returns a pointer to a character array 2447/// containing the literal. This contents are exactly that of the 2448/// given string, i.e. it will not be null terminated automatically; 2449/// see GetAddrOfConstantCString. Note that whether the result is 2450/// actually a pointer to an LLVM constant depends on 2451/// Feature.WriteableStrings. 2452/// 2453/// The result has pointer to array type. 2454llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str, 2455 const char *GlobalName, 2456 unsigned Alignment) { 2457 // Get the default prefix if a name wasn't specified. 2458 if (!GlobalName) 2459 GlobalName = ".str"; 2460 2461 // Don't share any string literals if strings aren't constant. 2462 if (LangOpts.WritableStrings) 2463 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment); 2464 2465 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2466 ConstantStringMap.GetOrCreateValue(Str); 2467 2468 if (llvm::GlobalVariable *GV = Entry.getValue()) { 2469 if (Alignment > GV->getAlignment()) { 2470 GV->setAlignment(Alignment); 2471 } 2472 return GV; 2473 } 2474 2475 // Create a global variable for this. 2476 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, 2477 Alignment); 2478 Entry.setValue(GV); 2479 return GV; 2480} 2481 2482/// GetAddrOfConstantCString - Returns a pointer to a character 2483/// array containing the literal and a terminating '\0' 2484/// character. The result has pointer to array type. 2485llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str, 2486 const char *GlobalName, 2487 unsigned Alignment) { 2488 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 2489 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment); 2490} 2491 2492/// EmitObjCPropertyImplementations - Emit information for synthesized 2493/// properties for an implementation. 2494void CodeGenModule::EmitObjCPropertyImplementations(const 2495 ObjCImplementationDecl *D) { 2496 for (ObjCImplementationDecl::propimpl_iterator 2497 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 2498 ObjCPropertyImplDecl *PID = *i; 2499 2500 // Dynamic is just for type-checking. 2501 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 2502 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2503 2504 // Determine which methods need to be implemented, some may have 2505 // been overridden. Note that ::isPropertyAccessor is not the method 2506 // we want, that just indicates if the decl came from a 2507 // property. What we want to know is if the method is defined in 2508 // this implementation. 2509 if (!D->getInstanceMethod(PD->getGetterName())) 2510 CodeGenFunction(*this).GenerateObjCGetter( 2511 const_cast<ObjCImplementationDecl *>(D), PID); 2512 if (!PD->isReadOnly() && 2513 !D->getInstanceMethod(PD->getSetterName())) 2514 CodeGenFunction(*this).GenerateObjCSetter( 2515 const_cast<ObjCImplementationDecl *>(D), PID); 2516 } 2517 } 2518} 2519 2520static bool needsDestructMethod(ObjCImplementationDecl *impl) { 2521 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 2522 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 2523 ivar; ivar = ivar->getNextIvar()) 2524 if (ivar->getType().isDestructedType()) 2525 return true; 2526 2527 return false; 2528} 2529 2530/// EmitObjCIvarInitializations - Emit information for ivar initialization 2531/// for an implementation. 2532void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 2533 // We might need a .cxx_destruct even if we don't have any ivar initializers. 2534 if (needsDestructMethod(D)) { 2535 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 2536 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2537 ObjCMethodDecl *DTORMethod = 2538 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 2539 cxxSelector, getContext().VoidTy, 0, D, 2540 /*isInstance=*/true, /*isVariadic=*/false, 2541 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 2542 /*isDefined=*/false, ObjCMethodDecl::Required); 2543 D->addInstanceMethod(DTORMethod); 2544 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 2545 D->setHasDestructors(true); 2546 } 2547 2548 // If the implementation doesn't have any ivar initializers, we don't need 2549 // a .cxx_construct. 2550 if (D->getNumIvarInitializers() == 0) 2551 return; 2552 2553 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 2554 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2555 // The constructor returns 'self'. 2556 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 2557 D->getLocation(), 2558 D->getLocation(), 2559 cxxSelector, 2560 getContext().getObjCIdType(), 0, 2561 D, /*isInstance=*/true, 2562 /*isVariadic=*/false, 2563 /*isPropertyAccessor=*/true, 2564 /*isImplicitlyDeclared=*/true, 2565 /*isDefined=*/false, 2566 ObjCMethodDecl::Required); 2567 D->addInstanceMethod(CTORMethod); 2568 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 2569 D->setHasNonZeroConstructors(true); 2570} 2571 2572/// EmitNamespace - Emit all declarations in a namespace. 2573void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 2574 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 2575 I != E; ++I) 2576 EmitTopLevelDecl(*I); 2577} 2578 2579// EmitLinkageSpec - Emit all declarations in a linkage spec. 2580void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 2581 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 2582 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 2583 ErrorUnsupported(LSD, "linkage spec"); 2584 return; 2585 } 2586 2587 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 2588 I != E; ++I) { 2589 // Meta-data for ObjC class includes references to implemented methods. 2590 // Generate class's method definitions first. 2591 if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) { 2592 for (ObjCContainerDecl::method_iterator M = OID->meth_begin(), 2593 MEnd = OID->meth_end(); 2594 M != MEnd; ++M) 2595 EmitTopLevelDecl(*M); 2596 } 2597 EmitTopLevelDecl(*I); 2598 } 2599} 2600 2601/// EmitTopLevelDecl - Emit code for a single top level declaration. 2602void CodeGenModule::EmitTopLevelDecl(Decl *D) { 2603 // If an error has occurred, stop code generation, but continue 2604 // parsing and semantic analysis (to ensure all warnings and errors 2605 // are emitted). 2606 if (Diags.hasErrorOccurred()) 2607 return; 2608 2609 // Ignore dependent declarations. 2610 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 2611 return; 2612 2613 switch (D->getKind()) { 2614 case Decl::CXXConversion: 2615 case Decl::CXXMethod: 2616 case Decl::Function: 2617 // Skip function templates 2618 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2619 cast<FunctionDecl>(D)->isLateTemplateParsed()) 2620 return; 2621 2622 EmitGlobal(cast<FunctionDecl>(D)); 2623 break; 2624 2625 case Decl::Var: 2626 EmitGlobal(cast<VarDecl>(D)); 2627 break; 2628 2629 // Indirect fields from global anonymous structs and unions can be 2630 // ignored; only the actual variable requires IR gen support. 2631 case Decl::IndirectField: 2632 break; 2633 2634 // C++ Decls 2635 case Decl::Namespace: 2636 EmitNamespace(cast<NamespaceDecl>(D)); 2637 break; 2638 // No code generation needed. 2639 case Decl::UsingShadow: 2640 case Decl::Using: 2641 case Decl::UsingDirective: 2642 case Decl::ClassTemplate: 2643 case Decl::FunctionTemplate: 2644 case Decl::TypeAliasTemplate: 2645 case Decl::NamespaceAlias: 2646 case Decl::Block: 2647 case Decl::Import: 2648 break; 2649 case Decl::CXXConstructor: 2650 // Skip function templates 2651 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 2652 cast<FunctionDecl>(D)->isLateTemplateParsed()) 2653 return; 2654 2655 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 2656 break; 2657 case Decl::CXXDestructor: 2658 if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 2659 return; 2660 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 2661 break; 2662 2663 case Decl::StaticAssert: 2664 // Nothing to do. 2665 break; 2666 2667 // Objective-C Decls 2668 2669 // Forward declarations, no (immediate) code generation. 2670 case Decl::ObjCInterface: 2671 case Decl::ObjCCategory: 2672 break; 2673 2674 case Decl::ObjCProtocol: { 2675 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D); 2676 if (Proto->isThisDeclarationADefinition()) 2677 ObjCRuntime->GenerateProtocol(Proto); 2678 break; 2679 } 2680 2681 case Decl::ObjCCategoryImpl: 2682 // Categories have properties but don't support synthesize so we 2683 // can ignore them here. 2684 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 2685 break; 2686 2687 case Decl::ObjCImplementation: { 2688 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 2689 EmitObjCPropertyImplementations(OMD); 2690 EmitObjCIvarInitializations(OMD); 2691 ObjCRuntime->GenerateClass(OMD); 2692 // Emit global variable debug information. 2693 if (CGDebugInfo *DI = getModuleDebugInfo()) 2694 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(OMD->getClassInterface()), 2695 OMD->getLocation()); 2696 2697 break; 2698 } 2699 case Decl::ObjCMethod: { 2700 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 2701 // If this is not a prototype, emit the body. 2702 if (OMD->getBody()) 2703 CodeGenFunction(*this).GenerateObjCMethod(OMD); 2704 break; 2705 } 2706 case Decl::ObjCCompatibleAlias: 2707 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 2708 break; 2709 2710 case Decl::LinkageSpec: 2711 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 2712 break; 2713 2714 case Decl::FileScopeAsm: { 2715 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 2716 StringRef AsmString = AD->getAsmString()->getString(); 2717 2718 const std::string &S = getModule().getModuleInlineAsm(); 2719 if (S.empty()) 2720 getModule().setModuleInlineAsm(AsmString); 2721 else if (S.end()[-1] == '\n') 2722 getModule().setModuleInlineAsm(S + AsmString.str()); 2723 else 2724 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 2725 break; 2726 } 2727 2728 default: 2729 // Make sure we handled everything we should, every other kind is a 2730 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 2731 // function. Need to recode Decl::Kind to do that easily. 2732 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 2733 } 2734} 2735 2736/// Turns the given pointer into a constant. 2737static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 2738 const void *Ptr) { 2739 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 2740 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 2741 return llvm::ConstantInt::get(i64, PtrInt); 2742} 2743 2744static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 2745 llvm::NamedMDNode *&GlobalMetadata, 2746 GlobalDecl D, 2747 llvm::GlobalValue *Addr) { 2748 if (!GlobalMetadata) 2749 GlobalMetadata = 2750 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 2751 2752 // TODO: should we report variant information for ctors/dtors? 2753 llvm::Value *Ops[] = { 2754 Addr, 2755 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 2756 }; 2757 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 2758} 2759 2760/// Emits metadata nodes associating all the global values in the 2761/// current module with the Decls they came from. This is useful for 2762/// projects using IR gen as a subroutine. 2763/// 2764/// Since there's currently no way to associate an MDNode directly 2765/// with an llvm::GlobalValue, we create a global named metadata 2766/// with the name 'clang.global.decl.ptrs'. 2767void CodeGenModule::EmitDeclMetadata() { 2768 llvm::NamedMDNode *GlobalMetadata = 0; 2769 2770 // StaticLocalDeclMap 2771 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator 2772 I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 2773 I != E; ++I) { 2774 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 2775 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 2776 } 2777} 2778 2779/// Emits metadata nodes for all the local variables in the current 2780/// function. 2781void CodeGenFunction::EmitDeclMetadata() { 2782 if (LocalDeclMap.empty()) return; 2783 2784 llvm::LLVMContext &Context = getLLVMContext(); 2785 2786 // Find the unique metadata ID for this name. 2787 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 2788 2789 llvm::NamedMDNode *GlobalMetadata = 0; 2790 2791 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 2792 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 2793 const Decl *D = I->first; 2794 llvm::Value *Addr = I->second; 2795 2796 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 2797 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 2798 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr)); 2799 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 2800 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 2801 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 2802 } 2803 } 2804} 2805 2806void CodeGenModule::EmitCoverageFile() { 2807 if (!getCodeGenOpts().CoverageFile.empty()) { 2808 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 2809 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 2810 llvm::LLVMContext &Ctx = TheModule.getContext(); 2811 llvm::MDString *CoverageFile = 2812 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 2813 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 2814 llvm::MDNode *CU = CUNode->getOperand(i); 2815 llvm::Value *node[] = { CoverageFile, CU }; 2816 llvm::MDNode *N = llvm::MDNode::get(Ctx, node); 2817 GCov->addOperand(N); 2818 } 2819 } 2820 } 2821} 2822 2823llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid, 2824 QualType GuidType) { 2825 // Sema has checked that all uuid strings are of the form 2826 // "12345678-1234-1234-1234-1234567890ab". 2827 assert(Uuid.size() == 36); 2828 const char *Uuidstr = Uuid.data(); 2829 for (int i = 0; i < 36; ++i) { 2830 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-'); 2831 else assert(isxdigit(Uuidstr[i])); 2832 } 2833 2834 llvm::APInt Field0(32, StringRef(Uuidstr , 8), 16); 2835 llvm::APInt Field1(16, StringRef(Uuidstr + 9, 4), 16); 2836 llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16); 2837 static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 2838 2839 APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4); 2840 InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0)); 2841 InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1)); 2842 InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2)); 2843 APValue& Arr = InitStruct.getStructField(3); 2844 Arr = APValue(APValue::UninitArray(), 8, 8); 2845 for (int t = 0; t < 8; ++t) 2846 Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt( 2847 llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16))); 2848 2849 return EmitConstantValue(InitStruct, GuidType); 2850} 2851