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