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