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 "CGCUDARuntime.h" 16 #include "CGCXXABI.h" 17 #include "CGCall.h" 18 #include "CGDebugInfo.h" 19 #include "CGObjCRuntime.h" 20 #include "CGOpenCLRuntime.h" 21 #include "CGOpenMPRuntime.h" 22 #include "CodeGenFunction.h" 23 #include "CodeGenPGO.h" 24 #include "CodeGenTBAA.h" 25 #include "TargetInfo.h" 26 #include "clang/AST/ASTContext.h" 27 #include "clang/AST/CharUnits.h" 28 #include "clang/AST/DeclCXX.h" 29 #include "clang/AST/DeclObjC.h" 30 #include "clang/AST/DeclTemplate.h" 31 #include "clang/AST/Mangle.h" 32 #include "clang/AST/RecordLayout.h" 33 #include "clang/AST/RecursiveASTVisitor.h" 34 #include "clang/Basic/Builtins.h" 35 #include "clang/Basic/CharInfo.h" 36 #include "clang/Basic/Diagnostic.h" 37 #include "clang/Basic/Module.h" 38 #include "clang/Basic/SourceManager.h" 39 #include "clang/Basic/TargetInfo.h" 40 #include "clang/Basic/Version.h" 41 #include "clang/Frontend/CodeGenOptions.h" 42 #include "clang/Sema/SemaDiagnostic.h" 43 #include "llvm/ADT/APSInt.h" 44 #include "llvm/ADT/Triple.h" 45 #include "llvm/IR/CallSite.h" 46 #include "llvm/IR/CallingConv.h" 47 #include "llvm/IR/DataLayout.h" 48 #include "llvm/IR/Intrinsics.h" 49 #include "llvm/IR/LLVMContext.h" 50 #include "llvm/IR/Module.h" 51 #include "llvm/ProfileData/InstrProfReader.h" 52 #include "llvm/Support/ConvertUTF.h" 53 #include "llvm/Support/ErrorHandling.h" 54 55 using namespace clang; 56 using namespace CodeGen; 57 58 static const char AnnotationSection[] = "llvm.metadata"; 59 60 static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 61 switch (CGM.getTarget().getCXXABI().getKind()) { 62 case TargetCXXABI::GenericAArch64: 63 case TargetCXXABI::GenericARM: 64 case TargetCXXABI::iOS: 65 case TargetCXXABI::iOS64: 66 case TargetCXXABI::GenericItanium: 67 return CreateItaniumCXXABI(CGM); 68 case TargetCXXABI::Microsoft: 69 return CreateMicrosoftCXXABI(CGM); 70 } 71 72 llvm_unreachable("invalid C++ ABI kind"); 73 } 74 75 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 76 llvm::Module &M, const llvm::DataLayout &TD, 77 DiagnosticsEngine &diags) 78 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M), 79 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()), 80 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0), 81 TheTargetCodeGenInfo(0), Types(*this), VTables(*this), ObjCRuntime(0), 82 OpenCLRuntime(0), OpenMPRuntime(nullptr), CUDARuntime(0), DebugInfo(0), 83 ARCData(0), NoObjCARCExceptionsMetadata(0), RRData(0), PGOReader(nullptr), 84 CFConstantStringClassRef(0), 85 ConstantStringClassRef(0), NSConstantStringType(0), 86 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), BlockObjectAssign(0), 87 BlockObjectDispose(0), BlockDescriptorType(0), GenericBlockLiteralType(0), 88 LifetimeStartFn(0), LifetimeEndFn(0), 89 SanitizerBlacklist( 90 llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)), 91 SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled 92 : LangOpts.Sanitize) { 93 94 // Initialize the type cache. 95 llvm::LLVMContext &LLVMContext = M.getContext(); 96 VoidTy = llvm::Type::getVoidTy(LLVMContext); 97 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 98 Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 99 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 100 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 101 FloatTy = llvm::Type::getFloatTy(LLVMContext); 102 DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 103 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 104 PointerAlignInBytes = 105 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 106 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 107 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 108 Int8PtrTy = Int8Ty->getPointerTo(0); 109 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 110 111 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 112 113 if (LangOpts.ObjC1) 114 createObjCRuntime(); 115 if (LangOpts.OpenCL) 116 createOpenCLRuntime(); 117 if (LangOpts.OpenMP) 118 createOpenMPRuntime(); 119 if (LangOpts.CUDA) 120 createCUDARuntime(); 121 122 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 123 if (SanOpts.Thread || 124 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 125 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 126 getCXXABI().getMangleContext()); 127 128 // If debug info or coverage generation is enabled, create the CGDebugInfo 129 // object. 130 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo || 131 CodeGenOpts.EmitGcovArcs || 132 CodeGenOpts.EmitGcovNotes) 133 DebugInfo = new CGDebugInfo(*this); 134 135 Block.GlobalUniqueCount = 0; 136 137 if (C.getLangOpts().ObjCAutoRefCount) 138 ARCData = new ARCEntrypoints(); 139 RRData = new RREntrypoints(); 140 141 if (!CodeGenOpts.InstrProfileInput.empty()) { 142 if (llvm::error_code EC = llvm::IndexedInstrProfReader::create( 143 CodeGenOpts.InstrProfileInput, PGOReader)) { 144 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 145 "Could not read profile: %0"); 146 getDiags().Report(DiagID) << EC.message(); 147 } 148 } 149 } 150 151 CodeGenModule::~CodeGenModule() { 152 delete ObjCRuntime; 153 delete OpenCLRuntime; 154 delete OpenMPRuntime; 155 delete CUDARuntime; 156 delete TheTargetCodeGenInfo; 157 delete TBAA; 158 delete DebugInfo; 159 delete ARCData; 160 delete RRData; 161 } 162 163 void CodeGenModule::createObjCRuntime() { 164 // This is just isGNUFamily(), but we want to force implementors of 165 // new ABIs to decide how best to do this. 166 switch (LangOpts.ObjCRuntime.getKind()) { 167 case ObjCRuntime::GNUstep: 168 case ObjCRuntime::GCC: 169 case ObjCRuntime::ObjFW: 170 ObjCRuntime = CreateGNUObjCRuntime(*this); 171 return; 172 173 case ObjCRuntime::FragileMacOSX: 174 case ObjCRuntime::MacOSX: 175 case ObjCRuntime::iOS: 176 ObjCRuntime = CreateMacObjCRuntime(*this); 177 return; 178 } 179 llvm_unreachable("bad runtime kind"); 180 } 181 182 void CodeGenModule::createOpenCLRuntime() { 183 OpenCLRuntime = new CGOpenCLRuntime(*this); 184 } 185 186 void CodeGenModule::createOpenMPRuntime() { 187 OpenMPRuntime = new CGOpenMPRuntime(*this); 188 } 189 190 void CodeGenModule::createCUDARuntime() { 191 CUDARuntime = CreateNVCUDARuntime(*this); 192 } 193 194 void CodeGenModule::applyReplacements() { 195 for (ReplacementsTy::iterator I = Replacements.begin(), 196 E = Replacements.end(); 197 I != E; ++I) { 198 StringRef MangledName = I->first(); 199 llvm::Constant *Replacement = I->second; 200 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 201 if (!Entry) 202 continue; 203 auto *OldF = cast<llvm::Function>(Entry); 204 auto *NewF = dyn_cast<llvm::Function>(Replacement); 205 if (!NewF) { 206 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 207 NewF = dyn_cast<llvm::Function>(Alias->getAliasedGlobal()); 208 } else { 209 auto *CE = cast<llvm::ConstantExpr>(Replacement); 210 assert(CE->getOpcode() == llvm::Instruction::BitCast || 211 CE->getOpcode() == llvm::Instruction::GetElementPtr); 212 NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 213 } 214 } 215 216 // Replace old with new, but keep the old order. 217 OldF->replaceAllUsesWith(Replacement); 218 if (NewF) { 219 NewF->removeFromParent(); 220 OldF->getParent()->getFunctionList().insertAfter(OldF, NewF); 221 } 222 OldF->eraseFromParent(); 223 } 224 } 225 226 void CodeGenModule::checkAliases() { 227 // Check if the constructed aliases are well formed. It is really unfortunate 228 // that we have to do this in CodeGen, but we only construct mangled names 229 // and aliases during codegen. 230 bool Error = false; 231 DiagnosticsEngine &Diags = getDiags(); 232 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(), 233 E = Aliases.end(); I != E; ++I) { 234 const GlobalDecl &GD = *I; 235 const auto *D = cast<ValueDecl>(GD.getDecl()); 236 const AliasAttr *AA = D->getAttr<AliasAttr>(); 237 StringRef MangledName = getMangledName(GD); 238 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 239 auto *Alias = cast<llvm::GlobalAlias>(Entry); 240 llvm::GlobalValue *GV = Alias->getAliasedGlobal(); 241 if (!GV) { 242 Error = true; 243 Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 244 } else if (GV->isDeclaration()) { 245 Error = true; 246 Diags.Report(AA->getLocation(), diag::err_alias_to_undefined); 247 } 248 249 llvm::Constant *Aliasee = Alias->getAliasee(); 250 llvm::GlobalValue *AliaseeGV; 251 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) { 252 assert((CE->getOpcode() == llvm::Instruction::BitCast || 253 CE->getOpcode() == llvm::Instruction::AddrSpaceCast) && 254 "Unsupported aliasee"); 255 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 256 } else { 257 AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 258 } 259 260 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 261 StringRef AliasSection = SA->getName(); 262 if (AliasSection != AliaseeGV->getSection()) 263 Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 264 << AliasSection; 265 } 266 267 // We have to handle alias to weak aliases in here. LLVM itself disallows 268 // this since the object semantics would not match the IL one. For 269 // compatibility with gcc we implement it by just pointing the alias 270 // to its aliasee's aliasee. We also warn, since the user is probably 271 // expecting the link to be weak. 272 if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 273 if (GA->mayBeOverridden()) { 274 Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias) 275 << GA->getAliasedGlobal()->getName() << GA->getName(); 276 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 277 GA->getAliasee(), Alias->getType()); 278 Alias->setAliasee(Aliasee); 279 } 280 } 281 } 282 if (!Error) 283 return; 284 285 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(), 286 E = Aliases.end(); I != E; ++I) { 287 const GlobalDecl &GD = *I; 288 StringRef MangledName = getMangledName(GD); 289 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 290 auto *Alias = cast<llvm::GlobalAlias>(Entry); 291 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 292 Alias->eraseFromParent(); 293 } 294 } 295 296 void CodeGenModule::clear() { 297 DeferredDeclsToEmit.clear(); 298 } 299 300 void CodeGenModule::Release() { 301 EmitDeferred(); 302 applyReplacements(); 303 checkAliases(); 304 EmitCXXGlobalInitFunc(); 305 EmitCXXGlobalDtorFunc(); 306 EmitCXXThreadLocalInitFunc(); 307 if (ObjCRuntime) 308 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 309 AddGlobalCtor(ObjCInitFunction); 310 if (getCodeGenOpts().ProfileInstrGenerate) 311 if (llvm::Function *PGOInit = CodeGenPGO::emitInitialization(*this)) 312 AddGlobalCtor(PGOInit, 0); 313 if (PGOReader && PGOStats.isOutOfDate()) 314 getDiags().Report(diag::warn_profile_data_out_of_date) 315 << PGOStats.Visited << PGOStats.Missing << PGOStats.Mismatched; 316 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 317 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 318 EmitGlobalAnnotations(); 319 EmitStaticExternCAliases(); 320 emitLLVMUsed(); 321 322 if (CodeGenOpts.Autolink && 323 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 324 EmitModuleLinkOptions(); 325 } 326 if (CodeGenOpts.DwarfVersion) 327 // We actually want the latest version when there are conflicts. 328 // We can change from Warning to Latest if such mode is supported. 329 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 330 CodeGenOpts.DwarfVersion); 331 if (DebugInfo) 332 // We support a single version in the linked module: error out when 333 // modules do not have the same version. We are going to implement dropping 334 // debug info when the version number is not up-to-date. Once that is 335 // done, the bitcode linker is not going to see modules with different 336 // version numbers. 337 getModule().addModuleFlag(llvm::Module::Error, "Debug Info Version", 338 llvm::DEBUG_METADATA_VERSION); 339 340 SimplifyPersonality(); 341 342 if (getCodeGenOpts().EmitDeclMetadata) 343 EmitDeclMetadata(); 344 345 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 346 EmitCoverageFile(); 347 348 if (DebugInfo) 349 DebugInfo->finalize(); 350 351 EmitVersionIdentMetadata(); 352 } 353 354 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 355 // Make sure that this type is translated. 356 Types.UpdateCompletedType(TD); 357 } 358 359 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 360 if (!TBAA) 361 return 0; 362 return TBAA->getTBAAInfo(QTy); 363 } 364 365 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 366 if (!TBAA) 367 return 0; 368 return TBAA->getTBAAInfoForVTablePtr(); 369 } 370 371 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 372 if (!TBAA) 373 return 0; 374 return TBAA->getTBAAStructInfo(QTy); 375 } 376 377 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) { 378 if (!TBAA) 379 return 0; 380 return TBAA->getTBAAStructTypeInfo(QTy); 381 } 382 383 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 384 llvm::MDNode *AccessN, 385 uint64_t O) { 386 if (!TBAA) 387 return 0; 388 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 389 } 390 391 /// Decorate the instruction with a TBAA tag. For both scalar TBAA 392 /// and struct-path aware TBAA, the tag has the same format: 393 /// base type, access type and offset. 394 /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 395 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 396 llvm::MDNode *TBAAInfo, 397 bool ConvertTypeToTag) { 398 if (ConvertTypeToTag && TBAA) 399 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 400 TBAA->getTBAAScalarTagInfo(TBAAInfo)); 401 else 402 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 403 } 404 405 void CodeGenModule::Error(SourceLocation loc, StringRef message) { 406 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 407 getDiags().Report(Context.getFullLoc(loc), diagID) << message; 408 } 409 410 /// ErrorUnsupported - Print out an error that codegen doesn't support the 411 /// specified stmt yet. 412 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 413 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 414 "cannot compile this %0 yet"); 415 std::string Msg = Type; 416 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 417 << Msg << S->getSourceRange(); 418 } 419 420 /// ErrorUnsupported - Print out an error that codegen doesn't support the 421 /// specified decl yet. 422 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 423 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 424 "cannot compile this %0 yet"); 425 std::string Msg = Type; 426 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 427 } 428 429 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 430 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 431 } 432 433 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 434 const NamedDecl *D) const { 435 // Internal definitions always have default visibility. 436 if (GV->hasLocalLinkage()) { 437 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 438 return; 439 } 440 441 // Set visibility for definitions. 442 LinkageInfo LV = D->getLinkageAndVisibility(); 443 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 444 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 445 } 446 447 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 448 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 449 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 450 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 451 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 452 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 453 } 454 455 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 456 CodeGenOptions::TLSModel M) { 457 switch (M) { 458 case CodeGenOptions::GeneralDynamicTLSModel: 459 return llvm::GlobalVariable::GeneralDynamicTLSModel; 460 case CodeGenOptions::LocalDynamicTLSModel: 461 return llvm::GlobalVariable::LocalDynamicTLSModel; 462 case CodeGenOptions::InitialExecTLSModel: 463 return llvm::GlobalVariable::InitialExecTLSModel; 464 case CodeGenOptions::LocalExecTLSModel: 465 return llvm::GlobalVariable::LocalExecTLSModel; 466 } 467 llvm_unreachable("Invalid TLS model!"); 468 } 469 470 void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV, 471 const VarDecl &D) const { 472 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 473 474 llvm::GlobalVariable::ThreadLocalMode TLM; 475 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 476 477 // Override the TLS model if it is explicitly specified. 478 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 479 TLM = GetLLVMTLSModel(Attr->getModel()); 480 } 481 482 GV->setThreadLocalMode(TLM); 483 } 484 485 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 486 const auto *ND = cast<NamedDecl>(GD.getDecl()); 487 488 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 489 if (!Str.empty()) 490 return Str; 491 492 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 493 IdentifierInfo *II = ND->getIdentifier(); 494 assert(II && "Attempt to mangle unnamed decl."); 495 496 Str = II->getName(); 497 return Str; 498 } 499 500 SmallString<256> Buffer; 501 llvm::raw_svector_ostream Out(Buffer); 502 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 503 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 504 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 505 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 506 else 507 getCXXABI().getMangleContext().mangleName(ND, Out); 508 509 // Allocate space for the mangled name. 510 Out.flush(); 511 size_t Length = Buffer.size(); 512 char *Name = MangledNamesAllocator.Allocate<char>(Length); 513 std::copy(Buffer.begin(), Buffer.end(), Name); 514 515 Str = StringRef(Name, Length); 516 517 return Str; 518 } 519 520 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 521 const BlockDecl *BD) { 522 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 523 const Decl *D = GD.getDecl(); 524 llvm::raw_svector_ostream Out(Buffer.getBuffer()); 525 if (D == 0) 526 MangleCtx.mangleGlobalBlock(BD, 527 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 528 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 529 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 530 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 531 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 532 else 533 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 534 } 535 536 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 537 return getModule().getNamedValue(Name); 538 } 539 540 /// AddGlobalCtor - Add a function to the list that will be called before 541 /// main() runs. 542 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 543 // FIXME: Type coercion of void()* types. 544 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 545 } 546 547 /// AddGlobalDtor - Add a function to the list that will be called 548 /// when the module is unloaded. 549 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 550 // FIXME: Type coercion of void()* types. 551 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 552 } 553 554 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 555 // Ctor function type is void()*. 556 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 557 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 558 559 // Get the type of a ctor entry, { i32, void ()* }. 560 llvm::StructType *CtorStructTy = 561 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL); 562 563 // Construct the constructor and destructor arrays. 564 SmallVector<llvm::Constant*, 8> Ctors; 565 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 566 llvm::Constant *S[] = { 567 llvm::ConstantInt::get(Int32Ty, I->second, false), 568 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy) 569 }; 570 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 571 } 572 573 if (!Ctors.empty()) { 574 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 575 new llvm::GlobalVariable(TheModule, AT, false, 576 llvm::GlobalValue::AppendingLinkage, 577 llvm::ConstantArray::get(AT, Ctors), 578 GlobalName); 579 } 580 } 581 582 llvm::GlobalValue::LinkageTypes 583 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 584 const auto *D = cast<FunctionDecl>(GD.getDecl()); 585 586 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 587 588 bool UseThunkForDtorVariant = 589 isa<CXXDestructorDecl>(D) && 590 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 591 GD.getDtorType()); 592 593 return getLLVMLinkageforDeclarator(D, Linkage, /*isConstantVariable=*/false, 594 UseThunkForDtorVariant); 595 } 596 597 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 598 llvm::Function *F) { 599 setNonAliasAttributes(D, F); 600 } 601 602 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 603 const CGFunctionInfo &Info, 604 llvm::Function *F) { 605 unsigned CallingConv; 606 AttributeListType AttributeList; 607 ConstructAttributeList(Info, D, AttributeList, CallingConv, false); 608 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList)); 609 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 610 } 611 612 /// Determines whether the language options require us to model 613 /// unwind exceptions. We treat -fexceptions as mandating this 614 /// except under the fragile ObjC ABI with only ObjC exceptions 615 /// enabled. This means, for example, that C with -fexceptions 616 /// enables this. 617 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 618 // If exceptions are completely disabled, obviously this is false. 619 if (!LangOpts.Exceptions) return false; 620 621 // If C++ exceptions are enabled, this is true. 622 if (LangOpts.CXXExceptions) return true; 623 624 // If ObjC exceptions are enabled, this depends on the ABI. 625 if (LangOpts.ObjCExceptions) { 626 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 627 } 628 629 return true; 630 } 631 632 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 633 llvm::Function *F) { 634 llvm::AttrBuilder B; 635 636 if (CodeGenOpts.UnwindTables) 637 B.addAttribute(llvm::Attribute::UWTable); 638 639 if (!hasUnwindExceptions(LangOpts)) 640 B.addAttribute(llvm::Attribute::NoUnwind); 641 642 if (D->hasAttr<NakedAttr>()) { 643 // Naked implies noinline: we should not be inlining such functions. 644 B.addAttribute(llvm::Attribute::Naked); 645 B.addAttribute(llvm::Attribute::NoInline); 646 } else if (D->hasAttr<OptimizeNoneAttr>()) { 647 // OptimizeNone implies noinline; we should not be inlining such functions. 648 B.addAttribute(llvm::Attribute::OptimizeNone); 649 B.addAttribute(llvm::Attribute::NoInline); 650 } else if (D->hasAttr<NoDuplicateAttr>()) { 651 B.addAttribute(llvm::Attribute::NoDuplicate); 652 } else if (D->hasAttr<NoInlineAttr>()) { 653 B.addAttribute(llvm::Attribute::NoInline); 654 } else if (D->hasAttr<AlwaysInlineAttr>() && 655 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex, 656 llvm::Attribute::NoInline)) { 657 // (noinline wins over always_inline, and we can't specify both in IR) 658 B.addAttribute(llvm::Attribute::AlwaysInline); 659 } 660 661 if (D->hasAttr<ColdAttr>()) { 662 B.addAttribute(llvm::Attribute::OptimizeForSize); 663 B.addAttribute(llvm::Attribute::Cold); 664 } 665 666 if (D->hasAttr<MinSizeAttr>()) 667 B.addAttribute(llvm::Attribute::MinSize); 668 669 if (D->hasAttr<OptimizeNoneAttr>()) { 670 // OptimizeNone wins over OptimizeForSize and MinSize. 671 B.removeAttribute(llvm::Attribute::OptimizeForSize); 672 B.removeAttribute(llvm::Attribute::MinSize); 673 } 674 675 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 676 B.addAttribute(llvm::Attribute::StackProtect); 677 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 678 B.addAttribute(llvm::Attribute::StackProtectStrong); 679 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 680 B.addAttribute(llvm::Attribute::StackProtectReq); 681 682 // Add sanitizer attributes if function is not blacklisted. 683 if (!SanitizerBlacklist->isIn(*F)) { 684 // When AddressSanitizer is enabled, set SanitizeAddress attribute 685 // unless __attribute__((no_sanitize_address)) is used. 686 if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>()) 687 B.addAttribute(llvm::Attribute::SanitizeAddress); 688 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread)) 689 if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) { 690 B.addAttribute(llvm::Attribute::SanitizeThread); 691 } 692 // Same for MemorySanitizer and __attribute__((no_sanitize_memory)) 693 if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>()) 694 B.addAttribute(llvm::Attribute::SanitizeMemory); 695 } 696 697 F->addAttributes(llvm::AttributeSet::FunctionIndex, 698 llvm::AttributeSet::get( 699 F->getContext(), llvm::AttributeSet::FunctionIndex, B)); 700 701 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 702 F->setUnnamedAddr(true); 703 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) 704 if (MD->isVirtual()) 705 F->setUnnamedAddr(true); 706 707 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 708 if (alignment) 709 F->setAlignment(alignment); 710 711 // C++ ABI requires 2-byte alignment for member functions. 712 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 713 F->setAlignment(2); 714 } 715 716 void CodeGenModule::SetCommonAttributes(const Decl *D, 717 llvm::GlobalValue *GV) { 718 if (const auto *ND = dyn_cast<NamedDecl>(D)) 719 setGlobalVisibility(GV, ND); 720 else 721 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 722 723 if (D->hasAttr<UsedAttr>()) 724 addUsedGlobal(GV); 725 } 726 727 void CodeGenModule::setNonAliasAttributes(const Decl *D, 728 llvm::GlobalObject *GO) { 729 SetCommonAttributes(D, GO); 730 731 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 732 GO->setSection(SA->getName()); 733 734 getTargetCodeGenInfo().SetTargetAttributes(D, GO, *this); 735 } 736 737 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 738 llvm::Function *F, 739 const CGFunctionInfo &FI) { 740 SetLLVMFunctionAttributes(D, FI, F); 741 SetLLVMFunctionAttributesForDefinition(D, F); 742 743 F->setLinkage(llvm::Function::InternalLinkage); 744 745 setNonAliasAttributes(D, F); 746 } 747 748 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 749 const NamedDecl *ND) { 750 // Set linkage and visibility in case we never see a definition. 751 LinkageInfo LV = ND->getLinkageAndVisibility(); 752 if (LV.getLinkage() != ExternalLinkage) { 753 // Don't set internal linkage on declarations. 754 } else { 755 if (ND->hasAttr<DLLImportAttr>()) { 756 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 757 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 758 } else if (ND->hasAttr<DLLExportAttr>()) { 759 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 760 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 761 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 762 // "extern_weak" is overloaded in LLVM; we probably should have 763 // separate linkage types for this. 764 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 765 } 766 767 // Set visibility on a declaration only if it's explicit. 768 if (LV.isVisibilityExplicit()) 769 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 770 } 771 } 772 773 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 774 llvm::Function *F, 775 bool IsIncompleteFunction) { 776 if (unsigned IID = F->getIntrinsicID()) { 777 // If this is an intrinsic function, set the function's attributes 778 // to the intrinsic's attributes. 779 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), 780 (llvm::Intrinsic::ID)IID)); 781 return; 782 } 783 784 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 785 786 if (!IsIncompleteFunction) 787 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 788 789 // Add the Returned attribute for "this", except for iOS 5 and earlier 790 // where substantial code, including the libstdc++ dylib, was compiled with 791 // GCC and does not actually return "this". 792 if (getCXXABI().HasThisReturn(GD) && 793 !(getTarget().getTriple().isiOS() && 794 getTarget().getTriple().isOSVersionLT(6))) { 795 assert(!F->arg_empty() && 796 F->arg_begin()->getType() 797 ->canLosslesslyBitCastTo(F->getReturnType()) && 798 "unexpected this return"); 799 F->addAttribute(1, llvm::Attribute::Returned); 800 } 801 802 // Only a few attributes are set on declarations; these may later be 803 // overridden by a definition. 804 805 setLinkageAndVisibilityForGV(F, FD); 806 807 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 808 F->setSection(SA->getName()); 809 810 // A replaceable global allocation function does not act like a builtin by 811 // default, only if it is invoked by a new-expression or delete-expression. 812 if (FD->isReplaceableGlobalAllocationFunction()) 813 F->addAttribute(llvm::AttributeSet::FunctionIndex, 814 llvm::Attribute::NoBuiltin); 815 } 816 817 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 818 assert(!GV->isDeclaration() && 819 "Only globals with definition can force usage."); 820 LLVMUsed.push_back(GV); 821 } 822 823 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 824 assert(!GV->isDeclaration() && 825 "Only globals with definition can force usage."); 826 LLVMCompilerUsed.push_back(GV); 827 } 828 829 static void emitUsed(CodeGenModule &CGM, StringRef Name, 830 std::vector<llvm::WeakVH> &List) { 831 // Don't create llvm.used if there is no need. 832 if (List.empty()) 833 return; 834 835 // Convert List to what ConstantArray needs. 836 SmallVector<llvm::Constant*, 8> UsedArray; 837 UsedArray.resize(List.size()); 838 for (unsigned i = 0, e = List.size(); i != e; ++i) { 839 UsedArray[i] = 840 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]), 841 CGM.Int8PtrTy); 842 } 843 844 if (UsedArray.empty()) 845 return; 846 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 847 848 auto *GV = new llvm::GlobalVariable( 849 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 850 llvm::ConstantArray::get(ATy, UsedArray), Name); 851 852 GV->setSection("llvm.metadata"); 853 } 854 855 void CodeGenModule::emitLLVMUsed() { 856 emitUsed(*this, "llvm.used", LLVMUsed); 857 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 858 } 859 860 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 861 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 862 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 863 } 864 865 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 866 llvm::SmallString<32> Opt; 867 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 868 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 869 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 870 } 871 872 void CodeGenModule::AddDependentLib(StringRef Lib) { 873 llvm::SmallString<24> Opt; 874 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 875 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 876 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 877 } 878 879 /// \brief Add link options implied by the given module, including modules 880 /// it depends on, using a postorder walk. 881 static void addLinkOptionsPostorder(CodeGenModule &CGM, 882 Module *Mod, 883 SmallVectorImpl<llvm::Value *> &Metadata, 884 llvm::SmallPtrSet<Module *, 16> &Visited) { 885 // Import this module's parent. 886 if (Mod->Parent && Visited.insert(Mod->Parent)) { 887 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 888 } 889 890 // Import this module's dependencies. 891 for (unsigned I = Mod->Imports.size(); I > 0; --I) { 892 if (Visited.insert(Mod->Imports[I-1])) 893 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 894 } 895 896 // Add linker options to link against the libraries/frameworks 897 // described by this module. 898 llvm::LLVMContext &Context = CGM.getLLVMContext(); 899 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 900 // Link against a framework. Frameworks are currently Darwin only, so we 901 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 902 if (Mod->LinkLibraries[I-1].IsFramework) { 903 llvm::Value *Args[2] = { 904 llvm::MDString::get(Context, "-framework"), 905 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library) 906 }; 907 908 Metadata.push_back(llvm::MDNode::get(Context, Args)); 909 continue; 910 } 911 912 // Link against a library. 913 llvm::SmallString<24> Opt; 914 CGM.getTargetCodeGenInfo().getDependentLibraryOption( 915 Mod->LinkLibraries[I-1].Library, Opt); 916 llvm::Value *OptString = llvm::MDString::get(Context, Opt); 917 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 918 } 919 } 920 921 void CodeGenModule::EmitModuleLinkOptions() { 922 // Collect the set of all of the modules we want to visit to emit link 923 // options, which is essentially the imported modules and all of their 924 // non-explicit child modules. 925 llvm::SetVector<clang::Module *> LinkModules; 926 llvm::SmallPtrSet<clang::Module *, 16> Visited; 927 SmallVector<clang::Module *, 16> Stack; 928 929 // Seed the stack with imported modules. 930 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(), 931 MEnd = ImportedModules.end(); 932 M != MEnd; ++M) { 933 if (Visited.insert(*M)) 934 Stack.push_back(*M); 935 } 936 937 // Find all of the modules to import, making a little effort to prune 938 // non-leaf modules. 939 while (!Stack.empty()) { 940 clang::Module *Mod = Stack.pop_back_val(); 941 942 bool AnyChildren = false; 943 944 // Visit the submodules of this module. 945 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 946 SubEnd = Mod->submodule_end(); 947 Sub != SubEnd; ++Sub) { 948 // Skip explicit children; they need to be explicitly imported to be 949 // linked against. 950 if ((*Sub)->IsExplicit) 951 continue; 952 953 if (Visited.insert(*Sub)) { 954 Stack.push_back(*Sub); 955 AnyChildren = true; 956 } 957 } 958 959 // We didn't find any children, so add this module to the list of 960 // modules to link against. 961 if (!AnyChildren) { 962 LinkModules.insert(Mod); 963 } 964 } 965 966 // Add link options for all of the imported modules in reverse topological 967 // order. We don't do anything to try to order import link flags with respect 968 // to linker options inserted by things like #pragma comment(). 969 SmallVector<llvm::Value *, 16> MetadataArgs; 970 Visited.clear(); 971 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(), 972 MEnd = LinkModules.end(); 973 M != MEnd; ++M) { 974 if (Visited.insert(*M)) 975 addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited); 976 } 977 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 978 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 979 980 // Add the linker options metadata flag. 981 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 982 llvm::MDNode::get(getLLVMContext(), 983 LinkerOptionsMetadata)); 984 } 985 986 void CodeGenModule::EmitDeferred() { 987 // Emit code for any potentially referenced deferred decls. Since a 988 // previously unused static decl may become used during the generation of code 989 // for a static function, iterate until no changes are made. 990 991 while (true) { 992 if (!DeferredVTables.empty()) { 993 EmitDeferredVTables(); 994 995 // Emitting a v-table doesn't directly cause more v-tables to 996 // become deferred, although it can cause functions to be 997 // emitted that then need those v-tables. 998 assert(DeferredVTables.empty()); 999 } 1000 1001 // Stop if we're out of both deferred v-tables and deferred declarations. 1002 if (DeferredDeclsToEmit.empty()) break; 1003 1004 DeferredGlobal &G = DeferredDeclsToEmit.back(); 1005 GlobalDecl D = G.GD; 1006 llvm::GlobalValue *GV = G.GV; 1007 DeferredDeclsToEmit.pop_back(); 1008 1009 assert(GV == GetGlobalValue(getMangledName(D))); 1010 // Check to see if we've already emitted this. This is necessary 1011 // for a couple of reasons: first, decls can end up in the 1012 // deferred-decls queue multiple times, and second, decls can end 1013 // up with definitions in unusual ways (e.g. by an extern inline 1014 // function acquiring a strong function redefinition). Just 1015 // ignore these cases. 1016 if(!GV->isDeclaration()) 1017 continue; 1018 1019 // Otherwise, emit the definition and move on to the next one. 1020 EmitGlobalDefinition(D, GV); 1021 } 1022 } 1023 1024 void CodeGenModule::EmitGlobalAnnotations() { 1025 if (Annotations.empty()) 1026 return; 1027 1028 // Create a new global variable for the ConstantStruct in the Module. 1029 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 1030 Annotations[0]->getType(), Annotations.size()), Annotations); 1031 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 1032 llvm::GlobalValue::AppendingLinkage, 1033 Array, "llvm.global.annotations"); 1034 gv->setSection(AnnotationSection); 1035 } 1036 1037 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1038 llvm::Constant *&AStr = AnnotationStrings[Str]; 1039 if (AStr) 1040 return AStr; 1041 1042 // Not found yet, create a new global. 1043 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 1044 auto *gv = 1045 new llvm::GlobalVariable(getModule(), s->getType(), true, 1046 llvm::GlobalValue::PrivateLinkage, s, ".str"); 1047 gv->setSection(AnnotationSection); 1048 gv->setUnnamedAddr(true); 1049 AStr = gv; 1050 return gv; 1051 } 1052 1053 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 1054 SourceManager &SM = getContext().getSourceManager(); 1055 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 1056 if (PLoc.isValid()) 1057 return EmitAnnotationString(PLoc.getFilename()); 1058 return EmitAnnotationString(SM.getBufferName(Loc)); 1059 } 1060 1061 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 1062 SourceManager &SM = getContext().getSourceManager(); 1063 PresumedLoc PLoc = SM.getPresumedLoc(L); 1064 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 1065 SM.getExpansionLineNumber(L); 1066 return llvm::ConstantInt::get(Int32Ty, LineNo); 1067 } 1068 1069 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1070 const AnnotateAttr *AA, 1071 SourceLocation L) { 1072 // Get the globals for file name, annotation, and the line number. 1073 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 1074 *UnitGV = EmitAnnotationUnit(L), 1075 *LineNoCst = EmitAnnotationLineNo(L); 1076 1077 // Create the ConstantStruct for the global annotation. 1078 llvm::Constant *Fields[4] = { 1079 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 1080 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 1081 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 1082 LineNoCst 1083 }; 1084 return llvm::ConstantStruct::getAnon(Fields); 1085 } 1086 1087 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 1088 llvm::GlobalValue *GV) { 1089 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1090 // Get the struct elements for these annotations. 1091 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 1092 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 1093 } 1094 1095 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 1096 // Never defer when EmitAllDecls is specified. 1097 if (LangOpts.EmitAllDecls) 1098 return false; 1099 1100 return !getContext().DeclMustBeEmitted(Global); 1101 } 1102 1103 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor( 1104 const CXXUuidofExpr* E) { 1105 // Sema has verified that IIDSource has a __declspec(uuid()), and that its 1106 // well-formed. 1107 StringRef Uuid = E->getUuidAsStringRef(Context); 1108 std::string Name = "_GUID_" + Uuid.lower(); 1109 std::replace(Name.begin(), Name.end(), '-', '_'); 1110 1111 // Look for an existing global. 1112 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 1113 return GV; 1114 1115 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType()); 1116 assert(Init && "failed to initialize as constant"); 1117 1118 auto *GV = new llvm::GlobalVariable( 1119 getModule(), Init->getType(), 1120 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 1121 return GV; 1122 } 1123 1124 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1125 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1126 assert(AA && "No alias?"); 1127 1128 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1129 1130 // See if there is already something with the target's name in the module. 1131 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 1132 if (Entry) { 1133 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 1134 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 1135 } 1136 1137 llvm::Constant *Aliasee; 1138 if (isa<llvm::FunctionType>(DeclTy)) 1139 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 1140 GlobalDecl(cast<FunctionDecl>(VD)), 1141 /*ForVTable=*/false); 1142 else 1143 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1144 llvm::PointerType::getUnqual(DeclTy), 0); 1145 1146 auto *F = cast<llvm::GlobalValue>(Aliasee); 1147 F->setLinkage(llvm::Function::ExternalWeakLinkage); 1148 WeakRefReferences.insert(F); 1149 1150 return Aliasee; 1151 } 1152 1153 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 1154 const auto *Global = cast<ValueDecl>(GD.getDecl()); 1155 1156 // Weak references don't produce any output by themselves. 1157 if (Global->hasAttr<WeakRefAttr>()) 1158 return; 1159 1160 // If this is an alias definition (which otherwise looks like a declaration) 1161 // emit it now. 1162 if (Global->hasAttr<AliasAttr>()) 1163 return EmitAliasDefinition(GD); 1164 1165 // If this is CUDA, be selective about which declarations we emit. 1166 if (LangOpts.CUDA) { 1167 if (CodeGenOpts.CUDAIsDevice) { 1168 if (!Global->hasAttr<CUDADeviceAttr>() && 1169 !Global->hasAttr<CUDAGlobalAttr>() && 1170 !Global->hasAttr<CUDAConstantAttr>() && 1171 !Global->hasAttr<CUDASharedAttr>()) 1172 return; 1173 } else { 1174 if (!Global->hasAttr<CUDAHostAttr>() && ( 1175 Global->hasAttr<CUDADeviceAttr>() || 1176 Global->hasAttr<CUDAConstantAttr>() || 1177 Global->hasAttr<CUDASharedAttr>())) 1178 return; 1179 } 1180 } 1181 1182 // Ignore declarations, they will be emitted on their first use. 1183 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1184 // Forward declarations are emitted lazily on first use. 1185 if (!FD->doesThisDeclarationHaveABody()) { 1186 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1187 return; 1188 1189 StringRef MangledName = getMangledName(GD); 1190 1191 // Compute the function info and LLVM type. 1192 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 1193 llvm::Type *Ty = getTypes().GetFunctionType(FI); 1194 1195 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 1196 /*DontDefer=*/false); 1197 return; 1198 } 1199 } else { 1200 const auto *VD = cast<VarDecl>(Global); 1201 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1202 1203 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 1204 return; 1205 } 1206 1207 // Defer code generation when possible if this is a static definition, inline 1208 // function etc. These we only want to emit if they are used. 1209 if (!MayDeferGeneration(Global)) { 1210 // Emit the definition if it can't be deferred. 1211 EmitGlobalDefinition(GD); 1212 return; 1213 } 1214 1215 // If we're deferring emission of a C++ variable with an 1216 // initializer, remember the order in which it appeared in the file. 1217 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1218 cast<VarDecl>(Global)->hasInit()) { 1219 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 1220 CXXGlobalInits.push_back(0); 1221 } 1222 1223 // If the value has already been used, add it directly to the 1224 // DeferredDeclsToEmit list. 1225 StringRef MangledName = getMangledName(GD); 1226 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) 1227 addDeferredDeclToEmit(GV, GD); 1228 else { 1229 // Otherwise, remember that we saw a deferred decl with this name. The 1230 // first use of the mangled name will cause it to move into 1231 // DeferredDeclsToEmit. 1232 DeferredDecls[MangledName] = GD; 1233 } 1234 } 1235 1236 namespace { 1237 struct FunctionIsDirectlyRecursive : 1238 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1239 const StringRef Name; 1240 const Builtin::Context &BI; 1241 bool Result; 1242 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1243 Name(N), BI(C), Result(false) { 1244 } 1245 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1246 1247 bool TraverseCallExpr(CallExpr *E) { 1248 const FunctionDecl *FD = E->getDirectCallee(); 1249 if (!FD) 1250 return true; 1251 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1252 if (Attr && Name == Attr->getLabel()) { 1253 Result = true; 1254 return false; 1255 } 1256 unsigned BuiltinID = FD->getBuiltinID(); 1257 if (!BuiltinID) 1258 return true; 1259 StringRef BuiltinName = BI.GetName(BuiltinID); 1260 if (BuiltinName.startswith("__builtin_") && 1261 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1262 Result = true; 1263 return false; 1264 } 1265 return true; 1266 } 1267 }; 1268 } 1269 1270 // isTriviallyRecursive - Check if this function calls another 1271 // decl that, because of the asm attribute or the other decl being a builtin, 1272 // ends up pointing to itself. 1273 bool 1274 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1275 StringRef Name; 1276 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1277 // asm labels are a special kind of mangling we have to support. 1278 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1279 if (!Attr) 1280 return false; 1281 Name = Attr->getLabel(); 1282 } else { 1283 Name = FD->getName(); 1284 } 1285 1286 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1287 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1288 return Walker.Result; 1289 } 1290 1291 bool 1292 CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1293 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1294 return true; 1295 const auto *F = cast<FunctionDecl>(GD.getDecl()); 1296 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1297 return false; 1298 // PR9614. Avoid cases where the source code is lying to us. An available 1299 // externally function should have an equivalent function somewhere else, 1300 // but a function that calls itself is clearly not equivalent to the real 1301 // implementation. 1302 // This happens in glibc's btowc and in some configure checks. 1303 return !isTriviallyRecursive(F); 1304 } 1305 1306 /// If the type for the method's class was generated by 1307 /// CGDebugInfo::createContextChain(), the cache contains only a 1308 /// limited DIType without any declarations. Since EmitFunctionStart() 1309 /// needs to find the canonical declaration for each method, we need 1310 /// to construct the complete type prior to emitting the method. 1311 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) { 1312 if (!D->isInstance()) 1313 return; 1314 1315 if (CGDebugInfo *DI = getModuleDebugInfo()) 1316 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 1317 const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext())); 1318 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation()); 1319 } 1320 } 1321 1322 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 1323 const auto *D = cast<ValueDecl>(GD.getDecl()); 1324 1325 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1326 Context.getSourceManager(), 1327 "Generating code for declaration"); 1328 1329 if (isa<FunctionDecl>(D)) { 1330 // At -O0, don't generate IR for functions with available_externally 1331 // linkage. 1332 if (!shouldEmitFunction(GD)) 1333 return; 1334 1335 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 1336 CompleteDIClassType(Method); 1337 // Make sure to emit the definition(s) before we emit the thunks. 1338 // This is necessary for the generation of certain thunks. 1339 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 1340 EmitCXXConstructor(CD, GD.getCtorType()); 1341 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 1342 EmitCXXDestructor(DD, GD.getDtorType()); 1343 else 1344 EmitGlobalFunctionDefinition(GD, GV); 1345 1346 if (Method->isVirtual()) 1347 getVTables().EmitThunks(GD); 1348 1349 return; 1350 } 1351 1352 return EmitGlobalFunctionDefinition(GD, GV); 1353 } 1354 1355 if (const auto *VD = dyn_cast<VarDecl>(D)) 1356 return EmitGlobalVarDefinition(VD); 1357 1358 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1359 } 1360 1361 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1362 /// module, create and return an llvm Function with the specified type. If there 1363 /// is something in the module with the specified name, return it potentially 1364 /// bitcasted to the right type. 1365 /// 1366 /// If D is non-null, it specifies a decl that correspond to this. This is used 1367 /// to set the attributes on the function when it is first created. 1368 llvm::Constant * 1369 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 1370 llvm::Type *Ty, 1371 GlobalDecl GD, bool ForVTable, 1372 bool DontDefer, 1373 llvm::AttributeSet ExtraAttrs) { 1374 const Decl *D = GD.getDecl(); 1375 1376 // Lookup the entry, lazily creating it if necessary. 1377 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1378 if (Entry) { 1379 if (WeakRefReferences.erase(Entry)) { 1380 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1381 if (FD && !FD->hasAttr<WeakAttr>()) 1382 Entry->setLinkage(llvm::Function::ExternalLinkage); 1383 } 1384 1385 if (Entry->getType()->getElementType() == Ty) 1386 return Entry; 1387 1388 // Make sure the result is of the correct type. 1389 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1390 } 1391 1392 // This function doesn't have a complete type (for example, the return 1393 // type is an incomplete struct). Use a fake type instead, and make 1394 // sure not to try to set attributes. 1395 bool IsIncompleteFunction = false; 1396 1397 llvm::FunctionType *FTy; 1398 if (isa<llvm::FunctionType>(Ty)) { 1399 FTy = cast<llvm::FunctionType>(Ty); 1400 } else { 1401 FTy = llvm::FunctionType::get(VoidTy, false); 1402 IsIncompleteFunction = true; 1403 } 1404 1405 llvm::Function *F = llvm::Function::Create(FTy, 1406 llvm::Function::ExternalLinkage, 1407 MangledName, &getModule()); 1408 assert(F->getName() == MangledName && "name was uniqued!"); 1409 if (D) 1410 SetFunctionAttributes(GD, F, IsIncompleteFunction); 1411 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1412 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1413 F->addAttributes(llvm::AttributeSet::FunctionIndex, 1414 llvm::AttributeSet::get(VMContext, 1415 llvm::AttributeSet::FunctionIndex, 1416 B)); 1417 } 1418 1419 if (!DontDefer) { 1420 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 1421 // each other bottoming out with the base dtor. Therefore we emit non-base 1422 // dtors on usage, even if there is no dtor definition in the TU. 1423 if (D && isa<CXXDestructorDecl>(D) && 1424 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 1425 GD.getDtorType())) 1426 addDeferredDeclToEmit(F, GD); 1427 1428 // This is the first use or definition of a mangled name. If there is a 1429 // deferred decl with this name, remember that we need to emit it at the end 1430 // of the file. 1431 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1432 if (DDI != DeferredDecls.end()) { 1433 // Move the potentially referenced deferred decl to the 1434 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 1435 // don't need it anymore). 1436 addDeferredDeclToEmit(F, DDI->second); 1437 DeferredDecls.erase(DDI); 1438 1439 // Otherwise, if this is a sized deallocation function, emit a weak 1440 // definition 1441 // for it at the end of the translation unit. 1442 } else if (D && cast<FunctionDecl>(D) 1443 ->getCorrespondingUnsizedGlobalDeallocationFunction()) { 1444 addDeferredDeclToEmit(F, GD); 1445 1446 // Otherwise, there are cases we have to worry about where we're 1447 // using a declaration for which we must emit a definition but where 1448 // we might not find a top-level definition: 1449 // - member functions defined inline in their classes 1450 // - friend functions defined inline in some class 1451 // - special member functions with implicit definitions 1452 // If we ever change our AST traversal to walk into class methods, 1453 // this will be unnecessary. 1454 // 1455 // We also don't emit a definition for a function if it's going to be an 1456 // entry 1457 // in a vtable, unless it's already marked as used. 1458 } else if (getLangOpts().CPlusPlus && D) { 1459 // Look for a declaration that's lexically in a record. 1460 const auto *FD = cast<FunctionDecl>(D); 1461 FD = FD->getMostRecentDecl(); 1462 do { 1463 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 1464 if (FD->isImplicit() && !ForVTable) { 1465 assert(FD->isUsed() && 1466 "Sema didn't mark implicit function as used!"); 1467 addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 1468 break; 1469 } else if (FD->doesThisDeclarationHaveABody()) { 1470 addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 1471 break; 1472 } 1473 } 1474 FD = FD->getPreviousDecl(); 1475 } while (FD); 1476 } 1477 } 1478 1479 getTargetCodeGenInfo().emitTargetMD(D, F, *this); 1480 1481 // Make sure the result is of the requested type. 1482 if (!IsIncompleteFunction) { 1483 assert(F->getType()->getElementType() == Ty); 1484 return F; 1485 } 1486 1487 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1488 return llvm::ConstantExpr::getBitCast(F, PTy); 1489 } 1490 1491 /// GetAddrOfFunction - Return the address of the given function. If Ty is 1492 /// non-null, then this function will use the specified type if it has to 1493 /// create it (this occurs when we see a definition of the function). 1494 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 1495 llvm::Type *Ty, 1496 bool ForVTable, 1497 bool DontDefer) { 1498 // If there was no specific requested type, just convert it now. 1499 if (!Ty) 1500 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 1501 1502 StringRef MangledName = getMangledName(GD); 1503 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer); 1504 } 1505 1506 /// CreateRuntimeFunction - Create a new runtime function with the specified 1507 /// type and name. 1508 llvm::Constant * 1509 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 1510 StringRef Name, 1511 llvm::AttributeSet ExtraAttrs) { 1512 llvm::Constant *C = 1513 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 1514 /*DontDefer=*/false, ExtraAttrs); 1515 if (auto *F = dyn_cast<llvm::Function>(C)) 1516 if (F->empty()) 1517 F->setCallingConv(getRuntimeCC()); 1518 return C; 1519 } 1520 1521 /// isTypeConstant - Determine whether an object of this type can be emitted 1522 /// as a constant. 1523 /// 1524 /// If ExcludeCtor is true, the duration when the object's constructor runs 1525 /// will not be considered. The caller will need to verify that the object is 1526 /// not written to during its construction. 1527 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 1528 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 1529 return false; 1530 1531 if (Context.getLangOpts().CPlusPlus) { 1532 if (const CXXRecordDecl *Record 1533 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 1534 return ExcludeCtor && !Record->hasMutableFields() && 1535 Record->hasTrivialDestructor(); 1536 } 1537 1538 return true; 1539 } 1540 1541 static bool isVarDeclInlineInitializedStaticDataMember(const VarDecl *VD) { 1542 if (!VD->isStaticDataMember()) 1543 return false; 1544 const VarDecl *InitDecl; 1545 const Expr *InitExpr = VD->getAnyInitializer(InitDecl); 1546 if (!InitExpr) 1547 return false; 1548 if (InitDecl->isThisDeclarationADefinition()) 1549 return false; 1550 return true; 1551 } 1552 1553 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1554 /// create and return an llvm GlobalVariable with the specified type. If there 1555 /// is something in the module with the specified name, return it potentially 1556 /// bitcasted to the right type. 1557 /// 1558 /// If D is non-null, it specifies a decl that correspond to this. This is used 1559 /// to set the attributes on the global when it is first created. 1560 llvm::Constant * 1561 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 1562 llvm::PointerType *Ty, 1563 const VarDecl *D, 1564 bool UnnamedAddr) { 1565 // Lookup the entry, lazily creating it if necessary. 1566 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1567 if (Entry) { 1568 if (WeakRefReferences.erase(Entry)) { 1569 if (D && !D->hasAttr<WeakAttr>()) 1570 Entry->setLinkage(llvm::Function::ExternalLinkage); 1571 } 1572 1573 if (UnnamedAddr) 1574 Entry->setUnnamedAddr(true); 1575 1576 if (Entry->getType() == Ty) 1577 return Entry; 1578 1579 // Make sure the result is of the correct type. 1580 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 1581 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 1582 1583 return llvm::ConstantExpr::getBitCast(Entry, Ty); 1584 } 1585 1586 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 1587 auto *GV = new llvm::GlobalVariable( 1588 getModule(), Ty->getElementType(), false, 1589 llvm::GlobalValue::ExternalLinkage, 0, MangledName, 0, 1590 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 1591 1592 // This is the first use or definition of a mangled name. If there is a 1593 // deferred decl with this name, remember that we need to emit it at the end 1594 // of the file. 1595 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 1596 if (DDI != DeferredDecls.end()) { 1597 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1598 // list, and remove it from DeferredDecls (since we don't need it anymore). 1599 addDeferredDeclToEmit(GV, DDI->second); 1600 DeferredDecls.erase(DDI); 1601 } 1602 1603 // Handle things which are present even on external declarations. 1604 if (D) { 1605 // FIXME: This code is overly simple and should be merged with other global 1606 // handling. 1607 GV->setConstant(isTypeConstant(D->getType(), false)); 1608 1609 setLinkageAndVisibilityForGV(GV, D); 1610 1611 if (D->getTLSKind()) { 1612 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 1613 CXXThreadLocals.push_back(std::make_pair(D, GV)); 1614 setTLSMode(GV, *D); 1615 } 1616 1617 // If required by the ABI, treat declarations of static data members with 1618 // inline initializers as definitions. 1619 if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() && 1620 isVarDeclInlineInitializedStaticDataMember(D)) 1621 EmitGlobalVarDefinition(D); 1622 1623 // Handle XCore specific ABI requirements. 1624 if (getTarget().getTriple().getArch() == llvm::Triple::xcore && 1625 D->getLanguageLinkage() == CLanguageLinkage && 1626 D->getType().isConstant(Context) && 1627 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 1628 GV->setSection(".cp.rodata"); 1629 } 1630 1631 if (AddrSpace != Ty->getAddressSpace()) 1632 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 1633 1634 getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 1635 1636 return GV; 1637 } 1638 1639 1640 llvm::GlobalVariable * 1641 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 1642 llvm::Type *Ty, 1643 llvm::GlobalValue::LinkageTypes Linkage) { 1644 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 1645 llvm::GlobalVariable *OldGV = 0; 1646 1647 1648 if (GV) { 1649 // Check if the variable has the right type. 1650 if (GV->getType()->getElementType() == Ty) 1651 return GV; 1652 1653 // Because C++ name mangling, the only way we can end up with an already 1654 // existing global with the same name is if it has been declared extern "C". 1655 assert(GV->isDeclaration() && "Declaration has wrong type!"); 1656 OldGV = GV; 1657 } 1658 1659 // Create a new variable. 1660 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 1661 Linkage, 0, Name); 1662 1663 if (OldGV) { 1664 // Replace occurrences of the old variable if needed. 1665 GV->takeName(OldGV); 1666 1667 if (!OldGV->use_empty()) { 1668 llvm::Constant *NewPtrForOldDecl = 1669 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 1670 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 1671 } 1672 1673 OldGV->eraseFromParent(); 1674 } 1675 1676 return GV; 1677 } 1678 1679 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1680 /// given global variable. If Ty is non-null and if the global doesn't exist, 1681 /// then it will be created with the specified type instead of whatever the 1682 /// normal requested type would be. 1683 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 1684 llvm::Type *Ty) { 1685 assert(D->hasGlobalStorage() && "Not a global variable"); 1686 QualType ASTTy = D->getType(); 1687 if (Ty == 0) 1688 Ty = getTypes().ConvertTypeForMem(ASTTy); 1689 1690 llvm::PointerType *PTy = 1691 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 1692 1693 StringRef MangledName = getMangledName(D); 1694 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1695 } 1696 1697 /// CreateRuntimeVariable - Create a new runtime global variable with the 1698 /// specified type and name. 1699 llvm::Constant * 1700 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 1701 StringRef Name) { 1702 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0, 1703 true); 1704 } 1705 1706 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1707 assert(!D->getInit() && "Cannot emit definite definitions here!"); 1708 1709 if (MayDeferGeneration(D)) { 1710 // If we have not seen a reference to this variable yet, place it 1711 // into the deferred declarations table to be emitted if needed 1712 // later. 1713 StringRef MangledName = getMangledName(D); 1714 if (!GetGlobalValue(MangledName)) { 1715 DeferredDecls[MangledName] = D; 1716 return; 1717 } 1718 } 1719 1720 // The tentative definition is the only definition. 1721 EmitGlobalVarDefinition(D); 1722 } 1723 1724 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 1725 return Context.toCharUnitsFromBits( 1726 TheDataLayout.getTypeStoreSizeInBits(Ty)); 1727 } 1728 1729 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 1730 unsigned AddrSpace) { 1731 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) { 1732 if (D->hasAttr<CUDAConstantAttr>()) 1733 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 1734 else if (D->hasAttr<CUDASharedAttr>()) 1735 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 1736 else 1737 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 1738 } 1739 1740 return AddrSpace; 1741 } 1742 1743 template<typename SomeDecl> 1744 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 1745 llvm::GlobalValue *GV) { 1746 if (!getLangOpts().CPlusPlus) 1747 return; 1748 1749 // Must have 'used' attribute, or else inline assembly can't rely on 1750 // the name existing. 1751 if (!D->template hasAttr<UsedAttr>()) 1752 return; 1753 1754 // Must have internal linkage and an ordinary name. 1755 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 1756 return; 1757 1758 // Must be in an extern "C" context. Entities declared directly within 1759 // a record are not extern "C" even if the record is in such a context. 1760 const SomeDecl *First = D->getFirstDecl(); 1761 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 1762 return; 1763 1764 // OK, this is an internal linkage entity inside an extern "C" linkage 1765 // specification. Make a note of that so we can give it the "expected" 1766 // mangled name if nothing else is using that name. 1767 std::pair<StaticExternCMap::iterator, bool> R = 1768 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 1769 1770 // If we have multiple internal linkage entities with the same name 1771 // in extern "C" regions, none of them gets that name. 1772 if (!R.second) 1773 R.first->second = 0; 1774 } 1775 1776 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1777 llvm::Constant *Init = 0; 1778 QualType ASTTy = D->getType(); 1779 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1780 bool NeedsGlobalCtor = false; 1781 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 1782 1783 const VarDecl *InitDecl; 1784 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 1785 1786 if (!InitExpr) { 1787 // This is a tentative definition; tentative definitions are 1788 // implicitly initialized with { 0 }. 1789 // 1790 // Note that tentative definitions are only emitted at the end of 1791 // a translation unit, so they should never have incomplete 1792 // type. In addition, EmitTentativeDefinition makes sure that we 1793 // never attempt to emit a tentative definition if a real one 1794 // exists. A use may still exists, however, so we still may need 1795 // to do a RAUW. 1796 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1797 Init = EmitNullConstant(D->getType()); 1798 } else { 1799 initializedGlobalDecl = GlobalDecl(D); 1800 Init = EmitConstantInit(*InitDecl); 1801 1802 if (!Init) { 1803 QualType T = InitExpr->getType(); 1804 if (D->getType()->isReferenceType()) 1805 T = D->getType(); 1806 1807 if (getLangOpts().CPlusPlus) { 1808 Init = EmitNullConstant(T); 1809 NeedsGlobalCtor = true; 1810 } else { 1811 ErrorUnsupported(D, "static initializer"); 1812 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1813 } 1814 } else { 1815 // We don't need an initializer, so remove the entry for the delayed 1816 // initializer position (just in case this entry was delayed) if we 1817 // also don't need to register a destructor. 1818 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 1819 DelayedCXXInitPosition.erase(D); 1820 } 1821 } 1822 1823 llvm::Type* InitType = Init->getType(); 1824 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1825 1826 // Strip off a bitcast if we got one back. 1827 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1828 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1829 CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 1830 // All zero index gep. 1831 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1832 Entry = CE->getOperand(0); 1833 } 1834 1835 // Entry is now either a Function or GlobalVariable. 1836 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1837 1838 // We have a definition after a declaration with the wrong type. 1839 // We must make a new GlobalVariable* and update everything that used OldGV 1840 // (a declaration or tentative definition) with the new GlobalVariable* 1841 // (which will be a definition). 1842 // 1843 // This happens if there is a prototype for a global (e.g. 1844 // "extern int x[];") and then a definition of a different type (e.g. 1845 // "int x[10];"). This also happens when an initializer has a different type 1846 // from the type of the global (this happens with unions). 1847 if (GV == 0 || 1848 GV->getType()->getElementType() != InitType || 1849 GV->getType()->getAddressSpace() != 1850 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 1851 1852 // Move the old entry aside so that we'll create a new one. 1853 Entry->setName(StringRef()); 1854 1855 // Make a new global with the correct type, this is now guaranteed to work. 1856 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1857 1858 // Replace all uses of the old global with the new global 1859 llvm::Constant *NewPtrForOldDecl = 1860 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1861 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1862 1863 // Erase the old global, since it is no longer used. 1864 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1865 } 1866 1867 MaybeHandleStaticInExternC(D, GV); 1868 1869 if (D->hasAttr<AnnotateAttr>()) 1870 AddGlobalAnnotations(D, GV); 1871 1872 GV->setInitializer(Init); 1873 1874 // If it is safe to mark the global 'constant', do so now. 1875 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 1876 isTypeConstant(D->getType(), true)); 1877 1878 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1879 1880 // Set the llvm linkage type as appropriate. 1881 llvm::GlobalValue::LinkageTypes Linkage = 1882 getLLVMLinkageVarDefinition(D, GV->isConstant()); 1883 GV->setLinkage(Linkage); 1884 if (D->hasAttr<DLLImportAttr>()) 1885 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 1886 else if (D->hasAttr<DLLExportAttr>()) 1887 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 1888 1889 if (Linkage == llvm::GlobalVariable::CommonLinkage) 1890 // common vars aren't constant even if declared const. 1891 GV->setConstant(false); 1892 1893 setNonAliasAttributes(D, GV); 1894 1895 // Emit the initializer function if necessary. 1896 if (NeedsGlobalCtor || NeedsGlobalDtor) 1897 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 1898 1899 // If we are compiling with ASan, add metadata indicating dynamically 1900 // initialized globals. 1901 if (SanOpts.Address && NeedsGlobalCtor) { 1902 llvm::Module &M = getModule(); 1903 1904 llvm::NamedMDNode *DynamicInitializers = 1905 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals"); 1906 llvm::Value *GlobalToAdd[] = { GV }; 1907 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd); 1908 DynamicInitializers->addOperand(ThisGlobal); 1909 } 1910 1911 // Emit global variable debug information. 1912 if (CGDebugInfo *DI = getModuleDebugInfo()) 1913 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 1914 DI->EmitGlobalVariable(GV, D); 1915 } 1916 1917 static bool isVarDeclStrongDefinition(const VarDecl *D, bool NoCommon) { 1918 // Don't give variables common linkage if -fno-common was specified unless it 1919 // was overridden by a NoCommon attribute. 1920 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 1921 return true; 1922 1923 // C11 6.9.2/2: 1924 // A declaration of an identifier for an object that has file scope without 1925 // an initializer, and without a storage-class specifier or with the 1926 // storage-class specifier static, constitutes a tentative definition. 1927 if (D->getInit() || D->hasExternalStorage()) 1928 return true; 1929 1930 // A variable cannot be both common and exist in a section. 1931 if (D->hasAttr<SectionAttr>()) 1932 return true; 1933 1934 // Thread local vars aren't considered common linkage. 1935 if (D->getTLSKind()) 1936 return true; 1937 1938 // Tentative definitions marked with WeakImportAttr are true definitions. 1939 if (D->hasAttr<WeakImportAttr>()) 1940 return true; 1941 1942 return false; 1943 } 1944 1945 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageforDeclarator( 1946 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable, 1947 bool UseThunkForDtorVariant) { 1948 if (Linkage == GVA_Internal) 1949 return llvm::Function::InternalLinkage; 1950 1951 if (D->hasAttr<WeakAttr>()) { 1952 if (IsConstantVariable) 1953 return llvm::GlobalVariable::WeakODRLinkage; 1954 else 1955 return llvm::GlobalVariable::WeakAnyLinkage; 1956 } 1957 1958 // We are guaranteed to have a strong definition somewhere else, 1959 // so we can use available_externally linkage. 1960 if (Linkage == GVA_AvailableExternally) 1961 return llvm::Function::AvailableExternallyLinkage; 1962 1963 // LinkOnceODRLinkage is insufficient if the symbol is required to exist in 1964 // the symbol table. Promote the linkage to WeakODRLinkage to preserve the 1965 // semantics of LinkOnceODRLinkage while providing visibility in the symbol 1966 // table. 1967 llvm::GlobalValue::LinkageTypes OnceLinkage = 1968 llvm::GlobalValue::LinkOnceODRLinkage; 1969 if (D->hasAttr<DLLExportAttr>() || D->hasAttr<DLLImportAttr>()) 1970 OnceLinkage = llvm::GlobalVariable::WeakODRLinkage; 1971 1972 // Note that Apple's kernel linker doesn't support symbol 1973 // coalescing, so we need to avoid linkonce and weak linkages there. 1974 // Normally, this means we just map to internal, but for explicit 1975 // instantiations we'll map to external. 1976 1977 // In C++, the compiler has to emit a definition in every translation unit 1978 // that references the function. We should use linkonce_odr because 1979 // a) if all references in this translation unit are optimized away, we 1980 // don't need to codegen it. b) if the function persists, it needs to be 1981 // merged with other definitions. c) C++ has the ODR, so we know the 1982 // definition is dependable. 1983 if (Linkage == GVA_DiscardableODR) 1984 return !Context.getLangOpts().AppleKext ? OnceLinkage 1985 : llvm::Function::InternalLinkage; 1986 1987 // An explicit instantiation of a template has weak linkage, since 1988 // explicit instantiations can occur in multiple translation units 1989 // and must all be equivalent. However, we are not allowed to 1990 // throw away these explicit instantiations. 1991 if (Linkage == GVA_StrongODR) 1992 return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage 1993 : llvm::Function::ExternalLinkage; 1994 1995 // Destructor variants in the Microsoft C++ ABI are always linkonce_odr thunks 1996 // emitted on an as-needed basis. 1997 if (UseThunkForDtorVariant) 1998 return OnceLinkage; 1999 2000 // If required by the ABI, give definitions of static data members with inline 2001 // initializers at least linkonce_odr linkage. 2002 if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() && 2003 isa<VarDecl>(D) && 2004 isVarDeclInlineInitializedStaticDataMember(cast<VarDecl>(D))) 2005 return OnceLinkage; 2006 2007 // C++ doesn't have tentative definitions and thus cannot have common 2008 // linkage. 2009 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 2010 !isVarDeclStrongDefinition(cast<VarDecl>(D), CodeGenOpts.NoCommon)) 2011 return llvm::GlobalVariable::CommonLinkage; 2012 2013 // selectany symbols are externally visible, so use weak instead of 2014 // linkonce. MSVC optimizes away references to const selectany globals, so 2015 // all definitions should be the same and ODR linkage should be used. 2016 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 2017 if (D->hasAttr<SelectAnyAttr>()) 2018 return llvm::GlobalVariable::WeakODRLinkage; 2019 2020 // Otherwise, we have strong external linkage. 2021 assert(Linkage == GVA_StrongExternal); 2022 return llvm::GlobalVariable::ExternalLinkage; 2023 } 2024 2025 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 2026 const VarDecl *VD, bool IsConstant) { 2027 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 2028 return getLLVMLinkageforDeclarator(VD, Linkage, IsConstant, 2029 /*UseThunkForDtorVariant=*/false); 2030 } 2031 2032 /// Replace the uses of a function that was declared with a non-proto type. 2033 /// We want to silently drop extra arguments from call sites 2034 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2035 llvm::Function *newFn) { 2036 // Fast path. 2037 if (old->use_empty()) return; 2038 2039 llvm::Type *newRetTy = newFn->getReturnType(); 2040 SmallVector<llvm::Value*, 4> newArgs; 2041 2042 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2043 ui != ue; ) { 2044 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 2045 llvm::User *user = use->getUser(); 2046 2047 // Recognize and replace uses of bitcasts. Most calls to 2048 // unprototyped functions will use bitcasts. 2049 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2050 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2051 replaceUsesOfNonProtoConstant(bitcast, newFn); 2052 continue; 2053 } 2054 2055 // Recognize calls to the function. 2056 llvm::CallSite callSite(user); 2057 if (!callSite) continue; 2058 if (!callSite.isCallee(&*use)) continue; 2059 2060 // If the return types don't match exactly, then we can't 2061 // transform this call unless it's dead. 2062 if (callSite->getType() != newRetTy && !callSite->use_empty()) 2063 continue; 2064 2065 // Get the call site's attribute list. 2066 SmallVector<llvm::AttributeSet, 8> newAttrs; 2067 llvm::AttributeSet oldAttrs = callSite.getAttributes(); 2068 2069 // Collect any return attributes from the call. 2070 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 2071 newAttrs.push_back( 2072 llvm::AttributeSet::get(newFn->getContext(), 2073 oldAttrs.getRetAttributes())); 2074 2075 // If the function was passed too few arguments, don't transform. 2076 unsigned newNumArgs = newFn->arg_size(); 2077 if (callSite.arg_size() < newNumArgs) continue; 2078 2079 // If extra arguments were passed, we silently drop them. 2080 // If any of the types mismatch, we don't transform. 2081 unsigned argNo = 0; 2082 bool dontTransform = false; 2083 for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 2084 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 2085 if (callSite.getArgument(argNo)->getType() != ai->getType()) { 2086 dontTransform = true; 2087 break; 2088 } 2089 2090 // Add any parameter attributes. 2091 if (oldAttrs.hasAttributes(argNo + 1)) 2092 newAttrs. 2093 push_back(llvm:: 2094 AttributeSet::get(newFn->getContext(), 2095 oldAttrs.getParamAttributes(argNo + 1))); 2096 } 2097 if (dontTransform) 2098 continue; 2099 2100 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 2101 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 2102 oldAttrs.getFnAttributes())); 2103 2104 // Okay, we can transform this. Create the new call instruction and copy 2105 // over the required information. 2106 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2107 2108 llvm::CallSite newCall; 2109 if (callSite.isCall()) { 2110 newCall = llvm::CallInst::Create(newFn, newArgs, "", 2111 callSite.getInstruction()); 2112 } else { 2113 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 2114 newCall = llvm::InvokeInst::Create(newFn, 2115 oldInvoke->getNormalDest(), 2116 oldInvoke->getUnwindDest(), 2117 newArgs, "", 2118 callSite.getInstruction()); 2119 } 2120 newArgs.clear(); // for the next iteration 2121 2122 if (!newCall->getType()->isVoidTy()) 2123 newCall->takeName(callSite.getInstruction()); 2124 newCall.setAttributes( 2125 llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2126 newCall.setCallingConv(callSite.getCallingConv()); 2127 2128 // Finally, remove the old call, replacing any uses with the new one. 2129 if (!callSite->use_empty()) 2130 callSite->replaceAllUsesWith(newCall.getInstruction()); 2131 2132 // Copy debug location attached to CI. 2133 if (!callSite->getDebugLoc().isUnknown()) 2134 newCall->setDebugLoc(callSite->getDebugLoc()); 2135 callSite->eraseFromParent(); 2136 } 2137 } 2138 2139 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2140 /// implement a function with no prototype, e.g. "int foo() {}". If there are 2141 /// existing call uses of the old function in the module, this adjusts them to 2142 /// call the new function directly. 2143 /// 2144 /// This is not just a cleanup: the always_inline pass requires direct calls to 2145 /// functions to be able to inline them. If there is a bitcast in the way, it 2146 /// won't inline them. Instcombine normally deletes these calls, but it isn't 2147 /// run at -O0. 2148 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2149 llvm::Function *NewFn) { 2150 // If we're redefining a global as a function, don't transform it. 2151 if (!isa<llvm::Function>(Old)) return; 2152 2153 replaceUsesOfNonProtoConstant(Old, NewFn); 2154 } 2155 2156 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2157 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2158 // If we have a definition, this might be a deferred decl. If the 2159 // instantiation is explicit, make sure we emit it at the end. 2160 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2161 GetAddrOfGlobalVar(VD); 2162 2163 EmitTopLevelDecl(VD); 2164 } 2165 2166 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 2167 llvm::GlobalValue *GV) { 2168 const auto *D = cast<FunctionDecl>(GD.getDecl()); 2169 2170 // Compute the function info and LLVM type. 2171 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2172 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2173 2174 // Get or create the prototype for the function. 2175 if (!GV) { 2176 llvm::Constant *C = 2177 GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true); 2178 2179 // Strip off a bitcast if we got one back. 2180 if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) { 2181 assert(CE->getOpcode() == llvm::Instruction::BitCast); 2182 GV = cast<llvm::GlobalValue>(CE->getOperand(0)); 2183 } else { 2184 GV = cast<llvm::GlobalValue>(C); 2185 } 2186 } 2187 2188 if (!GV->isDeclaration()) { 2189 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name); 2190 return; 2191 } 2192 2193 if (GV->getType()->getElementType() != Ty) { 2194 // If the types mismatch then we have to rewrite the definition. 2195 assert(GV->isDeclaration() && "Shouldn't replace non-declaration"); 2196 2197 // F is the Function* for the one with the wrong type, we must make a new 2198 // Function* and update everything that used F (a declaration) with the new 2199 // Function* (which will be a definition). 2200 // 2201 // This happens if there is a prototype for a function 2202 // (e.g. "int f()") and then a definition of a different type 2203 // (e.g. "int f(int x)"). Move the old function aside so that it 2204 // doesn't interfere with GetAddrOfFunction. 2205 GV->setName(StringRef()); 2206 auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 2207 2208 // This might be an implementation of a function without a 2209 // prototype, in which case, try to do special replacement of 2210 // calls which match the new prototype. The really key thing here 2211 // is that we also potentially drop arguments from the call site 2212 // so as to make a direct call, which makes the inliner happier 2213 // and suppresses a number of optimizer warnings (!) about 2214 // dropping arguments. 2215 if (!GV->use_empty()) { 2216 ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn); 2217 GV->removeDeadConstantUsers(); 2218 } 2219 2220 // Replace uses of F with the Function we will endow with a body. 2221 if (!GV->use_empty()) { 2222 llvm::Constant *NewPtrForOldDecl = 2223 llvm::ConstantExpr::getBitCast(NewFn, GV->getType()); 2224 GV->replaceAllUsesWith(NewPtrForOldDecl); 2225 } 2226 2227 // Ok, delete the old function now, which is dead. 2228 GV->eraseFromParent(); 2229 2230 GV = NewFn; 2231 } 2232 2233 // We need to set linkage and visibility on the function before 2234 // generating code for it because various parts of IR generation 2235 // want to propagate this information down (e.g. to local static 2236 // declarations). 2237 auto *Fn = cast<llvm::Function>(GV); 2238 setFunctionLinkage(GD, Fn); 2239 2240 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 2241 setGlobalVisibility(Fn, D); 2242 2243 MaybeHandleStaticInExternC(D, Fn); 2244 2245 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2246 2247 setFunctionDefinitionAttributes(D, Fn); 2248 SetLLVMFunctionAttributesForDefinition(D, Fn); 2249 2250 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2251 AddGlobalCtor(Fn, CA->getPriority()); 2252 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2253 AddGlobalDtor(Fn, DA->getPriority()); 2254 if (D->hasAttr<AnnotateAttr>()) 2255 AddGlobalAnnotations(D, Fn); 2256 } 2257 2258 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 2259 const auto *D = cast<ValueDecl>(GD.getDecl()); 2260 const AliasAttr *AA = D->getAttr<AliasAttr>(); 2261 assert(AA && "Not an alias?"); 2262 2263 StringRef MangledName = getMangledName(GD); 2264 2265 // If there is a definition in the module, then it wins over the alias. 2266 // This is dubious, but allow it to be safe. Just ignore the alias. 2267 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2268 if (Entry && !Entry->isDeclaration()) 2269 return; 2270 2271 Aliases.push_back(GD); 2272 2273 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2274 2275 // Create a reference to the named value. This ensures that it is emitted 2276 // if a deferred decl. 2277 llvm::Constant *Aliasee; 2278 if (isa<llvm::FunctionType>(DeclTy)) 2279 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 2280 /*ForVTable=*/false); 2281 else 2282 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2283 llvm::PointerType::getUnqual(DeclTy), 0); 2284 2285 // Create the new alias itself, but don't set a name yet. 2286 auto *GA = 2287 new llvm::GlobalAlias(Aliasee->getType(), llvm::Function::ExternalLinkage, 2288 "", Aliasee, &getModule()); 2289 2290 if (Entry) { 2291 assert(Entry->isDeclaration()); 2292 2293 // If there is a declaration in the module, then we had an extern followed 2294 // by the alias, as in: 2295 // extern int test6(); 2296 // ... 2297 // int test6() __attribute__((alias("test7"))); 2298 // 2299 // Remove it and replace uses of it with the alias. 2300 GA->takeName(Entry); 2301 2302 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2303 Entry->getType())); 2304 Entry->eraseFromParent(); 2305 } else { 2306 GA->setName(MangledName); 2307 } 2308 2309 // Set attributes which are particular to an alias; this is a 2310 // specialization of the attributes which may be set on a global 2311 // variable/function. 2312 if (D->hasAttr<DLLExportAttr>()) { 2313 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 2314 // The dllexport attribute is ignored for undefined symbols. 2315 if (FD->hasBody()) 2316 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 2317 } else { 2318 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 2319 } 2320 } else if (D->hasAttr<WeakAttr>() || 2321 D->hasAttr<WeakRefAttr>() || 2322 D->isWeakImported()) { 2323 GA->setLinkage(llvm::Function::WeakAnyLinkage); 2324 } 2325 2326 SetCommonAttributes(D, GA); 2327 } 2328 2329 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 2330 ArrayRef<llvm::Type*> Tys) { 2331 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 2332 Tys); 2333 } 2334 2335 static llvm::StringMapEntry<llvm::Constant*> & 2336 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2337 const StringLiteral *Literal, 2338 bool TargetIsLSB, 2339 bool &IsUTF16, 2340 unsigned &StringLength) { 2341 StringRef String = Literal->getString(); 2342 unsigned NumBytes = String.size(); 2343 2344 // Check for simple case. 2345 if (!Literal->containsNonAsciiOrNull()) { 2346 StringLength = NumBytes; 2347 return Map.GetOrCreateValue(String); 2348 } 2349 2350 // Otherwise, convert the UTF8 literals into a string of shorts. 2351 IsUTF16 = true; 2352 2353 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 2354 const UTF8 *FromPtr = (const UTF8 *)String.data(); 2355 UTF16 *ToPtr = &ToBuf[0]; 2356 2357 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2358 &ToPtr, ToPtr + NumBytes, 2359 strictConversion); 2360 2361 // ConvertUTF8toUTF16 returns the length in ToPtr. 2362 StringLength = ToPtr - &ToBuf[0]; 2363 2364 // Add an explicit null. 2365 *ToPtr = 0; 2366 return Map. 2367 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()), 2368 (StringLength + 1) * 2)); 2369 } 2370 2371 static llvm::StringMapEntry<llvm::Constant*> & 2372 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2373 const StringLiteral *Literal, 2374 unsigned &StringLength) { 2375 StringRef String = Literal->getString(); 2376 StringLength = String.size(); 2377 return Map.GetOrCreateValue(String); 2378 } 2379 2380 llvm::Constant * 2381 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2382 unsigned StringLength = 0; 2383 bool isUTF16 = false; 2384 llvm::StringMapEntry<llvm::Constant*> &Entry = 2385 GetConstantCFStringEntry(CFConstantStringMap, Literal, 2386 getDataLayout().isLittleEndian(), 2387 isUTF16, StringLength); 2388 2389 if (llvm::Constant *C = Entry.getValue()) 2390 return C; 2391 2392 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2393 llvm::Constant *Zeros[] = { Zero, Zero }; 2394 llvm::Value *V; 2395 2396 // If we don't already have it, get __CFConstantStringClassReference. 2397 if (!CFConstantStringClassRef) { 2398 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2399 Ty = llvm::ArrayType::get(Ty, 0); 2400 llvm::Constant *GV = CreateRuntimeVariable(Ty, 2401 "__CFConstantStringClassReference"); 2402 // Decay array -> ptr 2403 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2404 CFConstantStringClassRef = V; 2405 } 2406 else 2407 V = CFConstantStringClassRef; 2408 2409 QualType CFTy = getContext().getCFConstantStringType(); 2410 2411 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2412 2413 llvm::Constant *Fields[4]; 2414 2415 // Class pointer. 2416 Fields[0] = cast<llvm::ConstantExpr>(V); 2417 2418 // Flags. 2419 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2420 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2421 llvm::ConstantInt::get(Ty, 0x07C8); 2422 2423 // String pointer. 2424 llvm::Constant *C = 0; 2425 if (isUTF16) { 2426 ArrayRef<uint16_t> Arr = 2427 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>( 2428 const_cast<char *>(Entry.getKey().data())), 2429 Entry.getKey().size() / 2); 2430 C = llvm::ConstantDataArray::get(VMContext, Arr); 2431 } else { 2432 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2433 } 2434 2435 // Note: -fwritable-strings doesn't make the backing store strings of 2436 // CFStrings writable. (See <rdar://problem/10657500>) 2437 auto *GV = 2438 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 2439 llvm::GlobalValue::PrivateLinkage, C, ".str"); 2440 GV->setUnnamedAddr(true); 2441 // Don't enforce the target's minimum global alignment, since the only use 2442 // of the string is via this class initializer. 2443 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without 2444 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing 2445 // that changes the section it ends in, which surprises ld64. 2446 if (isUTF16) { 2447 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2448 GV->setAlignment(Align.getQuantity()); 2449 GV->setSection("__TEXT,__ustring"); 2450 } else { 2451 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2452 GV->setAlignment(Align.getQuantity()); 2453 GV->setSection("__TEXT,__cstring,cstring_literals"); 2454 } 2455 2456 // String. 2457 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2458 2459 if (isUTF16) 2460 // Cast the UTF16 string to the correct type. 2461 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2462 2463 // String length. 2464 Ty = getTypes().ConvertType(getContext().LongTy); 2465 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2466 2467 // The struct. 2468 C = llvm::ConstantStruct::get(STy, Fields); 2469 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2470 llvm::GlobalVariable::PrivateLinkage, C, 2471 "_unnamed_cfstring_"); 2472 GV->setSection("__DATA,__cfstring"); 2473 Entry.setValue(GV); 2474 2475 return GV; 2476 } 2477 2478 llvm::Constant * 2479 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2480 unsigned StringLength = 0; 2481 llvm::StringMapEntry<llvm::Constant*> &Entry = 2482 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2483 2484 if (llvm::Constant *C = Entry.getValue()) 2485 return C; 2486 2487 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2488 llvm::Constant *Zeros[] = { Zero, Zero }; 2489 llvm::Value *V; 2490 // If we don't already have it, get _NSConstantStringClassReference. 2491 if (!ConstantStringClassRef) { 2492 std::string StringClass(getLangOpts().ObjCConstantStringClass); 2493 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2494 llvm::Constant *GV; 2495 if (LangOpts.ObjCRuntime.isNonFragile()) { 2496 std::string str = 2497 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2498 : "OBJC_CLASS_$_" + StringClass; 2499 GV = getObjCRuntime().GetClassGlobal(str); 2500 // Make sure the result is of the correct type. 2501 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2502 V = llvm::ConstantExpr::getBitCast(GV, PTy); 2503 ConstantStringClassRef = V; 2504 } else { 2505 std::string str = 2506 StringClass.empty() ? "_NSConstantStringClassReference" 2507 : "_" + StringClass + "ClassReference"; 2508 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 2509 GV = CreateRuntimeVariable(PTy, str); 2510 // Decay array -> ptr 2511 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2512 ConstantStringClassRef = V; 2513 } 2514 } 2515 else 2516 V = ConstantStringClassRef; 2517 2518 if (!NSConstantStringType) { 2519 // Construct the type for a constant NSString. 2520 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString"); 2521 D->startDefinition(); 2522 2523 QualType FieldTypes[3]; 2524 2525 // const int *isa; 2526 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 2527 // const char *str; 2528 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 2529 // unsigned int length; 2530 FieldTypes[2] = Context.UnsignedIntTy; 2531 2532 // Create fields 2533 for (unsigned i = 0; i < 3; ++i) { 2534 FieldDecl *Field = FieldDecl::Create(Context, D, 2535 SourceLocation(), 2536 SourceLocation(), 0, 2537 FieldTypes[i], /*TInfo=*/0, 2538 /*BitWidth=*/0, 2539 /*Mutable=*/false, 2540 ICIS_NoInit); 2541 Field->setAccess(AS_public); 2542 D->addDecl(Field); 2543 } 2544 2545 D->completeDefinition(); 2546 QualType NSTy = Context.getTagDeclType(D); 2547 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 2548 } 2549 2550 llvm::Constant *Fields[3]; 2551 2552 // Class pointer. 2553 Fields[0] = cast<llvm::ConstantExpr>(V); 2554 2555 // String pointer. 2556 llvm::Constant *C = 2557 llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 2558 2559 llvm::GlobalValue::LinkageTypes Linkage; 2560 bool isConstant; 2561 Linkage = llvm::GlobalValue::PrivateLinkage; 2562 isConstant = !LangOpts.WritableStrings; 2563 2564 auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant, 2565 Linkage, C, ".str"); 2566 GV->setUnnamedAddr(true); 2567 // Don't enforce the target's minimum global alignment, since the only use 2568 // of the string is via this class initializer. 2569 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 2570 GV->setAlignment(Align.getQuantity()); 2571 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2572 2573 // String length. 2574 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2575 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 2576 2577 // The struct. 2578 C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 2579 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2580 llvm::GlobalVariable::PrivateLinkage, C, 2581 "_unnamed_nsstring_"); 2582 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip"; 2583 const char *NSStringNonFragileABISection = 2584 "__DATA,__objc_stringobj,regular,no_dead_strip"; 2585 // FIXME. Fix section. 2586 GV->setSection(LangOpts.ObjCRuntime.isNonFragile() 2587 ? NSStringNonFragileABISection 2588 : NSStringSection); 2589 Entry.setValue(GV); 2590 2591 return GV; 2592 } 2593 2594 QualType CodeGenModule::getObjCFastEnumerationStateType() { 2595 if (ObjCFastEnumerationStateType.isNull()) { 2596 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 2597 D->startDefinition(); 2598 2599 QualType FieldTypes[] = { 2600 Context.UnsignedLongTy, 2601 Context.getPointerType(Context.getObjCIdType()), 2602 Context.getPointerType(Context.UnsignedLongTy), 2603 Context.getConstantArrayType(Context.UnsignedLongTy, 2604 llvm::APInt(32, 5), ArrayType::Normal, 0) 2605 }; 2606 2607 for (size_t i = 0; i < 4; ++i) { 2608 FieldDecl *Field = FieldDecl::Create(Context, 2609 D, 2610 SourceLocation(), 2611 SourceLocation(), 0, 2612 FieldTypes[i], /*TInfo=*/0, 2613 /*BitWidth=*/0, 2614 /*Mutable=*/false, 2615 ICIS_NoInit); 2616 Field->setAccess(AS_public); 2617 D->addDecl(Field); 2618 } 2619 2620 D->completeDefinition(); 2621 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 2622 } 2623 2624 return ObjCFastEnumerationStateType; 2625 } 2626 2627 llvm::Constant * 2628 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 2629 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 2630 2631 // Don't emit it as the address of the string, emit the string data itself 2632 // as an inline array. 2633 if (E->getCharByteWidth() == 1) { 2634 SmallString<64> Str(E->getString()); 2635 2636 // Resize the string to the right size, which is indicated by its type. 2637 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 2638 Str.resize(CAT->getSize().getZExtValue()); 2639 return llvm::ConstantDataArray::getString(VMContext, Str, false); 2640 } 2641 2642 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 2643 llvm::Type *ElemTy = AType->getElementType(); 2644 unsigned NumElements = AType->getNumElements(); 2645 2646 // Wide strings have either 2-byte or 4-byte elements. 2647 if (ElemTy->getPrimitiveSizeInBits() == 16) { 2648 SmallVector<uint16_t, 32> Elements; 2649 Elements.reserve(NumElements); 2650 2651 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2652 Elements.push_back(E->getCodeUnit(i)); 2653 Elements.resize(NumElements); 2654 return llvm::ConstantDataArray::get(VMContext, Elements); 2655 } 2656 2657 assert(ElemTy->getPrimitiveSizeInBits() == 32); 2658 SmallVector<uint32_t, 32> Elements; 2659 Elements.reserve(NumElements); 2660 2661 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2662 Elements.push_back(E->getCodeUnit(i)); 2663 Elements.resize(NumElements); 2664 return llvm::ConstantDataArray::get(VMContext, Elements); 2665 } 2666 2667 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 2668 /// constant array for the given string literal. 2669 llvm::Constant * 2670 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 2671 CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType()); 2672 2673 llvm::StringMapEntry<llvm::GlobalVariable *> *Entry = nullptr; 2674 llvm::GlobalVariable *GV = nullptr; 2675 if (!LangOpts.WritableStrings) { 2676 llvm::StringMap<llvm::GlobalVariable *> *ConstantStringMap = nullptr; 2677 switch (S->getCharByteWidth()) { 2678 case 1: 2679 ConstantStringMap = &Constant1ByteStringMap; 2680 break; 2681 case 2: 2682 ConstantStringMap = &Constant2ByteStringMap; 2683 break; 2684 case 4: 2685 ConstantStringMap = &Constant4ByteStringMap; 2686 break; 2687 default: 2688 llvm_unreachable("unhandled byte width!"); 2689 } 2690 Entry = &ConstantStringMap->GetOrCreateValue(S->getBytes()); 2691 GV = Entry->getValue(); 2692 } 2693 2694 if (!GV) { 2695 SmallString<256> MangledNameBuffer; 2696 StringRef GlobalVariableName; 2697 llvm::GlobalValue::LinkageTypes LT; 2698 2699 // Mangle the string literal if the ABI allows for it. However, we cannot 2700 // do this if we are compiling with ASan or -fwritable-strings because they 2701 // rely on strings having normal linkage. 2702 if (!LangOpts.WritableStrings && !SanOpts.Address && 2703 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 2704 llvm::raw_svector_ostream Out(MangledNameBuffer); 2705 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 2706 Out.flush(); 2707 2708 LT = llvm::GlobalValue::LinkOnceODRLinkage; 2709 GlobalVariableName = MangledNameBuffer; 2710 } else { 2711 LT = llvm::GlobalValue::PrivateLinkage; 2712 GlobalVariableName = ".str"; 2713 } 2714 2715 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 2716 unsigned AddrSpace = 0; 2717 if (getLangOpts().OpenCL) 2718 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant); 2719 2720 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 2721 GV = new llvm::GlobalVariable( 2722 getModule(), C->getType(), !LangOpts.WritableStrings, LT, C, 2723 GlobalVariableName, /*InsertBefore=*/nullptr, 2724 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 2725 GV->setUnnamedAddr(true); 2726 if (Entry) 2727 Entry->setValue(GV); 2728 } 2729 2730 if (Align.getQuantity() > GV->getAlignment()) 2731 GV->setAlignment(Align.getQuantity()); 2732 2733 return GV; 2734 } 2735 2736 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 2737 /// array for the given ObjCEncodeExpr node. 2738 llvm::Constant * 2739 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 2740 std::string Str; 2741 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 2742 2743 return GetAddrOfConstantCString(Str); 2744 } 2745 2746 2747 /// GenerateWritableString -- Creates storage for a string literal. 2748 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str, 2749 bool constant, 2750 CodeGenModule &CGM, 2751 const char *GlobalName, 2752 unsigned Alignment) { 2753 // Create Constant for this string literal. Don't add a '\0'. 2754 llvm::Constant *C = 2755 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false); 2756 2757 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 2758 unsigned AddrSpace = 0; 2759 if (CGM.getLangOpts().OpenCL) 2760 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 2761 2762 // Create a global variable for this string 2763 auto *GV = new llvm::GlobalVariable( 2764 CGM.getModule(), C->getType(), constant, 2765 llvm::GlobalValue::PrivateLinkage, C, GlobalName, 0, 2766 llvm::GlobalVariable::NotThreadLocal, AddrSpace); 2767 GV->setAlignment(Alignment); 2768 GV->setUnnamedAddr(true); 2769 return GV; 2770 } 2771 2772 /// GetAddrOfConstantString - Returns a pointer to a character array 2773 /// containing the literal. This contents are exactly that of the 2774 /// given string, i.e. it will not be null terminated automatically; 2775 /// see GetAddrOfConstantCString. Note that whether the result is 2776 /// actually a pointer to an LLVM constant depends on 2777 /// Feature.WriteableStrings. 2778 /// 2779 /// The result has pointer to array type. 2780 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str, 2781 const char *GlobalName, 2782 unsigned Alignment) { 2783 // Get the default prefix if a name wasn't specified. 2784 if (!GlobalName) 2785 GlobalName = ".str"; 2786 2787 if (Alignment == 0) 2788 Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy) 2789 .getQuantity(); 2790 2791 // Don't share any string literals if strings aren't constant. 2792 if (LangOpts.WritableStrings) 2793 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment); 2794 2795 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2796 Constant1ByteStringMap.GetOrCreateValue(Str); 2797 2798 if (llvm::GlobalVariable *GV = Entry.getValue()) { 2799 if (Alignment > GV->getAlignment()) { 2800 GV->setAlignment(Alignment); 2801 } 2802 return GV; 2803 } 2804 2805 // Create a global variable for this. 2806 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, 2807 Alignment); 2808 Entry.setValue(GV); 2809 return GV; 2810 } 2811 2812 /// GetAddrOfConstantCString - Returns a pointer to a character 2813 /// array containing the literal and a terminating '\0' 2814 /// character. The result has pointer to array type. 2815 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str, 2816 const char *GlobalName, 2817 unsigned Alignment) { 2818 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 2819 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment); 2820 } 2821 2822 llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary( 2823 const MaterializeTemporaryExpr *E, const Expr *Init) { 2824 assert((E->getStorageDuration() == SD_Static || 2825 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 2826 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 2827 2828 // If we're not materializing a subobject of the temporary, keep the 2829 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 2830 QualType MaterializedType = Init->getType(); 2831 if (Init == E->GetTemporaryExpr()) 2832 MaterializedType = E->getType(); 2833 2834 llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E]; 2835 if (Slot) 2836 return Slot; 2837 2838 // FIXME: If an externally-visible declaration extends multiple temporaries, 2839 // we need to give each temporary the same name in every translation unit (and 2840 // we also need to make the temporaries externally-visible). 2841 SmallString<256> Name; 2842 llvm::raw_svector_ostream Out(Name); 2843 getCXXABI().getMangleContext().mangleReferenceTemporary( 2844 VD, E->getManglingNumber(), Out); 2845 Out.flush(); 2846 2847 APValue *Value = 0; 2848 if (E->getStorageDuration() == SD_Static) { 2849 // We might have a cached constant initializer for this temporary. Note 2850 // that this might have a different value from the value computed by 2851 // evaluating the initializer if the surrounding constant expression 2852 // modifies the temporary. 2853 Value = getContext().getMaterializedTemporaryValue(E, false); 2854 if (Value && Value->isUninit()) 2855 Value = 0; 2856 } 2857 2858 // Try evaluating it now, it might have a constant initializer. 2859 Expr::EvalResult EvalResult; 2860 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 2861 !EvalResult.hasSideEffects()) 2862 Value = &EvalResult.Val; 2863 2864 llvm::Constant *InitialValue = 0; 2865 bool Constant = false; 2866 llvm::Type *Type; 2867 if (Value) { 2868 // The temporary has a constant initializer, use it. 2869 InitialValue = EmitConstantValue(*Value, MaterializedType, 0); 2870 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 2871 Type = InitialValue->getType(); 2872 } else { 2873 // No initializer, the initialization will be provided when we 2874 // initialize the declaration which performed lifetime extension. 2875 Type = getTypes().ConvertTypeForMem(MaterializedType); 2876 } 2877 2878 // Create a global variable for this lifetime-extended temporary. 2879 llvm::GlobalValue::LinkageTypes Linkage = 2880 getLLVMLinkageVarDefinition(VD, Constant); 2881 // There is no need for this temporary to have global linkage if the global 2882 // variable has external linkage. 2883 if (Linkage == llvm::GlobalVariable::ExternalLinkage) 2884 Linkage = llvm::GlobalVariable::PrivateLinkage; 2885 unsigned AddrSpace = GetGlobalVarAddressSpace( 2886 VD, getContext().getTargetAddressSpace(MaterializedType)); 2887 auto *GV = new llvm::GlobalVariable( 2888 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 2889 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 2890 AddrSpace); 2891 setGlobalVisibility(GV, VD); 2892 GV->setAlignment( 2893 getContext().getTypeAlignInChars(MaterializedType).getQuantity()); 2894 if (VD->getTLSKind()) 2895 setTLSMode(GV, *VD); 2896 Slot = GV; 2897 return GV; 2898 } 2899 2900 /// EmitObjCPropertyImplementations - Emit information for synthesized 2901 /// properties for an implementation. 2902 void CodeGenModule::EmitObjCPropertyImplementations(const 2903 ObjCImplementationDecl *D) { 2904 for (const auto *PID : D->property_impls()) { 2905 // Dynamic is just for type-checking. 2906 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 2907 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2908 2909 // Determine which methods need to be implemented, some may have 2910 // been overridden. Note that ::isPropertyAccessor is not the method 2911 // we want, that just indicates if the decl came from a 2912 // property. What we want to know is if the method is defined in 2913 // this implementation. 2914 if (!D->getInstanceMethod(PD->getGetterName())) 2915 CodeGenFunction(*this).GenerateObjCGetter( 2916 const_cast<ObjCImplementationDecl *>(D), PID); 2917 if (!PD->isReadOnly() && 2918 !D->getInstanceMethod(PD->getSetterName())) 2919 CodeGenFunction(*this).GenerateObjCSetter( 2920 const_cast<ObjCImplementationDecl *>(D), PID); 2921 } 2922 } 2923 } 2924 2925 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 2926 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 2927 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 2928 ivar; ivar = ivar->getNextIvar()) 2929 if (ivar->getType().isDestructedType()) 2930 return true; 2931 2932 return false; 2933 } 2934 2935 /// EmitObjCIvarInitializations - Emit information for ivar initialization 2936 /// for an implementation. 2937 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 2938 // We might need a .cxx_destruct even if we don't have any ivar initializers. 2939 if (needsDestructMethod(D)) { 2940 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 2941 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2942 ObjCMethodDecl *DTORMethod = 2943 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 2944 cxxSelector, getContext().VoidTy, 0, D, 2945 /*isInstance=*/true, /*isVariadic=*/false, 2946 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 2947 /*isDefined=*/false, ObjCMethodDecl::Required); 2948 D->addInstanceMethod(DTORMethod); 2949 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 2950 D->setHasDestructors(true); 2951 } 2952 2953 // If the implementation doesn't have any ivar initializers, we don't need 2954 // a .cxx_construct. 2955 if (D->getNumIvarInitializers() == 0) 2956 return; 2957 2958 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 2959 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 2960 // The constructor returns 'self'. 2961 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 2962 D->getLocation(), 2963 D->getLocation(), 2964 cxxSelector, 2965 getContext().getObjCIdType(), 0, 2966 D, /*isInstance=*/true, 2967 /*isVariadic=*/false, 2968 /*isPropertyAccessor=*/true, 2969 /*isImplicitlyDeclared=*/true, 2970 /*isDefined=*/false, 2971 ObjCMethodDecl::Required); 2972 D->addInstanceMethod(CTORMethod); 2973 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 2974 D->setHasNonZeroConstructors(true); 2975 } 2976 2977 /// EmitNamespace - Emit all declarations in a namespace. 2978 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 2979 for (auto *I : ND->decls()) { 2980 if (const auto *VD = dyn_cast<VarDecl>(I)) 2981 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 2982 VD->getTemplateSpecializationKind() != TSK_Undeclared) 2983 continue; 2984 EmitTopLevelDecl(I); 2985 } 2986 } 2987 2988 // EmitLinkageSpec - Emit all declarations in a linkage spec. 2989 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 2990 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 2991 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 2992 ErrorUnsupported(LSD, "linkage spec"); 2993 return; 2994 } 2995 2996 for (auto *I : LSD->decls()) { 2997 // Meta-data for ObjC class includes references to implemented methods. 2998 // Generate class's method definitions first. 2999 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 3000 for (auto *M : OID->methods()) 3001 EmitTopLevelDecl(M); 3002 } 3003 EmitTopLevelDecl(I); 3004 } 3005 } 3006 3007 /// EmitTopLevelDecl - Emit code for a single top level declaration. 3008 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3009 // Ignore dependent declarations. 3010 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3011 return; 3012 3013 switch (D->getKind()) { 3014 case Decl::CXXConversion: 3015 case Decl::CXXMethod: 3016 case Decl::Function: 3017 // Skip function templates 3018 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 3019 cast<FunctionDecl>(D)->isLateTemplateParsed()) 3020 return; 3021 3022 EmitGlobal(cast<FunctionDecl>(D)); 3023 break; 3024 3025 case Decl::Var: 3026 // Skip variable templates 3027 if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3028 return; 3029 case Decl::VarTemplateSpecialization: 3030 EmitGlobal(cast<VarDecl>(D)); 3031 break; 3032 3033 // Indirect fields from global anonymous structs and unions can be 3034 // ignored; only the actual variable requires IR gen support. 3035 case Decl::IndirectField: 3036 break; 3037 3038 // C++ Decls 3039 case Decl::Namespace: 3040 EmitNamespace(cast<NamespaceDecl>(D)); 3041 break; 3042 // No code generation needed. 3043 case Decl::UsingShadow: 3044 case Decl::ClassTemplate: 3045 case Decl::VarTemplate: 3046 case Decl::VarTemplatePartialSpecialization: 3047 case Decl::FunctionTemplate: 3048 case Decl::TypeAliasTemplate: 3049 case Decl::Block: 3050 case Decl::Empty: 3051 break; 3052 case Decl::Using: // using X; [C++] 3053 if (CGDebugInfo *DI = getModuleDebugInfo()) 3054 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 3055 return; 3056 case Decl::NamespaceAlias: 3057 if (CGDebugInfo *DI = getModuleDebugInfo()) 3058 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3059 return; 3060 case Decl::UsingDirective: // using namespace X; [C++] 3061 if (CGDebugInfo *DI = getModuleDebugInfo()) 3062 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3063 return; 3064 case Decl::CXXConstructor: 3065 // Skip function templates 3066 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 3067 cast<FunctionDecl>(D)->isLateTemplateParsed()) 3068 return; 3069 3070 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3071 break; 3072 case Decl::CXXDestructor: 3073 if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 3074 return; 3075 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3076 break; 3077 3078 case Decl::StaticAssert: 3079 // Nothing to do. 3080 break; 3081 3082 // Objective-C Decls 3083 3084 // Forward declarations, no (immediate) code generation. 3085 case Decl::ObjCInterface: 3086 case Decl::ObjCCategory: 3087 break; 3088 3089 case Decl::ObjCProtocol: { 3090 auto *Proto = cast<ObjCProtocolDecl>(D); 3091 if (Proto->isThisDeclarationADefinition()) 3092 ObjCRuntime->GenerateProtocol(Proto); 3093 break; 3094 } 3095 3096 case Decl::ObjCCategoryImpl: 3097 // Categories have properties but don't support synthesize so we 3098 // can ignore them here. 3099 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3100 break; 3101 3102 case Decl::ObjCImplementation: { 3103 auto *OMD = cast<ObjCImplementationDecl>(D); 3104 EmitObjCPropertyImplementations(OMD); 3105 EmitObjCIvarInitializations(OMD); 3106 ObjCRuntime->GenerateClass(OMD); 3107 // Emit global variable debug information. 3108 if (CGDebugInfo *DI = getModuleDebugInfo()) 3109 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 3110 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3111 OMD->getClassInterface()), OMD->getLocation()); 3112 break; 3113 } 3114 case Decl::ObjCMethod: { 3115 auto *OMD = cast<ObjCMethodDecl>(D); 3116 // If this is not a prototype, emit the body. 3117 if (OMD->getBody()) 3118 CodeGenFunction(*this).GenerateObjCMethod(OMD); 3119 break; 3120 } 3121 case Decl::ObjCCompatibleAlias: 3122 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3123 break; 3124 3125 case Decl::LinkageSpec: 3126 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3127 break; 3128 3129 case Decl::FileScopeAsm: { 3130 auto *AD = cast<FileScopeAsmDecl>(D); 3131 StringRef AsmString = AD->getAsmString()->getString(); 3132 3133 const std::string &S = getModule().getModuleInlineAsm(); 3134 if (S.empty()) 3135 getModule().setModuleInlineAsm(AsmString); 3136 else if (S.end()[-1] == '\n') 3137 getModule().setModuleInlineAsm(S + AsmString.str()); 3138 else 3139 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 3140 break; 3141 } 3142 3143 case Decl::Import: { 3144 auto *Import = cast<ImportDecl>(D); 3145 3146 // Ignore import declarations that come from imported modules. 3147 if (clang::Module *Owner = Import->getOwningModule()) { 3148 if (getLangOpts().CurrentModule.empty() || 3149 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule) 3150 break; 3151 } 3152 3153 ImportedModules.insert(Import->getImportedModule()); 3154 break; 3155 } 3156 3157 case Decl::ClassTemplateSpecialization: { 3158 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 3159 if (DebugInfo && 3160 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition) 3161 DebugInfo->completeTemplateDefinition(*Spec); 3162 } 3163 3164 default: 3165 // Make sure we handled everything we should, every other kind is a 3166 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 3167 // function. Need to recode Decl::Kind to do that easily. 3168 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 3169 } 3170 } 3171 3172 /// Turns the given pointer into a constant. 3173 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 3174 const void *Ptr) { 3175 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 3176 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 3177 return llvm::ConstantInt::get(i64, PtrInt); 3178 } 3179 3180 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 3181 llvm::NamedMDNode *&GlobalMetadata, 3182 GlobalDecl D, 3183 llvm::GlobalValue *Addr) { 3184 if (!GlobalMetadata) 3185 GlobalMetadata = 3186 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 3187 3188 // TODO: should we report variant information for ctors/dtors? 3189 llvm::Value *Ops[] = { 3190 Addr, 3191 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 3192 }; 3193 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 3194 } 3195 3196 /// For each function which is declared within an extern "C" region and marked 3197 /// as 'used', but has internal linkage, create an alias from the unmangled 3198 /// name to the mangled name if possible. People expect to be able to refer 3199 /// to such functions with an unmangled name from inline assembly within the 3200 /// same translation unit. 3201 void CodeGenModule::EmitStaticExternCAliases() { 3202 for (StaticExternCMap::iterator I = StaticExternCValues.begin(), 3203 E = StaticExternCValues.end(); 3204 I != E; ++I) { 3205 IdentifierInfo *Name = I->first; 3206 llvm::GlobalValue *Val = I->second; 3207 if (Val && !getModule().getNamedValue(Name->getName())) 3208 addUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(), 3209 Name->getName(), Val, &getModule())); 3210 } 3211 } 3212 3213 /// Emits metadata nodes associating all the global values in the 3214 /// current module with the Decls they came from. This is useful for 3215 /// projects using IR gen as a subroutine. 3216 /// 3217 /// Since there's currently no way to associate an MDNode directly 3218 /// with an llvm::GlobalValue, we create a global named metadata 3219 /// with the name 'clang.global.decl.ptrs'. 3220 void CodeGenModule::EmitDeclMetadata() { 3221 llvm::NamedMDNode *GlobalMetadata = 0; 3222 3223 // StaticLocalDeclMap 3224 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator 3225 I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 3226 I != E; ++I) { 3227 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 3228 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 3229 } 3230 } 3231 3232 /// Emits metadata nodes for all the local variables in the current 3233 /// function. 3234 void CodeGenFunction::EmitDeclMetadata() { 3235 if (LocalDeclMap.empty()) return; 3236 3237 llvm::LLVMContext &Context = getLLVMContext(); 3238 3239 // Find the unique metadata ID for this name. 3240 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 3241 3242 llvm::NamedMDNode *GlobalMetadata = 0; 3243 3244 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 3245 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 3246 const Decl *D = I->first; 3247 llvm::Value *Addr = I->second; 3248 3249 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 3250 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 3251 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr)); 3252 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 3253 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 3254 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 3255 } 3256 } 3257 } 3258 3259 void CodeGenModule::EmitVersionIdentMetadata() { 3260 llvm::NamedMDNode *IdentMetadata = 3261 TheModule.getOrInsertNamedMetadata("llvm.ident"); 3262 std::string Version = getClangFullVersion(); 3263 llvm::LLVMContext &Ctx = TheModule.getContext(); 3264 3265 llvm::Value *IdentNode[] = { 3266 llvm::MDString::get(Ctx, Version) 3267 }; 3268 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 3269 } 3270 3271 void CodeGenModule::EmitCoverageFile() { 3272 if (!getCodeGenOpts().CoverageFile.empty()) { 3273 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 3274 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 3275 llvm::LLVMContext &Ctx = TheModule.getContext(); 3276 llvm::MDString *CoverageFile = 3277 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 3278 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 3279 llvm::MDNode *CU = CUNode->getOperand(i); 3280 llvm::Value *node[] = { CoverageFile, CU }; 3281 llvm::MDNode *N = llvm::MDNode::get(Ctx, node); 3282 GCov->addOperand(N); 3283 } 3284 } 3285 } 3286 } 3287 3288 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid, 3289 QualType GuidType) { 3290 // Sema has checked that all uuid strings are of the form 3291 // "12345678-1234-1234-1234-1234567890ab". 3292 assert(Uuid.size() == 36); 3293 for (unsigned i = 0; i < 36; ++i) { 3294 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 3295 else assert(isHexDigit(Uuid[i])); 3296 } 3297 3298 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 3299 3300 llvm::Constant *Field3[8]; 3301 for (unsigned Idx = 0; Idx < 8; ++Idx) 3302 Field3[Idx] = llvm::ConstantInt::get( 3303 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 3304 3305 llvm::Constant *Fields[4] = { 3306 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 3307 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 3308 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 3309 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 3310 }; 3311 3312 return llvm::ConstantStruct::getAnon(Fields); 3313 } 3314