1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This coordinates the per-module state used while generating code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CodeGenModule.h" 14 #include "CGBlocks.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 "CGOpenMPRuntimeGPU.h" 23 #include "CodeGenFunction.h" 24 #include "CodeGenPGO.h" 25 #include "ConstantEmitter.h" 26 #include "CoverageMappingGen.h" 27 #include "TargetInfo.h" 28 #include "clang/AST/ASTContext.h" 29 #include "clang/AST/CharUnits.h" 30 #include "clang/AST/DeclCXX.h" 31 #include "clang/AST/DeclObjC.h" 32 #include "clang/AST/DeclTemplate.h" 33 #include "clang/AST/Mangle.h" 34 #include "clang/AST/RecordLayout.h" 35 #include "clang/AST/RecursiveASTVisitor.h" 36 #include "clang/AST/StmtVisitor.h" 37 #include "clang/Basic/Builtins.h" 38 #include "clang/Basic/CharInfo.h" 39 #include "clang/Basic/CodeGenOptions.h" 40 #include "clang/Basic/Diagnostic.h" 41 #include "clang/Basic/FileManager.h" 42 #include "clang/Basic/Module.h" 43 #include "clang/Basic/SourceManager.h" 44 #include "clang/Basic/TargetInfo.h" 45 #include "clang/Basic/Version.h" 46 #include "clang/CodeGen/ConstantInitBuilder.h" 47 #include "clang/Frontend/FrontendDiagnostic.h" 48 #include "llvm/ADT/StringSwitch.h" 49 #include "llvm/ADT/Triple.h" 50 #include "llvm/Analysis/TargetLibraryInfo.h" 51 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 52 #include "llvm/IR/CallingConv.h" 53 #include "llvm/IR/DataLayout.h" 54 #include "llvm/IR/Intrinsics.h" 55 #include "llvm/IR/LLVMContext.h" 56 #include "llvm/IR/Module.h" 57 #include "llvm/IR/ProfileSummary.h" 58 #include "llvm/ProfileData/InstrProfReader.h" 59 #include "llvm/Support/CodeGen.h" 60 #include "llvm/Support/CommandLine.h" 61 #include "llvm/Support/ConvertUTF.h" 62 #include "llvm/Support/ErrorHandling.h" 63 #include "llvm/Support/MD5.h" 64 #include "llvm/Support/TimeProfiler.h" 65 #include "llvm/Support/X86TargetParser.h" 66 67 using namespace clang; 68 using namespace CodeGen; 69 70 static llvm::cl::opt<bool> LimitedCoverage( 71 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden, 72 llvm::cl::desc("Emit limited coverage mapping information (experimental)"), 73 llvm::cl::init(false)); 74 75 static const char AnnotationSection[] = "llvm.metadata"; 76 77 static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 78 switch (CGM.getContext().getCXXABIKind()) { 79 case TargetCXXABI::AppleARM64: 80 case TargetCXXABI::Fuchsia: 81 case TargetCXXABI::GenericAArch64: 82 case TargetCXXABI::GenericARM: 83 case TargetCXXABI::iOS: 84 case TargetCXXABI::WatchOS: 85 case TargetCXXABI::GenericMIPS: 86 case TargetCXXABI::GenericItanium: 87 case TargetCXXABI::WebAssembly: 88 case TargetCXXABI::XL: 89 return CreateItaniumCXXABI(CGM); 90 case TargetCXXABI::Microsoft: 91 return CreateMicrosoftCXXABI(CGM); 92 } 93 94 llvm_unreachable("invalid C++ ABI kind"); 95 } 96 97 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, 98 const PreprocessorOptions &PPO, 99 const CodeGenOptions &CGO, llvm::Module &M, 100 DiagnosticsEngine &diags, 101 CoverageSourceInfo *CoverageInfo) 102 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), 103 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 104 Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 105 VMContext(M.getContext()), Types(*this), VTables(*this), 106 SanitizerMD(new SanitizerMetadata(*this)) { 107 108 // Initialize the type cache. 109 llvm::LLVMContext &LLVMContext = M.getContext(); 110 VoidTy = llvm::Type::getVoidTy(LLVMContext); 111 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 112 Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 113 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 114 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 115 HalfTy = llvm::Type::getHalfTy(LLVMContext); 116 BFloatTy = llvm::Type::getBFloatTy(LLVMContext); 117 FloatTy = llvm::Type::getFloatTy(LLVMContext); 118 DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 119 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 120 PointerAlignInBytes = 121 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 122 SizeSizeInBytes = 123 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 124 IntAlignInBytes = 125 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 126 CharTy = 127 llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth()); 128 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 129 IntPtrTy = llvm::IntegerType::get(LLVMContext, 130 C.getTargetInfo().getMaxPointerWidth()); 131 Int8PtrTy = Int8Ty->getPointerTo(0); 132 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 133 const llvm::DataLayout &DL = M.getDataLayout(); 134 AllocaInt8PtrTy = Int8Ty->getPointerTo(DL.getAllocaAddrSpace()); 135 GlobalsInt8PtrTy = Int8Ty->getPointerTo(DL.getDefaultGlobalsAddressSpace()); 136 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 137 138 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 139 140 if (LangOpts.ObjC) 141 createObjCRuntime(); 142 if (LangOpts.OpenCL) 143 createOpenCLRuntime(); 144 if (LangOpts.OpenMP) 145 createOpenMPRuntime(); 146 if (LangOpts.CUDA) 147 createCUDARuntime(); 148 149 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 150 if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 151 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 152 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), 153 getCXXABI().getMangleContext())); 154 155 // If debug info or coverage generation is enabled, create the CGDebugInfo 156 // object. 157 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 158 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 159 DebugInfo.reset(new CGDebugInfo(*this)); 160 161 Block.GlobalUniqueCount = 0; 162 163 if (C.getLangOpts().ObjC) 164 ObjCData.reset(new ObjCEntrypoints()); 165 166 if (CodeGenOpts.hasProfileClangUse()) { 167 auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 168 CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile); 169 if (auto E = ReaderOrErr.takeError()) { 170 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 171 "Could not read profile %0: %1"); 172 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 173 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath 174 << EI.message(); 175 }); 176 } else 177 PGOReader = std::move(ReaderOrErr.get()); 178 } 179 180 // If coverage mapping generation is enabled, create the 181 // CoverageMappingModuleGen object. 182 if (CodeGenOpts.CoverageMapping) 183 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 184 185 // Generate the module name hash here if needed. 186 if (CodeGenOpts.UniqueInternalLinkageNames && 187 !getModule().getSourceFileName().empty()) { 188 std::string Path = getModule().getSourceFileName(); 189 // Check if a path substitution is needed from the MacroPrefixMap. 190 for (const auto &Entry : LangOpts.MacroPrefixMap) 191 if (Path.rfind(Entry.first, 0) != std::string::npos) { 192 Path = Entry.second + Path.substr(Entry.first.size()); 193 break; 194 } 195 llvm::MD5 Md5; 196 Md5.update(Path); 197 llvm::MD5::MD5Result R; 198 Md5.final(R); 199 SmallString<32> Str; 200 llvm::MD5::stringifyResult(R, Str); 201 // Convert MD5hash to Decimal. Demangler suffixes can either contain 202 // numbers or characters but not both. 203 llvm::APInt IntHash(128, Str.str(), 16); 204 // Prepend "__uniq" before the hash for tools like profilers to understand 205 // that this symbol is of internal linkage type. The "__uniq" is the 206 // pre-determined prefix that is used to tell tools that this symbol was 207 // created with -funique-internal-linakge-symbols and the tools can strip or 208 // keep the prefix as needed. 209 ModuleNameHash = (Twine(".__uniq.") + 210 Twine(toString(IntHash, /* Radix = */ 10, /* Signed = */false))).str(); 211 } 212 } 213 214 CodeGenModule::~CodeGenModule() {} 215 216 void CodeGenModule::createObjCRuntime() { 217 // This is just isGNUFamily(), but we want to force implementors of 218 // new ABIs to decide how best to do this. 219 switch (LangOpts.ObjCRuntime.getKind()) { 220 case ObjCRuntime::GNUstep: 221 case ObjCRuntime::GCC: 222 case ObjCRuntime::ObjFW: 223 ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 224 return; 225 226 case ObjCRuntime::FragileMacOSX: 227 case ObjCRuntime::MacOSX: 228 case ObjCRuntime::iOS: 229 case ObjCRuntime::WatchOS: 230 ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 231 return; 232 } 233 llvm_unreachable("bad runtime kind"); 234 } 235 236 void CodeGenModule::createOpenCLRuntime() { 237 OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 238 } 239 240 void CodeGenModule::createOpenMPRuntime() { 241 // Select a specialized code generation class based on the target, if any. 242 // If it does not exist use the default implementation. 243 switch (getTriple().getArch()) { 244 case llvm::Triple::nvptx: 245 case llvm::Triple::nvptx64: 246 case llvm::Triple::amdgcn: 247 assert(getLangOpts().OpenMPIsDevice && 248 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code."); 249 OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this)); 250 break; 251 default: 252 if (LangOpts.OpenMPSimd) 253 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); 254 else 255 OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 256 break; 257 } 258 } 259 260 void CodeGenModule::createCUDARuntime() { 261 CUDARuntime.reset(CreateNVCUDARuntime(*this)); 262 } 263 264 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 265 Replacements[Name] = C; 266 } 267 268 void CodeGenModule::applyReplacements() { 269 for (auto &I : Replacements) { 270 StringRef MangledName = I.first(); 271 llvm::Constant *Replacement = I.second; 272 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 273 if (!Entry) 274 continue; 275 auto *OldF = cast<llvm::Function>(Entry); 276 auto *NewF = dyn_cast<llvm::Function>(Replacement); 277 if (!NewF) { 278 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 279 NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 280 } else { 281 auto *CE = cast<llvm::ConstantExpr>(Replacement); 282 assert(CE->getOpcode() == llvm::Instruction::BitCast || 283 CE->getOpcode() == llvm::Instruction::GetElementPtr); 284 NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 285 } 286 } 287 288 // Replace old with new, but keep the old order. 289 OldF->replaceAllUsesWith(Replacement); 290 if (NewF) { 291 NewF->removeFromParent(); 292 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 293 NewF); 294 } 295 OldF->eraseFromParent(); 296 } 297 } 298 299 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 300 GlobalValReplacements.push_back(std::make_pair(GV, C)); 301 } 302 303 void CodeGenModule::applyGlobalValReplacements() { 304 for (auto &I : GlobalValReplacements) { 305 llvm::GlobalValue *GV = I.first; 306 llvm::Constant *C = I.second; 307 308 GV->replaceAllUsesWith(C); 309 GV->eraseFromParent(); 310 } 311 } 312 313 // This is only used in aliases that we created and we know they have a 314 // linear structure. 315 static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) { 316 const llvm::Constant *C; 317 if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV)) 318 C = GA->getAliasee(); 319 else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV)) 320 C = GI->getResolver(); 321 else 322 return GV; 323 324 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts()); 325 if (!AliaseeGV) 326 return nullptr; 327 328 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject(); 329 if (FinalGV == GV) 330 return nullptr; 331 332 return FinalGV; 333 } 334 335 static bool checkAliasedGlobal(DiagnosticsEngine &Diags, 336 SourceLocation Location, bool IsIFunc, 337 const llvm::GlobalValue *Alias, 338 const llvm::GlobalValue *&GV) { 339 GV = getAliasedGlobal(Alias); 340 if (!GV) { 341 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 342 return false; 343 } 344 345 if (GV->isDeclaration()) { 346 Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc; 347 return false; 348 } 349 350 if (IsIFunc) { 351 // Check resolver function type. 352 const auto *F = dyn_cast<llvm::Function>(GV); 353 if (!F) { 354 Diags.Report(Location, diag::err_alias_to_undefined) 355 << IsIFunc << IsIFunc; 356 return false; 357 } 358 359 llvm::FunctionType *FTy = F->getFunctionType(); 360 if (!FTy->getReturnType()->isPointerTy()) { 361 Diags.Report(Location, diag::err_ifunc_resolver_return); 362 return false; 363 } 364 } 365 366 return true; 367 } 368 369 void CodeGenModule::checkAliases() { 370 // Check if the constructed aliases are well formed. It is really unfortunate 371 // that we have to do this in CodeGen, but we only construct mangled names 372 // and aliases during codegen. 373 bool Error = false; 374 DiagnosticsEngine &Diags = getDiags(); 375 for (const GlobalDecl &GD : Aliases) { 376 const auto *D = cast<ValueDecl>(GD.getDecl()); 377 SourceLocation Location; 378 bool IsIFunc = D->hasAttr<IFuncAttr>(); 379 if (const Attr *A = D->getDefiningAttr()) 380 Location = A->getLocation(); 381 else 382 llvm_unreachable("Not an alias or ifunc?"); 383 384 StringRef MangledName = getMangledName(GD); 385 llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 386 const llvm::GlobalValue *GV = nullptr; 387 if (!checkAliasedGlobal(Diags, Location, IsIFunc, Alias, GV)) { 388 Error = true; 389 continue; 390 } 391 392 llvm::Constant *Aliasee = 393 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver() 394 : cast<llvm::GlobalAlias>(Alias)->getAliasee(); 395 396 llvm::GlobalValue *AliaseeGV; 397 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 398 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 399 else 400 AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 401 402 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 403 StringRef AliasSection = SA->getName(); 404 if (AliasSection != AliaseeGV->getSection()) 405 Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 406 << AliasSection << IsIFunc << IsIFunc; 407 } 408 409 // We have to handle alias to weak aliases in here. LLVM itself disallows 410 // this since the object semantics would not match the IL one. For 411 // compatibility with gcc we implement it by just pointing the alias 412 // to its aliasee's aliasee. We also warn, since the user is probably 413 // expecting the link to be weak. 414 if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 415 if (GA->isInterposable()) { 416 Diags.Report(Location, diag::warn_alias_to_weak_alias) 417 << GV->getName() << GA->getName() << IsIFunc; 418 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 419 GA->getAliasee(), Alias->getType()); 420 421 if (IsIFunc) 422 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee); 423 else 424 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee); 425 } 426 } 427 } 428 if (!Error) 429 return; 430 431 for (const GlobalDecl &GD : Aliases) { 432 StringRef MangledName = getMangledName(GD); 433 llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 434 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 435 Alias->eraseFromParent(); 436 } 437 } 438 439 void CodeGenModule::clear() { 440 DeferredDeclsToEmit.clear(); 441 if (OpenMPRuntime) 442 OpenMPRuntime->clear(); 443 } 444 445 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 446 StringRef MainFile) { 447 if (!hasDiagnostics()) 448 return; 449 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 450 if (MainFile.empty()) 451 MainFile = "<stdin>"; 452 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 453 } else { 454 if (Mismatched > 0) 455 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 456 457 if (Missing > 0) 458 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 459 } 460 } 461 462 static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, 463 llvm::Module &M) { 464 if (!LO.VisibilityFromDLLStorageClass) 465 return; 466 467 llvm::GlobalValue::VisibilityTypes DLLExportVisibility = 468 CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility()); 469 llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility = 470 CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility()); 471 llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility = 472 CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility()); 473 llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility = 474 CodeGenModule::GetLLVMVisibility( 475 LO.getExternDeclNoDLLStorageClassVisibility()); 476 477 for (llvm::GlobalValue &GV : M.global_values()) { 478 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage()) 479 continue; 480 481 // Reset DSO locality before setting the visibility. This removes 482 // any effects that visibility options and annotations may have 483 // had on the DSO locality. Setting the visibility will implicitly set 484 // appropriate globals to DSO Local; however, this will be pessimistic 485 // w.r.t. to the normal compiler IRGen. 486 GV.setDSOLocal(false); 487 488 if (GV.isDeclarationForLinker()) { 489 GV.setVisibility(GV.getDLLStorageClass() == 490 llvm::GlobalValue::DLLImportStorageClass 491 ? ExternDeclDLLImportVisibility 492 : ExternDeclNoDLLStorageClassVisibility); 493 } else { 494 GV.setVisibility(GV.getDLLStorageClass() == 495 llvm::GlobalValue::DLLExportStorageClass 496 ? DLLExportVisibility 497 : NoDLLStorageClassVisibility); 498 } 499 500 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 501 } 502 } 503 504 void CodeGenModule::Release() { 505 EmitDeferred(); 506 EmitVTablesOpportunistically(); 507 applyGlobalValReplacements(); 508 applyReplacements(); 509 checkAliases(); 510 emitMultiVersionFunctions(); 511 EmitCXXGlobalInitFunc(); 512 EmitCXXGlobalCleanUpFunc(); 513 registerGlobalDtorsWithAtExit(); 514 EmitCXXThreadLocalInitFunc(); 515 if (ObjCRuntime) 516 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 517 AddGlobalCtor(ObjCInitFunction); 518 if (Context.getLangOpts().CUDA && CUDARuntime) { 519 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule()) 520 AddGlobalCtor(CudaCtorFunction); 521 } 522 if (OpenMPRuntime) { 523 if (llvm::Function *OpenMPRequiresDirectiveRegFun = 524 OpenMPRuntime->emitRequiresDirectiveRegFun()) { 525 AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0); 526 } 527 OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); 528 OpenMPRuntime->clear(); 529 } 530 if (PGOReader) { 531 getModule().setProfileSummary( 532 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext), 533 llvm::ProfileSummary::PSK_Instr); 534 if (PGOStats.hasDiagnostics()) 535 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 536 } 537 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 538 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 539 EmitGlobalAnnotations(); 540 EmitStaticExternCAliases(); 541 EmitDeferredUnusedCoverageMappings(); 542 CodeGenPGO(*this).setValueProfilingFlag(getModule()); 543 if (CoverageMapping) 544 CoverageMapping->emit(); 545 if (CodeGenOpts.SanitizeCfiCrossDso) { 546 CodeGenFunction(*this).EmitCfiCheckFail(); 547 CodeGenFunction(*this).EmitCfiCheckStub(); 548 } 549 emitAtAvailableLinkGuard(); 550 if (Context.getTargetInfo().getTriple().isWasm() && 551 !Context.getTargetInfo().getTriple().isOSEmscripten()) { 552 EmitMainVoidAlias(); 553 } 554 555 // Emit reference of __amdgpu_device_library_preserve_asan_functions to 556 // preserve ASAN functions in bitcode libraries. 557 if (LangOpts.Sanitize.has(SanitizerKind::Address) && getTriple().isAMDGPU()) { 558 auto *FT = llvm::FunctionType::get(VoidTy, {}); 559 auto *F = llvm::Function::Create( 560 FT, llvm::GlobalValue::ExternalLinkage, 561 "__amdgpu_device_library_preserve_asan_functions", &getModule()); 562 auto *Var = new llvm::GlobalVariable( 563 getModule(), FT->getPointerTo(), 564 /*isConstant=*/true, llvm::GlobalValue::WeakAnyLinkage, F, 565 "__amdgpu_device_library_preserve_asan_functions_ptr", nullptr, 566 llvm::GlobalVariable::NotThreadLocal); 567 addCompilerUsedGlobal(Var); 568 getModule().addModuleFlag(llvm::Module::Override, "amdgpu_hostcall", 1); 569 } 570 571 emitLLVMUsed(); 572 if (SanStats) 573 SanStats->finish(); 574 575 if (CodeGenOpts.Autolink && 576 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 577 EmitModuleLinkOptions(); 578 } 579 580 // On ELF we pass the dependent library specifiers directly to the linker 581 // without manipulating them. This is in contrast to other platforms where 582 // they are mapped to a specific linker option by the compiler. This 583 // difference is a result of the greater variety of ELF linkers and the fact 584 // that ELF linkers tend to handle libraries in a more complicated fashion 585 // than on other platforms. This forces us to defer handling the dependent 586 // libs to the linker. 587 // 588 // CUDA/HIP device and host libraries are different. Currently there is no 589 // way to differentiate dependent libraries for host or device. Existing 590 // usage of #pragma comment(lib, *) is intended for host libraries on 591 // Windows. Therefore emit llvm.dependent-libraries only for host. 592 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { 593 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries"); 594 for (auto *MD : ELFDependentLibraries) 595 NMD->addOperand(MD); 596 } 597 598 // Record mregparm value now so it is visible through rest of codegen. 599 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 600 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 601 CodeGenOpts.NumRegisterParameters); 602 603 if (CodeGenOpts.DwarfVersion) { 604 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version", 605 CodeGenOpts.DwarfVersion); 606 } 607 608 if (CodeGenOpts.Dwarf64) 609 getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1); 610 611 if (Context.getLangOpts().SemanticInterposition) 612 // Require various optimization to respect semantic interposition. 613 getModule().setSemanticInterposition(1); 614 615 if (CodeGenOpts.EmitCodeView) { 616 // Indicate that we want CodeView in the metadata. 617 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 618 } 619 if (CodeGenOpts.CodeViewGHash) { 620 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1); 621 } 622 if (CodeGenOpts.ControlFlowGuard) { 623 // Function ID tables and checks for Control Flow Guard (cfguard=2). 624 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2); 625 } else if (CodeGenOpts.ControlFlowGuardNoChecks) { 626 // Function ID tables for Control Flow Guard (cfguard=1). 627 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1); 628 } 629 if (CodeGenOpts.EHContGuard) { 630 // Function ID tables for EH Continuation Guard. 631 getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1); 632 } 633 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 634 // We don't support LTO with 2 with different StrictVTablePointers 635 // FIXME: we could support it by stripping all the information introduced 636 // by StrictVTablePointers. 637 638 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 639 640 llvm::Metadata *Ops[2] = { 641 llvm::MDString::get(VMContext, "StrictVTablePointers"), 642 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 643 llvm::Type::getInt32Ty(VMContext), 1))}; 644 645 getModule().addModuleFlag(llvm::Module::Require, 646 "StrictVTablePointersRequirement", 647 llvm::MDNode::get(VMContext, Ops)); 648 } 649 if (getModuleDebugInfo()) 650 // We support a single version in the linked module. The LLVM 651 // parser will drop debug info with a different version number 652 // (and warn about it, too). 653 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 654 llvm::DEBUG_METADATA_VERSION); 655 656 // We need to record the widths of enums and wchar_t, so that we can generate 657 // the correct build attributes in the ARM backend. wchar_size is also used by 658 // TargetLibraryInfo. 659 uint64_t WCharWidth = 660 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 661 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 662 663 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 664 if ( Arch == llvm::Triple::arm 665 || Arch == llvm::Triple::armeb 666 || Arch == llvm::Triple::thumb 667 || Arch == llvm::Triple::thumbeb) { 668 // The minimum width of an enum in bytes 669 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 670 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 671 } 672 673 if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) { 674 StringRef ABIStr = Target.getABI(); 675 llvm::LLVMContext &Ctx = TheModule.getContext(); 676 getModule().addModuleFlag(llvm::Module::Error, "target-abi", 677 llvm::MDString::get(Ctx, ABIStr)); 678 } 679 680 if (CodeGenOpts.SanitizeCfiCrossDso) { 681 // Indicate that we want cross-DSO control flow integrity checks. 682 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 683 } 684 685 if (CodeGenOpts.WholeProgramVTables) { 686 // Indicate whether VFE was enabled for this module, so that the 687 // vcall_visibility metadata added under whole program vtables is handled 688 // appropriately in the optimizer. 689 getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim", 690 CodeGenOpts.VirtualFunctionElimination); 691 } 692 693 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) { 694 getModule().addModuleFlag(llvm::Module::Override, 695 "CFI Canonical Jump Tables", 696 CodeGenOpts.SanitizeCfiCanonicalJumpTables); 697 } 698 699 if (CodeGenOpts.CFProtectionReturn && 700 Target.checkCFProtectionReturnSupported(getDiags())) { 701 // Indicate that we want to instrument return control flow protection. 702 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return", 703 1); 704 } 705 706 if (CodeGenOpts.CFProtectionBranch && 707 Target.checkCFProtectionBranchSupported(getDiags())) { 708 // Indicate that we want to instrument branch control flow protection. 709 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch", 710 1); 711 } 712 713 // Add module metadata for return address signing (ignoring 714 // non-leaf/all) and stack tagging. These are actually turned on by function 715 // attributes, but we use module metadata to emit build attributes. This is 716 // needed for LTO, where the function attributes are inside bitcode 717 // serialised into a global variable by the time build attributes are 718 // emitted, so we can't access them. 719 if (Context.getTargetInfo().hasFeature("ptrauth") && 720 LangOpts.getSignReturnAddressScope() != 721 LangOptions::SignReturnAddressScopeKind::None) 722 getModule().addModuleFlag(llvm::Module::Override, 723 "sign-return-address-buildattr", 1); 724 if (LangOpts.Sanitize.has(SanitizerKind::MemTag)) 725 getModule().addModuleFlag(llvm::Module::Override, 726 "tag-stack-memory-buildattr", 1); 727 728 if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb || 729 Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 || 730 Arch == llvm::Triple::aarch64_be) { 731 getModule().addModuleFlag(llvm::Module::Error, "branch-target-enforcement", 732 LangOpts.BranchTargetEnforcement); 733 734 getModule().addModuleFlag(llvm::Module::Error, "sign-return-address", 735 LangOpts.hasSignReturnAddress()); 736 737 getModule().addModuleFlag(llvm::Module::Error, "sign-return-address-all", 738 LangOpts.isSignReturnAddressScopeAll()); 739 740 if (Arch != llvm::Triple::thumb && Arch != llvm::Triple::thumbeb) { 741 getModule().addModuleFlag(llvm::Module::Error, 742 "sign-return-address-with-bkey", 743 !LangOpts.isSignReturnAddressWithAKey()); 744 } 745 } 746 747 if (!CodeGenOpts.MemoryProfileOutput.empty()) { 748 llvm::LLVMContext &Ctx = TheModule.getContext(); 749 getModule().addModuleFlag( 750 llvm::Module::Error, "MemProfProfileFilename", 751 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput)); 752 } 753 754 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 755 // Indicate whether __nvvm_reflect should be configured to flush denormal 756 // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 757 // property.) 758 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 759 CodeGenOpts.FP32DenormalMode.Output != 760 llvm::DenormalMode::IEEE); 761 } 762 763 if (LangOpts.EHAsynch) 764 getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1); 765 766 // Indicate whether this Module was compiled with -fopenmp 767 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 768 getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP); 769 if (getLangOpts().OpenMPIsDevice) 770 getModule().addModuleFlag(llvm::Module::Max, "openmp-device", 771 LangOpts.OpenMP); 772 773 // Emit OpenCL specific module metadata: OpenCL/SPIR version. 774 if (LangOpts.OpenCL) { 775 EmitOpenCLMetadata(); 776 // Emit SPIR version. 777 if (getTriple().isSPIR()) { 778 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the 779 // opencl.spir.version named metadata. 780 // C++ for OpenCL has a distinct mapping for version compatibility with 781 // OpenCL. 782 auto Version = LangOpts.getOpenCLCompatibleVersion(); 783 llvm::Metadata *SPIRVerElts[] = { 784 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 785 Int32Ty, Version / 100)), 786 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 787 Int32Ty, (Version / 100 > 1) ? 0 : 2))}; 788 llvm::NamedMDNode *SPIRVerMD = 789 TheModule.getOrInsertNamedMetadata("opencl.spir.version"); 790 llvm::LLVMContext &Ctx = TheModule.getContext(); 791 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); 792 } 793 } 794 795 if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 796 assert(PLevel < 3 && "Invalid PIC Level"); 797 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 798 if (Context.getLangOpts().PIE) 799 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 800 } 801 802 if (getCodeGenOpts().CodeModel.size() > 0) { 803 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) 804 .Case("tiny", llvm::CodeModel::Tiny) 805 .Case("small", llvm::CodeModel::Small) 806 .Case("kernel", llvm::CodeModel::Kernel) 807 .Case("medium", llvm::CodeModel::Medium) 808 .Case("large", llvm::CodeModel::Large) 809 .Default(~0u); 810 if (CM != ~0u) { 811 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); 812 getModule().setCodeModel(codeModel); 813 } 814 } 815 816 if (CodeGenOpts.NoPLT) 817 getModule().setRtLibUseGOT(); 818 if (CodeGenOpts.UnwindTables) 819 getModule().setUwtable(); 820 821 switch (CodeGenOpts.getFramePointer()) { 822 case CodeGenOptions::FramePointerKind::None: 823 // 0 ("none") is the default. 824 break; 825 case CodeGenOptions::FramePointerKind::NonLeaf: 826 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf); 827 break; 828 case CodeGenOptions::FramePointerKind::All: 829 getModule().setFramePointer(llvm::FramePointerKind::All); 830 break; 831 } 832 833 SimplifyPersonality(); 834 835 if (getCodeGenOpts().EmitDeclMetadata) 836 EmitDeclMetadata(); 837 838 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 839 EmitCoverageFile(); 840 841 if (CGDebugInfo *DI = getModuleDebugInfo()) 842 DI->finalize(); 843 844 if (getCodeGenOpts().EmitVersionIdentMetadata) 845 EmitVersionIdentMetadata(); 846 847 if (!getCodeGenOpts().RecordCommandLine.empty()) 848 EmitCommandLineMetadata(); 849 850 if (!getCodeGenOpts().StackProtectorGuard.empty()) 851 getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard); 852 if (!getCodeGenOpts().StackProtectorGuardReg.empty()) 853 getModule().setStackProtectorGuardReg( 854 getCodeGenOpts().StackProtectorGuardReg); 855 if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX) 856 getModule().setStackProtectorGuardOffset( 857 getCodeGenOpts().StackProtectorGuardOffset); 858 if (getCodeGenOpts().StackAlignment) 859 getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment); 860 if (getCodeGenOpts().SkipRaxSetup) 861 getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1); 862 863 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames); 864 865 EmitBackendOptionsMetadata(getCodeGenOpts()); 866 867 // Set visibility from DLL storage class 868 // We do this at the end of LLVM IR generation; after any operation 869 // that might affect the DLL storage class or the visibility, and 870 // before anything that might act on these. 871 setVisibilityFromDLLStorageClass(LangOpts, getModule()); 872 } 873 874 void CodeGenModule::EmitOpenCLMetadata() { 875 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the 876 // opencl.ocl.version named metadata node. 877 // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL. 878 auto Version = LangOpts.getOpenCLCompatibleVersion(); 879 llvm::Metadata *OCLVerElts[] = { 880 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 881 Int32Ty, Version / 100)), 882 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 883 Int32Ty, (Version % 100) / 10))}; 884 llvm::NamedMDNode *OCLVerMD = 885 TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); 886 llvm::LLVMContext &Ctx = TheModule.getContext(); 887 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); 888 } 889 890 void CodeGenModule::EmitBackendOptionsMetadata( 891 const CodeGenOptions CodeGenOpts) { 892 switch (getTriple().getArch()) { 893 default: 894 break; 895 case llvm::Triple::riscv32: 896 case llvm::Triple::riscv64: 897 getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit", 898 CodeGenOpts.SmallDataLimit); 899 break; 900 } 901 } 902 903 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 904 // Make sure that this type is translated. 905 Types.UpdateCompletedType(TD); 906 } 907 908 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 909 // Make sure that this type is translated. 910 Types.RefreshTypeCacheForClass(RD); 911 } 912 913 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { 914 if (!TBAA) 915 return nullptr; 916 return TBAA->getTypeInfo(QTy); 917 } 918 919 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { 920 if (!TBAA) 921 return TBAAAccessInfo(); 922 if (getLangOpts().CUDAIsDevice) { 923 // As CUDA builtin surface/texture types are replaced, skip generating TBAA 924 // access info. 925 if (AccessType->isCUDADeviceBuiltinSurfaceType()) { 926 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() != 927 nullptr) 928 return TBAAAccessInfo(); 929 } else if (AccessType->isCUDADeviceBuiltinTextureType()) { 930 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() != 931 nullptr) 932 return TBAAAccessInfo(); 933 } 934 } 935 return TBAA->getAccessInfo(AccessType); 936 } 937 938 TBAAAccessInfo 939 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { 940 if (!TBAA) 941 return TBAAAccessInfo(); 942 return TBAA->getVTablePtrAccessInfo(VTablePtrType); 943 } 944 945 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 946 if (!TBAA) 947 return nullptr; 948 return TBAA->getTBAAStructInfo(QTy); 949 } 950 951 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { 952 if (!TBAA) 953 return nullptr; 954 return TBAA->getBaseTypeInfo(QTy); 955 } 956 957 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { 958 if (!TBAA) 959 return nullptr; 960 return TBAA->getAccessTagInfo(Info); 961 } 962 963 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 964 TBAAAccessInfo TargetInfo) { 965 if (!TBAA) 966 return TBAAAccessInfo(); 967 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); 968 } 969 970 TBAAAccessInfo 971 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 972 TBAAAccessInfo InfoB) { 973 if (!TBAA) 974 return TBAAAccessInfo(); 975 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); 976 } 977 978 TBAAAccessInfo 979 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 980 TBAAAccessInfo SrcInfo) { 981 if (!TBAA) 982 return TBAAAccessInfo(); 983 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo); 984 } 985 986 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 987 TBAAAccessInfo TBAAInfo) { 988 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) 989 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); 990 } 991 992 void CodeGenModule::DecorateInstructionWithInvariantGroup( 993 llvm::Instruction *I, const CXXRecordDecl *RD) { 994 I->setMetadata(llvm::LLVMContext::MD_invariant_group, 995 llvm::MDNode::get(getLLVMContext(), {})); 996 } 997 998 void CodeGenModule::Error(SourceLocation loc, StringRef message) { 999 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 1000 getDiags().Report(Context.getFullLoc(loc), diagID) << message; 1001 } 1002 1003 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1004 /// specified stmt yet. 1005 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 1006 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1007 "cannot compile this %0 yet"); 1008 std::string Msg = Type; 1009 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID) 1010 << Msg << S->getSourceRange(); 1011 } 1012 1013 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1014 /// specified decl yet. 1015 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 1016 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1017 "cannot compile this %0 yet"); 1018 std::string Msg = Type; 1019 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 1020 } 1021 1022 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 1023 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 1024 } 1025 1026 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 1027 const NamedDecl *D) const { 1028 if (GV->hasDLLImportStorageClass()) 1029 return; 1030 // Internal definitions always have default visibility. 1031 if (GV->hasLocalLinkage()) { 1032 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1033 return; 1034 } 1035 if (!D) 1036 return; 1037 // Set visibility for definitions, and for declarations if requested globally 1038 // or set explicitly. 1039 LinkageInfo LV = D->getLinkageAndVisibility(); 1040 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || 1041 !GV->isDeclarationForLinker()) 1042 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 1043 } 1044 1045 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, 1046 llvm::GlobalValue *GV) { 1047 if (GV->hasLocalLinkage()) 1048 return true; 1049 1050 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) 1051 return true; 1052 1053 // DLLImport explicitly marks the GV as external. 1054 if (GV->hasDLLImportStorageClass()) 1055 return false; 1056 1057 const llvm::Triple &TT = CGM.getTriple(); 1058 if (TT.isWindowsGNUEnvironment()) { 1059 // In MinGW, variables without DLLImport can still be automatically 1060 // imported from a DLL by the linker; don't mark variables that 1061 // potentially could come from another DLL as DSO local. 1062 1063 // With EmulatedTLS, TLS variables can be autoimported from other DLLs 1064 // (and this actually happens in the public interface of libstdc++), so 1065 // such variables can't be marked as DSO local. (Native TLS variables 1066 // can't be dllimported at all, though.) 1067 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) && 1068 (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS)) 1069 return false; 1070 } 1071 1072 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols 1073 // remain unresolved in the link, they can be resolved to zero, which is 1074 // outside the current DSO. 1075 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) 1076 return false; 1077 1078 // Every other GV is local on COFF. 1079 // Make an exception for windows OS in the triple: Some firmware builds use 1080 // *-win32-macho triples. This (accidentally?) produced windows relocations 1081 // without GOT tables in older clang versions; Keep this behaviour. 1082 // FIXME: even thread local variables? 1083 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) 1084 return true; 1085 1086 // Only handle COFF and ELF for now. 1087 if (!TT.isOSBinFormatELF()) 1088 return false; 1089 1090 // If this is not an executable, don't assume anything is local. 1091 const auto &CGOpts = CGM.getCodeGenOpts(); 1092 llvm::Reloc::Model RM = CGOpts.RelocationModel; 1093 const auto &LOpts = CGM.getLangOpts(); 1094 if (RM != llvm::Reloc::Static && !LOpts.PIE) { 1095 // On ELF, if -fno-semantic-interposition is specified and the target 1096 // supports local aliases, there will be neither CC1 1097 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set 1098 // dso_local on the function if using a local alias is preferable (can avoid 1099 // PLT indirection). 1100 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias())) 1101 return false; 1102 return !(CGM.getLangOpts().SemanticInterposition || 1103 CGM.getLangOpts().HalfNoSemanticInterposition); 1104 } 1105 1106 // A definition cannot be preempted from an executable. 1107 if (!GV->isDeclarationForLinker()) 1108 return true; 1109 1110 // Most PIC code sequences that assume that a symbol is local cannot produce a 1111 // 0 if it turns out the symbol is undefined. While this is ABI and relocation 1112 // depended, it seems worth it to handle it here. 1113 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) 1114 return false; 1115 1116 // PowerPC64 prefers TOC indirection to avoid copy relocations. 1117 if (TT.isPPC64()) 1118 return false; 1119 1120 if (CGOpts.DirectAccessExternalData) { 1121 // If -fdirect-access-external-data (default for -fno-pic), set dso_local 1122 // for non-thread-local variables. If the symbol is not defined in the 1123 // executable, a copy relocation will be needed at link time. dso_local is 1124 // excluded for thread-local variables because they generally don't support 1125 // copy relocations. 1126 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV)) 1127 if (!Var->isThreadLocal()) 1128 return true; 1129 1130 // -fno-pic sets dso_local on a function declaration to allow direct 1131 // accesses when taking its address (similar to a data symbol). If the 1132 // function is not defined in the executable, a canonical PLT entry will be 1133 // needed at link time. -fno-direct-access-external-data can avoid the 1134 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as 1135 // it could just cause trouble without providing perceptible benefits. 1136 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) 1137 return true; 1138 } 1139 1140 // If we can use copy relocations we can assume it is local. 1141 1142 // Otherwise don't assume it is local. 1143 return false; 1144 } 1145 1146 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { 1147 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV)); 1148 } 1149 1150 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1151 GlobalDecl GD) const { 1152 const auto *D = dyn_cast<NamedDecl>(GD.getDecl()); 1153 // C++ destructors have a few C++ ABI specific special cases. 1154 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) { 1155 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType()); 1156 return; 1157 } 1158 setDLLImportDLLExport(GV, D); 1159 } 1160 1161 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1162 const NamedDecl *D) const { 1163 if (D && D->isExternallyVisible()) { 1164 if (D->hasAttr<DLLImportAttr>()) 1165 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 1166 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker()) 1167 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 1168 } 1169 } 1170 1171 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1172 GlobalDecl GD) const { 1173 setDLLImportDLLExport(GV, GD); 1174 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl())); 1175 } 1176 1177 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1178 const NamedDecl *D) const { 1179 setDLLImportDLLExport(GV, D); 1180 setGVPropertiesAux(GV, D); 1181 } 1182 1183 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, 1184 const NamedDecl *D) const { 1185 setGlobalVisibility(GV, D); 1186 setDSOLocal(GV); 1187 GV->setPartition(CodeGenOpts.SymbolPartition); 1188 } 1189 1190 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 1191 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 1192 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 1193 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 1194 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 1195 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 1196 } 1197 1198 llvm::GlobalVariable::ThreadLocalMode 1199 CodeGenModule::GetDefaultLLVMTLSModel() const { 1200 switch (CodeGenOpts.getDefaultTLSModel()) { 1201 case CodeGenOptions::GeneralDynamicTLSModel: 1202 return llvm::GlobalVariable::GeneralDynamicTLSModel; 1203 case CodeGenOptions::LocalDynamicTLSModel: 1204 return llvm::GlobalVariable::LocalDynamicTLSModel; 1205 case CodeGenOptions::InitialExecTLSModel: 1206 return llvm::GlobalVariable::InitialExecTLSModel; 1207 case CodeGenOptions::LocalExecTLSModel: 1208 return llvm::GlobalVariable::LocalExecTLSModel; 1209 } 1210 llvm_unreachable("Invalid TLS model!"); 1211 } 1212 1213 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 1214 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 1215 1216 llvm::GlobalValue::ThreadLocalMode TLM; 1217 TLM = GetDefaultLLVMTLSModel(); 1218 1219 // Override the TLS model if it is explicitly specified. 1220 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 1221 TLM = GetLLVMTLSModel(Attr->getModel()); 1222 } 1223 1224 GV->setThreadLocalMode(TLM); 1225 } 1226 1227 static std::string getCPUSpecificMangling(const CodeGenModule &CGM, 1228 StringRef Name) { 1229 const TargetInfo &Target = CGM.getTarget(); 1230 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); 1231 } 1232 1233 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, 1234 const CPUSpecificAttr *Attr, 1235 unsigned CPUIndex, 1236 raw_ostream &Out) { 1237 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is 1238 // supported. 1239 if (Attr) 1240 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); 1241 else if (CGM.getTarget().supportsIFunc()) 1242 Out << ".resolver"; 1243 } 1244 1245 static void AppendTargetMangling(const CodeGenModule &CGM, 1246 const TargetAttr *Attr, raw_ostream &Out) { 1247 if (Attr->isDefaultVersion()) 1248 return; 1249 1250 Out << '.'; 1251 const TargetInfo &Target = CGM.getTarget(); 1252 ParsedTargetAttr Info = 1253 Attr->parse([&Target](StringRef LHS, StringRef RHS) { 1254 // Multiversioning doesn't allow "no-${feature}", so we can 1255 // only have "+" prefixes here. 1256 assert(LHS.startswith("+") && RHS.startswith("+") && 1257 "Features should always have a prefix."); 1258 return Target.multiVersionSortPriority(LHS.substr(1)) > 1259 Target.multiVersionSortPriority(RHS.substr(1)); 1260 }); 1261 1262 bool IsFirst = true; 1263 1264 if (!Info.Architecture.empty()) { 1265 IsFirst = false; 1266 Out << "arch_" << Info.Architecture; 1267 } 1268 1269 for (StringRef Feat : Info.Features) { 1270 if (!IsFirst) 1271 Out << '_'; 1272 IsFirst = false; 1273 Out << Feat.substr(1); 1274 } 1275 } 1276 1277 // Returns true if GD is a function decl with internal linkage and 1278 // needs a unique suffix after the mangled name. 1279 static bool isUniqueInternalLinkageDecl(GlobalDecl GD, 1280 CodeGenModule &CGM) { 1281 const Decl *D = GD.getDecl(); 1282 return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) && 1283 (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage); 1284 } 1285 1286 static void AppendTargetClonesMangling(const CodeGenModule &CGM, 1287 const TargetClonesAttr *Attr, 1288 unsigned VersionIndex, 1289 raw_ostream &Out) { 1290 Out << '.'; 1291 StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); 1292 if (FeatureStr.startswith("arch=")) 1293 Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1); 1294 else 1295 Out << FeatureStr; 1296 1297 Out << '.' << Attr->getMangledIndex(VersionIndex); 1298 } 1299 1300 static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, 1301 const NamedDecl *ND, 1302 bool OmitMultiVersionMangling = false) { 1303 SmallString<256> Buffer; 1304 llvm::raw_svector_ostream Out(Buffer); 1305 MangleContext &MC = CGM.getCXXABI().getMangleContext(); 1306 if (!CGM.getModuleNameHash().empty()) 1307 MC.needsUniqueInternalLinkageNames(); 1308 bool ShouldMangle = MC.shouldMangleDeclName(ND); 1309 if (ShouldMangle) 1310 MC.mangleName(GD.getWithDecl(ND), Out); 1311 else { 1312 IdentifierInfo *II = ND->getIdentifier(); 1313 assert(II && "Attempt to mangle unnamed decl."); 1314 const auto *FD = dyn_cast<FunctionDecl>(ND); 1315 1316 if (FD && 1317 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 1318 Out << "__regcall3__" << II->getName(); 1319 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() && 1320 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { 1321 Out << "__device_stub__" << II->getName(); 1322 } else { 1323 Out << II->getName(); 1324 } 1325 } 1326 1327 // Check if the module name hash should be appended for internal linkage 1328 // symbols. This should come before multi-version target suffixes are 1329 // appended. This is to keep the name and module hash suffix of the 1330 // internal linkage function together. The unique suffix should only be 1331 // added when name mangling is done to make sure that the final name can 1332 // be properly demangled. For example, for C functions without prototypes, 1333 // name mangling is not done and the unique suffix should not be appeneded 1334 // then. 1335 if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) { 1336 assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames && 1337 "Hash computed when not explicitly requested"); 1338 Out << CGM.getModuleNameHash(); 1339 } 1340 1341 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 1342 if (FD->isMultiVersion() && !OmitMultiVersionMangling) { 1343 switch (FD->getMultiVersionKind()) { 1344 case MultiVersionKind::CPUDispatch: 1345 case MultiVersionKind::CPUSpecific: 1346 AppendCPUSpecificCPUDispatchMangling(CGM, 1347 FD->getAttr<CPUSpecificAttr>(), 1348 GD.getMultiVersionIndex(), Out); 1349 break; 1350 case MultiVersionKind::Target: 1351 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); 1352 break; 1353 case MultiVersionKind::TargetClones: 1354 AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(), 1355 GD.getMultiVersionIndex(), Out); 1356 break; 1357 case MultiVersionKind::None: 1358 llvm_unreachable("None multiversion type isn't valid here"); 1359 } 1360 } 1361 1362 // Make unique name for device side static file-scope variable for HIP. 1363 if (CGM.getContext().shouldExternalizeStaticVar(ND) && 1364 CGM.getLangOpts().GPURelocatableDeviceCode && 1365 CGM.getLangOpts().CUDAIsDevice && !CGM.getLangOpts().CUID.empty()) 1366 CGM.printPostfixForExternalizedStaticVar(Out); 1367 return std::string(Out.str()); 1368 } 1369 1370 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, 1371 const FunctionDecl *FD) { 1372 if (!FD->isMultiVersion()) 1373 return; 1374 1375 // Get the name of what this would be without the 'target' attribute. This 1376 // allows us to lookup the version that was emitted when this wasn't a 1377 // multiversion function. 1378 std::string NonTargetName = 1379 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 1380 GlobalDecl OtherGD; 1381 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { 1382 assert(OtherGD.getCanonicalDecl() 1383 .getDecl() 1384 ->getAsFunction() 1385 ->isMultiVersion() && 1386 "Other GD should now be a multiversioned function"); 1387 // OtherFD is the version of this function that was mangled BEFORE 1388 // becoming a MultiVersion function. It potentially needs to be updated. 1389 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() 1390 .getDecl() 1391 ->getAsFunction() 1392 ->getMostRecentDecl(); 1393 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); 1394 // This is so that if the initial version was already the 'default' 1395 // version, we don't try to update it. 1396 if (OtherName != NonTargetName) { 1397 // Remove instead of erase, since others may have stored the StringRef 1398 // to this. 1399 const auto ExistingRecord = Manglings.find(NonTargetName); 1400 if (ExistingRecord != std::end(Manglings)) 1401 Manglings.remove(&(*ExistingRecord)); 1402 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD)); 1403 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first(); 1404 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) 1405 Entry->setName(OtherName); 1406 } 1407 } 1408 } 1409 1410 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 1411 GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 1412 1413 // Some ABIs don't have constructor variants. Make sure that base and 1414 // complete constructors get mangled the same. 1415 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 1416 if (!getTarget().getCXXABI().hasConstructorVariants()) { 1417 CXXCtorType OrigCtorType = GD.getCtorType(); 1418 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 1419 if (OrigCtorType == Ctor_Base) 1420 CanonicalGD = GlobalDecl(CD, Ctor_Complete); 1421 } 1422 } 1423 1424 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a 1425 // static device variable depends on whether the variable is referenced by 1426 // a host or device host function. Therefore the mangled name cannot be 1427 // cached. 1428 if (!LangOpts.CUDAIsDevice || 1429 !getContext().mayExternalizeStaticVar(GD.getDecl())) { 1430 auto FoundName = MangledDeclNames.find(CanonicalGD); 1431 if (FoundName != MangledDeclNames.end()) 1432 return FoundName->second; 1433 } 1434 1435 // Keep the first result in the case of a mangling collision. 1436 const auto *ND = cast<NamedDecl>(GD.getDecl()); 1437 std::string MangledName = getMangledNameImpl(*this, GD, ND); 1438 1439 // Ensure either we have different ABIs between host and device compilations, 1440 // says host compilation following MSVC ABI but device compilation follows 1441 // Itanium C++ ABI or, if they follow the same ABI, kernel names after 1442 // mangling should be the same after name stubbing. The later checking is 1443 // very important as the device kernel name being mangled in host-compilation 1444 // is used to resolve the device binaries to be executed. Inconsistent naming 1445 // result in undefined behavior. Even though we cannot check that naming 1446 // directly between host- and device-compilations, the host- and 1447 // device-mangling in host compilation could help catching certain ones. 1448 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || 1449 getLangOpts().CUDAIsDevice || 1450 (getContext().getAuxTargetInfo() && 1451 (getContext().getAuxTargetInfo()->getCXXABI() != 1452 getContext().getTargetInfo().getCXXABI())) || 1453 getCUDARuntime().getDeviceSideName(ND) == 1454 getMangledNameImpl( 1455 *this, 1456 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), 1457 ND)); 1458 1459 auto Result = Manglings.insert(std::make_pair(MangledName, GD)); 1460 return MangledDeclNames[CanonicalGD] = Result.first->first(); 1461 } 1462 1463 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 1464 const BlockDecl *BD) { 1465 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 1466 const Decl *D = GD.getDecl(); 1467 1468 SmallString<256> Buffer; 1469 llvm::raw_svector_ostream Out(Buffer); 1470 if (!D) 1471 MangleCtx.mangleGlobalBlock(BD, 1472 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 1473 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 1474 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 1475 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 1476 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 1477 else 1478 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 1479 1480 auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 1481 return Result.first->first(); 1482 } 1483 1484 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 1485 return getModule().getNamedValue(Name); 1486 } 1487 1488 /// AddGlobalCtor - Add a function to the list that will be called before 1489 /// main() runs. 1490 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 1491 llvm::Constant *AssociatedData) { 1492 // FIXME: Type coercion of void()* types. 1493 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 1494 } 1495 1496 /// AddGlobalDtor - Add a function to the list that will be called 1497 /// when the module is unloaded. 1498 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority, 1499 bool IsDtorAttrFunc) { 1500 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit && 1501 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) { 1502 DtorsUsingAtExit[Priority].push_back(Dtor); 1503 return; 1504 } 1505 1506 // FIXME: Type coercion of void()* types. 1507 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 1508 } 1509 1510 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 1511 if (Fns.empty()) return; 1512 1513 // Ctor function type is void()*. 1514 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 1515 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, 1516 TheModule.getDataLayout().getProgramAddressSpace()); 1517 1518 // Get the type of a ctor entry, { i32, void ()*, i8* }. 1519 llvm::StructType *CtorStructTy = llvm::StructType::get( 1520 Int32Ty, CtorPFTy, VoidPtrTy); 1521 1522 // Construct the constructor and destructor arrays. 1523 ConstantInitBuilder builder(*this); 1524 auto ctors = builder.beginArray(CtorStructTy); 1525 for (const auto &I : Fns) { 1526 auto ctor = ctors.beginStruct(CtorStructTy); 1527 ctor.addInt(Int32Ty, I.Priority); 1528 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 1529 if (I.AssociatedData) 1530 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 1531 else 1532 ctor.addNullPointer(VoidPtrTy); 1533 ctor.finishAndAddTo(ctors); 1534 } 1535 1536 auto list = 1537 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 1538 /*constant*/ false, 1539 llvm::GlobalValue::AppendingLinkage); 1540 1541 // The LTO linker doesn't seem to like it when we set an alignment 1542 // on appending variables. Take it off as a workaround. 1543 list->setAlignment(llvm::None); 1544 1545 Fns.clear(); 1546 } 1547 1548 llvm::GlobalValue::LinkageTypes 1549 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 1550 const auto *D = cast<FunctionDecl>(GD.getDecl()); 1551 1552 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 1553 1554 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D)) 1555 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType()); 1556 1557 if (isa<CXXConstructorDecl>(D) && 1558 cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 1559 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1560 // Our approach to inheriting constructors is fundamentally different from 1561 // that used by the MS ABI, so keep our inheriting constructor thunks 1562 // internal rather than trying to pick an unambiguous mangling for them. 1563 return llvm::GlobalValue::InternalLinkage; 1564 } 1565 1566 return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false); 1567 } 1568 1569 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 1570 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 1571 if (!MDS) return nullptr; 1572 1573 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 1574 } 1575 1576 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, 1577 const CGFunctionInfo &Info, 1578 llvm::Function *F, bool IsThunk) { 1579 unsigned CallingConv; 1580 llvm::AttributeList PAL; 1581 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, 1582 /*AttrOnCallSite=*/false, IsThunk); 1583 F->setAttributes(PAL); 1584 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 1585 } 1586 1587 static void removeImageAccessQualifier(std::string& TyName) { 1588 std::string ReadOnlyQual("__read_only"); 1589 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 1590 if (ReadOnlyPos != std::string::npos) 1591 // "+ 1" for the space after access qualifier. 1592 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 1593 else { 1594 std::string WriteOnlyQual("__write_only"); 1595 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 1596 if (WriteOnlyPos != std::string::npos) 1597 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 1598 else { 1599 std::string ReadWriteQual("__read_write"); 1600 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 1601 if (ReadWritePos != std::string::npos) 1602 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 1603 } 1604 } 1605 } 1606 1607 // Returns the address space id that should be produced to the 1608 // kernel_arg_addr_space metadata. This is always fixed to the ids 1609 // as specified in the SPIR 2.0 specification in order to differentiate 1610 // for example in clGetKernelArgInfo() implementation between the address 1611 // spaces with targets without unique mapping to the OpenCL address spaces 1612 // (basically all single AS CPUs). 1613 static unsigned ArgInfoAddressSpace(LangAS AS) { 1614 switch (AS) { 1615 case LangAS::opencl_global: 1616 return 1; 1617 case LangAS::opencl_constant: 1618 return 2; 1619 case LangAS::opencl_local: 1620 return 3; 1621 case LangAS::opencl_generic: 1622 return 4; // Not in SPIR 2.0 specs. 1623 case LangAS::opencl_global_device: 1624 return 5; 1625 case LangAS::opencl_global_host: 1626 return 6; 1627 default: 1628 return 0; // Assume private. 1629 } 1630 } 1631 1632 void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn, 1633 const FunctionDecl *FD, 1634 CodeGenFunction *CGF) { 1635 assert(((FD && CGF) || (!FD && !CGF)) && 1636 "Incorrect use - FD and CGF should either be both null or not!"); 1637 // Create MDNodes that represent the kernel arg metadata. 1638 // Each MDNode is a list in the form of "key", N number of values which is 1639 // the same number of values as their are kernel arguments. 1640 1641 const PrintingPolicy &Policy = Context.getPrintingPolicy(); 1642 1643 // MDNode for the kernel argument address space qualifiers. 1644 SmallVector<llvm::Metadata *, 8> addressQuals; 1645 1646 // MDNode for the kernel argument access qualifiers (images only). 1647 SmallVector<llvm::Metadata *, 8> accessQuals; 1648 1649 // MDNode for the kernel argument type names. 1650 SmallVector<llvm::Metadata *, 8> argTypeNames; 1651 1652 // MDNode for the kernel argument base type names. 1653 SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 1654 1655 // MDNode for the kernel argument type qualifiers. 1656 SmallVector<llvm::Metadata *, 8> argTypeQuals; 1657 1658 // MDNode for the kernel argument names. 1659 SmallVector<llvm::Metadata *, 8> argNames; 1660 1661 if (FD && CGF) 1662 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 1663 const ParmVarDecl *parm = FD->getParamDecl(i); 1664 QualType ty = parm->getType(); 1665 std::string typeQuals; 1666 1667 // Get image and pipe access qualifier: 1668 if (ty->isImageType() || ty->isPipeType()) { 1669 const Decl *PDecl = parm; 1670 if (auto *TD = dyn_cast<TypedefType>(ty)) 1671 PDecl = TD->getDecl(); 1672 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); 1673 if (A && A->isWriteOnly()) 1674 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only")); 1675 else if (A && A->isReadWrite()) 1676 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write")); 1677 else 1678 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only")); 1679 } else 1680 accessQuals.push_back(llvm::MDString::get(VMContext, "none")); 1681 1682 // Get argument name. 1683 argNames.push_back(llvm::MDString::get(VMContext, parm->getName())); 1684 1685 auto getTypeSpelling = [&](QualType Ty) { 1686 auto typeName = Ty.getUnqualifiedType().getAsString(Policy); 1687 1688 if (Ty.isCanonical()) { 1689 StringRef typeNameRef = typeName; 1690 // Turn "unsigned type" to "utype" 1691 if (typeNameRef.consume_front("unsigned ")) 1692 return std::string("u") + typeNameRef.str(); 1693 if (typeNameRef.consume_front("signed ")) 1694 return typeNameRef.str(); 1695 } 1696 1697 return typeName; 1698 }; 1699 1700 if (ty->isPointerType()) { 1701 QualType pointeeTy = ty->getPointeeType(); 1702 1703 // Get address qualifier. 1704 addressQuals.push_back( 1705 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32( 1706 ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 1707 1708 // Get argument type name. 1709 std::string typeName = getTypeSpelling(pointeeTy) + "*"; 1710 std::string baseTypeName = 1711 getTypeSpelling(pointeeTy.getCanonicalType()) + "*"; 1712 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1713 argBaseTypeNames.push_back( 1714 llvm::MDString::get(VMContext, baseTypeName)); 1715 1716 // Get argument type qualifiers: 1717 if (ty.isRestrictQualified()) 1718 typeQuals = "restrict"; 1719 if (pointeeTy.isConstQualified() || 1720 (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 1721 typeQuals += typeQuals.empty() ? "const" : " const"; 1722 if (pointeeTy.isVolatileQualified()) 1723 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 1724 } else { 1725 uint32_t AddrSpc = 0; 1726 bool isPipe = ty->isPipeType(); 1727 if (ty->isImageType() || isPipe) 1728 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 1729 1730 addressQuals.push_back( 1731 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc))); 1732 1733 // Get argument type name. 1734 ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty; 1735 std::string typeName = getTypeSpelling(ty); 1736 std::string baseTypeName = getTypeSpelling(ty.getCanonicalType()); 1737 1738 // Remove access qualifiers on images 1739 // (as they are inseparable from type in clang implementation, 1740 // but OpenCL spec provides a special query to get access qualifier 1741 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 1742 if (ty->isImageType()) { 1743 removeImageAccessQualifier(typeName); 1744 removeImageAccessQualifier(baseTypeName); 1745 } 1746 1747 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1748 argBaseTypeNames.push_back( 1749 llvm::MDString::get(VMContext, baseTypeName)); 1750 1751 if (isPipe) 1752 typeQuals = "pipe"; 1753 } 1754 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals)); 1755 } 1756 1757 Fn->setMetadata("kernel_arg_addr_space", 1758 llvm::MDNode::get(VMContext, addressQuals)); 1759 Fn->setMetadata("kernel_arg_access_qual", 1760 llvm::MDNode::get(VMContext, accessQuals)); 1761 Fn->setMetadata("kernel_arg_type", 1762 llvm::MDNode::get(VMContext, argTypeNames)); 1763 Fn->setMetadata("kernel_arg_base_type", 1764 llvm::MDNode::get(VMContext, argBaseTypeNames)); 1765 Fn->setMetadata("kernel_arg_type_qual", 1766 llvm::MDNode::get(VMContext, argTypeQuals)); 1767 if (getCodeGenOpts().EmitOpenCLArgMetadata) 1768 Fn->setMetadata("kernel_arg_name", 1769 llvm::MDNode::get(VMContext, argNames)); 1770 } 1771 1772 /// Determines whether the language options require us to model 1773 /// unwind exceptions. We treat -fexceptions as mandating this 1774 /// except under the fragile ObjC ABI with only ObjC exceptions 1775 /// enabled. This means, for example, that C with -fexceptions 1776 /// enables this. 1777 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 1778 // If exceptions are completely disabled, obviously this is false. 1779 if (!LangOpts.Exceptions) return false; 1780 1781 // If C++ exceptions are enabled, this is true. 1782 if (LangOpts.CXXExceptions) return true; 1783 1784 // If ObjC exceptions are enabled, this depends on the ABI. 1785 if (LangOpts.ObjCExceptions) { 1786 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 1787 } 1788 1789 return true; 1790 } 1791 1792 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, 1793 const CXXMethodDecl *MD) { 1794 // Check that the type metadata can ever actually be used by a call. 1795 if (!CGM.getCodeGenOpts().LTOUnit || 1796 !CGM.HasHiddenLTOVisibility(MD->getParent())) 1797 return false; 1798 1799 // Only functions whose address can be taken with a member function pointer 1800 // need this sort of type metadata. 1801 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) && 1802 !isa<CXXDestructorDecl>(MD); 1803 } 1804 1805 std::vector<const CXXRecordDecl *> 1806 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { 1807 llvm::SetVector<const CXXRecordDecl *> MostBases; 1808 1809 std::function<void (const CXXRecordDecl *)> CollectMostBases; 1810 CollectMostBases = [&](const CXXRecordDecl *RD) { 1811 if (RD->getNumBases() == 0) 1812 MostBases.insert(RD); 1813 for (const CXXBaseSpecifier &B : RD->bases()) 1814 CollectMostBases(B.getType()->getAsCXXRecordDecl()); 1815 }; 1816 CollectMostBases(RD); 1817 return MostBases.takeVector(); 1818 } 1819 1820 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 1821 llvm::Function *F) { 1822 llvm::AttrBuilder B; 1823 1824 if (CodeGenOpts.UnwindTables) 1825 B.addAttribute(llvm::Attribute::UWTable); 1826 1827 if (CodeGenOpts.StackClashProtector) 1828 B.addAttribute("probe-stack", "inline-asm"); 1829 1830 if (!hasUnwindExceptions(LangOpts)) 1831 B.addAttribute(llvm::Attribute::NoUnwind); 1832 1833 if (!D || !D->hasAttr<NoStackProtectorAttr>()) { 1834 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 1835 B.addAttribute(llvm::Attribute::StackProtect); 1836 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 1837 B.addAttribute(llvm::Attribute::StackProtectStrong); 1838 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 1839 B.addAttribute(llvm::Attribute::StackProtectReq); 1840 } 1841 1842 if (!D) { 1843 // If we don't have a declaration to control inlining, the function isn't 1844 // explicitly marked as alwaysinline for semantic reasons, and inlining is 1845 // disabled, mark the function as noinline. 1846 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 1847 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 1848 B.addAttribute(llvm::Attribute::NoInline); 1849 1850 F->addFnAttrs(B); 1851 return; 1852 } 1853 1854 // Track whether we need to add the optnone LLVM attribute, 1855 // starting with the default for this optimization level. 1856 bool ShouldAddOptNone = 1857 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 1858 // We can't add optnone in the following cases, it won't pass the verifier. 1859 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 1860 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 1861 1862 // Add optnone, but do so only if the function isn't always_inline. 1863 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) && 1864 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1865 B.addAttribute(llvm::Attribute::OptimizeNone); 1866 1867 // OptimizeNone implies noinline; we should not be inlining such functions. 1868 B.addAttribute(llvm::Attribute::NoInline); 1869 1870 // We still need to handle naked functions even though optnone subsumes 1871 // much of their semantics. 1872 if (D->hasAttr<NakedAttr>()) 1873 B.addAttribute(llvm::Attribute::Naked); 1874 1875 // OptimizeNone wins over OptimizeForSize and MinSize. 1876 F->removeFnAttr(llvm::Attribute::OptimizeForSize); 1877 F->removeFnAttr(llvm::Attribute::MinSize); 1878 } else if (D->hasAttr<NakedAttr>()) { 1879 // Naked implies noinline: we should not be inlining such functions. 1880 B.addAttribute(llvm::Attribute::Naked); 1881 B.addAttribute(llvm::Attribute::NoInline); 1882 } else if (D->hasAttr<NoDuplicateAttr>()) { 1883 B.addAttribute(llvm::Attribute::NoDuplicate); 1884 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1885 // Add noinline if the function isn't always_inline. 1886 B.addAttribute(llvm::Attribute::NoInline); 1887 } else if (D->hasAttr<AlwaysInlineAttr>() && 1888 !F->hasFnAttribute(llvm::Attribute::NoInline)) { 1889 // (noinline wins over always_inline, and we can't specify both in IR) 1890 B.addAttribute(llvm::Attribute::AlwaysInline); 1891 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 1892 // If we're not inlining, then force everything that isn't always_inline to 1893 // carry an explicit noinline attribute. 1894 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 1895 B.addAttribute(llvm::Attribute::NoInline); 1896 } else { 1897 // Otherwise, propagate the inline hint attribute and potentially use its 1898 // absence to mark things as noinline. 1899 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1900 // Search function and template pattern redeclarations for inline. 1901 auto CheckForInline = [](const FunctionDecl *FD) { 1902 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { 1903 return Redecl->isInlineSpecified(); 1904 }; 1905 if (any_of(FD->redecls(), CheckRedeclForInline)) 1906 return true; 1907 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); 1908 if (!Pattern) 1909 return false; 1910 return any_of(Pattern->redecls(), CheckRedeclForInline); 1911 }; 1912 if (CheckForInline(FD)) { 1913 B.addAttribute(llvm::Attribute::InlineHint); 1914 } else if (CodeGenOpts.getInlining() == 1915 CodeGenOptions::OnlyHintInlining && 1916 !FD->isInlined() && 1917 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1918 B.addAttribute(llvm::Attribute::NoInline); 1919 } 1920 } 1921 } 1922 1923 // Add other optimization related attributes if we are optimizing this 1924 // function. 1925 if (!D->hasAttr<OptimizeNoneAttr>()) { 1926 if (D->hasAttr<ColdAttr>()) { 1927 if (!ShouldAddOptNone) 1928 B.addAttribute(llvm::Attribute::OptimizeForSize); 1929 B.addAttribute(llvm::Attribute::Cold); 1930 } 1931 if (D->hasAttr<HotAttr>()) 1932 B.addAttribute(llvm::Attribute::Hot); 1933 if (D->hasAttr<MinSizeAttr>()) 1934 B.addAttribute(llvm::Attribute::MinSize); 1935 } 1936 1937 F->addFnAttrs(B); 1938 1939 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 1940 if (alignment) 1941 F->setAlignment(llvm::Align(alignment)); 1942 1943 if (!D->hasAttr<AlignedAttr>()) 1944 if (LangOpts.FunctionAlignment) 1945 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); 1946 1947 // Some C++ ABIs require 2-byte alignment for member functions, in order to 1948 // reserve a bit for differentiating between virtual and non-virtual member 1949 // functions. If the current target's C++ ABI requires this and this is a 1950 // member function, set its alignment accordingly. 1951 if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 1952 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 1953 F->setAlignment(llvm::Align(2)); 1954 } 1955 1956 // In the cross-dso CFI mode with canonical jump tables, we want !type 1957 // attributes on definitions only. 1958 if (CodeGenOpts.SanitizeCfiCrossDso && 1959 CodeGenOpts.SanitizeCfiCanonicalJumpTables) { 1960 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1961 // Skip available_externally functions. They won't be codegen'ed in the 1962 // current module anyway. 1963 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) 1964 CreateFunctionTypeMetadataForIcall(FD, F); 1965 } 1966 } 1967 1968 // Emit type metadata on member functions for member function pointer checks. 1969 // These are only ever necessary on definitions; we're guaranteed that the 1970 // definition will be present in the LTO unit as a result of LTO visibility. 1971 auto *MD = dyn_cast<CXXMethodDecl>(D); 1972 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) { 1973 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) { 1974 llvm::Metadata *Id = 1975 CreateMetadataIdentifierForType(Context.getMemberPointerType( 1976 MD->getType(), Context.getRecordType(Base).getTypePtr())); 1977 F->addTypeMetadata(0, Id); 1978 } 1979 } 1980 } 1981 1982 void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D, 1983 llvm::Function *F) { 1984 if (D->hasAttr<StrictFPAttr>()) { 1985 llvm::AttrBuilder FuncAttrs; 1986 FuncAttrs.addAttribute("strictfp"); 1987 F->addFnAttrs(FuncAttrs); 1988 } 1989 } 1990 1991 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { 1992 const Decl *D = GD.getDecl(); 1993 if (isa_and_nonnull<NamedDecl>(D)) 1994 setGVProperties(GV, GD); 1995 else 1996 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1997 1998 if (D && D->hasAttr<UsedAttr>()) 1999 addUsedOrCompilerUsedGlobal(GV); 2000 2001 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) { 2002 const auto *VD = cast<VarDecl>(D); 2003 if (VD->getType().isConstQualified() && 2004 VD->getStorageDuration() == SD_Static) 2005 addUsedOrCompilerUsedGlobal(GV); 2006 } 2007 } 2008 2009 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, 2010 llvm::AttrBuilder &Attrs) { 2011 // Add target-cpu and target-features attributes to functions. If 2012 // we have a decl for the function and it has a target attribute then 2013 // parse that and add it to the feature set. 2014 StringRef TargetCPU = getTarget().getTargetOpts().CPU; 2015 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; 2016 std::vector<std::string> Features; 2017 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl()); 2018 FD = FD ? FD->getMostRecentDecl() : FD; 2019 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; 2020 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; 2021 const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr; 2022 bool AddedAttr = false; 2023 if (TD || SD || TC) { 2024 llvm::StringMap<bool> FeatureMap; 2025 getContext().getFunctionFeatureMap(FeatureMap, GD); 2026 2027 // Produce the canonical string for this set of features. 2028 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) 2029 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str()); 2030 2031 // Now add the target-cpu and target-features to the function. 2032 // While we populated the feature map above, we still need to 2033 // get and parse the target attribute so we can get the cpu for 2034 // the function. 2035 if (TD) { 2036 ParsedTargetAttr ParsedAttr = TD->parse(); 2037 if (!ParsedAttr.Architecture.empty() && 2038 getTarget().isValidCPUName(ParsedAttr.Architecture)) { 2039 TargetCPU = ParsedAttr.Architecture; 2040 TuneCPU = ""; // Clear the tune CPU. 2041 } 2042 if (!ParsedAttr.Tune.empty() && 2043 getTarget().isValidCPUName(ParsedAttr.Tune)) 2044 TuneCPU = ParsedAttr.Tune; 2045 } 2046 } else { 2047 // Otherwise just add the existing target cpu and target features to the 2048 // function. 2049 Features = getTarget().getTargetOpts().Features; 2050 } 2051 2052 if (!TargetCPU.empty()) { 2053 Attrs.addAttribute("target-cpu", TargetCPU); 2054 AddedAttr = true; 2055 } 2056 if (!TuneCPU.empty()) { 2057 Attrs.addAttribute("tune-cpu", TuneCPU); 2058 AddedAttr = true; 2059 } 2060 if (!Features.empty()) { 2061 llvm::sort(Features); 2062 Attrs.addAttribute("target-features", llvm::join(Features, ",")); 2063 AddedAttr = true; 2064 } 2065 2066 return AddedAttr; 2067 } 2068 2069 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 2070 llvm::GlobalObject *GO) { 2071 const Decl *D = GD.getDecl(); 2072 SetCommonAttributes(GD, GO); 2073 2074 if (D) { 2075 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 2076 if (D->hasAttr<RetainAttr>()) 2077 addUsedGlobal(GV); 2078 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 2079 GV->addAttribute("bss-section", SA->getName()); 2080 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 2081 GV->addAttribute("data-section", SA->getName()); 2082 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 2083 GV->addAttribute("rodata-section", SA->getName()); 2084 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 2085 GV->addAttribute("relro-section", SA->getName()); 2086 } 2087 2088 if (auto *F = dyn_cast<llvm::Function>(GO)) { 2089 if (D->hasAttr<RetainAttr>()) 2090 addUsedGlobal(F); 2091 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 2092 if (!D->getAttr<SectionAttr>()) 2093 F->addFnAttr("implicit-section-name", SA->getName()); 2094 2095 llvm::AttrBuilder Attrs; 2096 if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 2097 // We know that GetCPUAndFeaturesAttributes will always have the 2098 // newest set, since it has the newest possible FunctionDecl, so the 2099 // new ones should replace the old. 2100 llvm::AttrBuilder RemoveAttrs; 2101 RemoveAttrs.addAttribute("target-cpu"); 2102 RemoveAttrs.addAttribute("target-features"); 2103 RemoveAttrs.addAttribute("tune-cpu"); 2104 F->removeFnAttrs(RemoveAttrs); 2105 F->addFnAttrs(Attrs); 2106 } 2107 } 2108 2109 if (const auto *CSA = D->getAttr<CodeSegAttr>()) 2110 GO->setSection(CSA->getName()); 2111 else if (const auto *SA = D->getAttr<SectionAttr>()) 2112 GO->setSection(SA->getName()); 2113 } 2114 2115 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 2116 } 2117 2118 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 2119 llvm::Function *F, 2120 const CGFunctionInfo &FI) { 2121 const Decl *D = GD.getDecl(); 2122 SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false); 2123 SetLLVMFunctionAttributesForDefinition(D, F); 2124 2125 F->setLinkage(llvm::Function::InternalLinkage); 2126 2127 setNonAliasAttributes(GD, F); 2128 } 2129 2130 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 2131 // Set linkage and visibility in case we never see a definition. 2132 LinkageInfo LV = ND->getLinkageAndVisibility(); 2133 // Don't set internal linkage on declarations. 2134 // "extern_weak" is overloaded in LLVM; we probably should have 2135 // separate linkage types for this. 2136 if (isExternallyVisible(LV.getLinkage()) && 2137 (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 2138 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 2139 } 2140 2141 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 2142 llvm::Function *F) { 2143 // Only if we are checking indirect calls. 2144 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 2145 return; 2146 2147 // Non-static class methods are handled via vtable or member function pointer 2148 // checks elsewhere. 2149 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 2150 return; 2151 2152 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 2153 F->addTypeMetadata(0, MD); 2154 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 2155 2156 // Emit a hash-based bit set entry for cross-DSO calls. 2157 if (CodeGenOpts.SanitizeCfiCrossDso) 2158 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 2159 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 2160 } 2161 2162 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 2163 bool IsIncompleteFunction, 2164 bool IsThunk) { 2165 2166 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 2167 // If this is an intrinsic function, set the function's attributes 2168 // to the intrinsic's attributes. 2169 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 2170 return; 2171 } 2172 2173 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2174 2175 if (!IsIncompleteFunction) 2176 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F, 2177 IsThunk); 2178 2179 // Add the Returned attribute for "this", except for iOS 5 and earlier 2180 // where substantial code, including the libstdc++ dylib, was compiled with 2181 // GCC and does not actually return "this". 2182 if (!IsThunk && getCXXABI().HasThisReturn(GD) && 2183 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 2184 assert(!F->arg_empty() && 2185 F->arg_begin()->getType() 2186 ->canLosslesslyBitCastTo(F->getReturnType()) && 2187 "unexpected this return"); 2188 F->addParamAttr(0, llvm::Attribute::Returned); 2189 } 2190 2191 // Only a few attributes are set on declarations; these may later be 2192 // overridden by a definition. 2193 2194 setLinkageForGV(F, FD); 2195 setGVProperties(F, FD); 2196 2197 // Setup target-specific attributes. 2198 if (!IsIncompleteFunction && F->isDeclaration()) 2199 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 2200 2201 if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 2202 F->setSection(CSA->getName()); 2203 else if (const auto *SA = FD->getAttr<SectionAttr>()) 2204 F->setSection(SA->getName()); 2205 2206 if (const auto *EA = FD->getAttr<ErrorAttr>()) { 2207 if (EA->isError()) 2208 F->addFnAttr("dontcall-error", EA->getUserDiagnostic()); 2209 else if (EA->isWarning()) 2210 F->addFnAttr("dontcall-warn", EA->getUserDiagnostic()); 2211 } 2212 2213 // If we plan on emitting this inline builtin, we can't treat it as a builtin. 2214 if (FD->isInlineBuiltinDeclaration()) { 2215 const FunctionDecl *FDBody; 2216 bool HasBody = FD->hasBody(FDBody); 2217 (void)HasBody; 2218 assert(HasBody && "Inline builtin declarations should always have an " 2219 "available body!"); 2220 if (shouldEmitFunction(FDBody)) 2221 F->addFnAttr(llvm::Attribute::NoBuiltin); 2222 } 2223 2224 if (FD->isReplaceableGlobalAllocationFunction()) { 2225 // A replaceable global allocation function does not act like a builtin by 2226 // default, only if it is invoked by a new-expression or delete-expression. 2227 F->addFnAttr(llvm::Attribute::NoBuiltin); 2228 } 2229 2230 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 2231 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2232 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 2233 if (MD->isVirtual()) 2234 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2235 2236 // Don't emit entries for function declarations in the cross-DSO mode. This 2237 // is handled with better precision by the receiving DSO. But if jump tables 2238 // are non-canonical then we need type metadata in order to produce the local 2239 // jump table. 2240 if (!CodeGenOpts.SanitizeCfiCrossDso || 2241 !CodeGenOpts.SanitizeCfiCanonicalJumpTables) 2242 CreateFunctionTypeMetadataForIcall(FD, F); 2243 2244 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 2245 getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 2246 2247 if (const auto *CB = FD->getAttr<CallbackAttr>()) { 2248 // Annotate the callback behavior as metadata: 2249 // - The callback callee (as argument number). 2250 // - The callback payloads (as argument numbers). 2251 llvm::LLVMContext &Ctx = F->getContext(); 2252 llvm::MDBuilder MDB(Ctx); 2253 2254 // The payload indices are all but the first one in the encoding. The first 2255 // identifies the callback callee. 2256 int CalleeIdx = *CB->encoding_begin(); 2257 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 2258 F->addMetadata(llvm::LLVMContext::MD_callback, 2259 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 2260 CalleeIdx, PayloadIndices, 2261 /* VarArgsArePassed */ false)})); 2262 } 2263 } 2264 2265 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 2266 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2267 "Only globals with definition can force usage."); 2268 LLVMUsed.emplace_back(GV); 2269 } 2270 2271 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 2272 assert(!GV->isDeclaration() && 2273 "Only globals with definition can force usage."); 2274 LLVMCompilerUsed.emplace_back(GV); 2275 } 2276 2277 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) { 2278 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2279 "Only globals with definition can force usage."); 2280 if (getTriple().isOSBinFormatELF()) 2281 LLVMCompilerUsed.emplace_back(GV); 2282 else 2283 LLVMUsed.emplace_back(GV); 2284 } 2285 2286 static void emitUsed(CodeGenModule &CGM, StringRef Name, 2287 std::vector<llvm::WeakTrackingVH> &List) { 2288 // Don't create llvm.used if there is no need. 2289 if (List.empty()) 2290 return; 2291 2292 // Convert List to what ConstantArray needs. 2293 SmallVector<llvm::Constant*, 8> UsedArray; 2294 UsedArray.resize(List.size()); 2295 for (unsigned i = 0, e = List.size(); i != e; ++i) { 2296 UsedArray[i] = 2297 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 2298 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 2299 } 2300 2301 if (UsedArray.empty()) 2302 return; 2303 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 2304 2305 auto *GV = new llvm::GlobalVariable( 2306 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 2307 llvm::ConstantArray::get(ATy, UsedArray), Name); 2308 2309 GV->setSection("llvm.metadata"); 2310 } 2311 2312 void CodeGenModule::emitLLVMUsed() { 2313 emitUsed(*this, "llvm.used", LLVMUsed); 2314 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 2315 } 2316 2317 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 2318 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 2319 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2320 } 2321 2322 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 2323 llvm::SmallString<32> Opt; 2324 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 2325 if (Opt.empty()) 2326 return; 2327 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2328 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2329 } 2330 2331 void CodeGenModule::AddDependentLib(StringRef Lib) { 2332 auto &C = getLLVMContext(); 2333 if (getTarget().getTriple().isOSBinFormatELF()) { 2334 ELFDependentLibraries.push_back( 2335 llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 2336 return; 2337 } 2338 2339 llvm::SmallString<24> Opt; 2340 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 2341 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2342 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 2343 } 2344 2345 /// Add link options implied by the given module, including modules 2346 /// it depends on, using a postorder walk. 2347 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 2348 SmallVectorImpl<llvm::MDNode *> &Metadata, 2349 llvm::SmallPtrSet<Module *, 16> &Visited) { 2350 // Import this module's parent. 2351 if (Mod->Parent && Visited.insert(Mod->Parent).second) { 2352 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 2353 } 2354 2355 // Import this module's dependencies. 2356 for (Module *Import : llvm::reverse(Mod->Imports)) { 2357 if (Visited.insert(Import).second) 2358 addLinkOptionsPostorder(CGM, Import, Metadata, Visited); 2359 } 2360 2361 // Add linker options to link against the libraries/frameworks 2362 // described by this module. 2363 llvm::LLVMContext &Context = CGM.getLLVMContext(); 2364 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 2365 2366 // For modules that use export_as for linking, use that module 2367 // name instead. 2368 if (Mod->UseExportAsModuleLinkName) 2369 return; 2370 2371 for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) { 2372 // Link against a framework. Frameworks are currently Darwin only, so we 2373 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 2374 if (LL.IsFramework) { 2375 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"), 2376 llvm::MDString::get(Context, LL.Library)}; 2377 2378 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2379 continue; 2380 } 2381 2382 // Link against a library. 2383 if (IsELF) { 2384 llvm::Metadata *Args[2] = { 2385 llvm::MDString::get(Context, "lib"), 2386 llvm::MDString::get(Context, LL.Library), 2387 }; 2388 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2389 } else { 2390 llvm::SmallString<24> Opt; 2391 CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt); 2392 auto *OptString = llvm::MDString::get(Context, Opt); 2393 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 2394 } 2395 } 2396 } 2397 2398 void CodeGenModule::EmitModuleLinkOptions() { 2399 // Collect the set of all of the modules we want to visit to emit link 2400 // options, which is essentially the imported modules and all of their 2401 // non-explicit child modules. 2402 llvm::SetVector<clang::Module *> LinkModules; 2403 llvm::SmallPtrSet<clang::Module *, 16> Visited; 2404 SmallVector<clang::Module *, 16> Stack; 2405 2406 // Seed the stack with imported modules. 2407 for (Module *M : ImportedModules) { 2408 // Do not add any link flags when an implementation TU of a module imports 2409 // a header of that same module. 2410 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 2411 !getLangOpts().isCompilingModule()) 2412 continue; 2413 if (Visited.insert(M).second) 2414 Stack.push_back(M); 2415 } 2416 2417 // Find all of the modules to import, making a little effort to prune 2418 // non-leaf modules. 2419 while (!Stack.empty()) { 2420 clang::Module *Mod = Stack.pop_back_val(); 2421 2422 bool AnyChildren = false; 2423 2424 // Visit the submodules of this module. 2425 for (const auto &SM : Mod->submodules()) { 2426 // Skip explicit children; they need to be explicitly imported to be 2427 // linked against. 2428 if (SM->IsExplicit) 2429 continue; 2430 2431 if (Visited.insert(SM).second) { 2432 Stack.push_back(SM); 2433 AnyChildren = true; 2434 } 2435 } 2436 2437 // We didn't find any children, so add this module to the list of 2438 // modules to link against. 2439 if (!AnyChildren) { 2440 LinkModules.insert(Mod); 2441 } 2442 } 2443 2444 // Add link options for all of the imported modules in reverse topological 2445 // order. We don't do anything to try to order import link flags with respect 2446 // to linker options inserted by things like #pragma comment(). 2447 SmallVector<llvm::MDNode *, 16> MetadataArgs; 2448 Visited.clear(); 2449 for (Module *M : LinkModules) 2450 if (Visited.insert(M).second) 2451 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 2452 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 2453 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 2454 2455 // Add the linker options metadata flag. 2456 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 2457 for (auto *MD : LinkerOptionsMetadata) 2458 NMD->addOperand(MD); 2459 } 2460 2461 void CodeGenModule::EmitDeferred() { 2462 // Emit deferred declare target declarations. 2463 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 2464 getOpenMPRuntime().emitDeferredTargetDecls(); 2465 2466 // Emit code for any potentially referenced deferred decls. Since a 2467 // previously unused static decl may become used during the generation of code 2468 // for a static function, iterate until no changes are made. 2469 2470 if (!DeferredVTables.empty()) { 2471 EmitDeferredVTables(); 2472 2473 // Emitting a vtable doesn't directly cause more vtables to 2474 // become deferred, although it can cause functions to be 2475 // emitted that then need those vtables. 2476 assert(DeferredVTables.empty()); 2477 } 2478 2479 // Emit CUDA/HIP static device variables referenced by host code only. 2480 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still 2481 // needed for further handling. 2482 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) 2483 for (const auto *V : getContext().CUDADeviceVarODRUsedByHost) 2484 DeferredDeclsToEmit.push_back(V); 2485 2486 // Stop if we're out of both deferred vtables and deferred declarations. 2487 if (DeferredDeclsToEmit.empty()) 2488 return; 2489 2490 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 2491 // work, it will not interfere with this. 2492 std::vector<GlobalDecl> CurDeclsToEmit; 2493 CurDeclsToEmit.swap(DeferredDeclsToEmit); 2494 2495 for (GlobalDecl &D : CurDeclsToEmit) { 2496 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 2497 // to get GlobalValue with exactly the type we need, not something that 2498 // might had been created for another decl with the same mangled name but 2499 // different type. 2500 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 2501 GetAddrOfGlobal(D, ForDefinition)); 2502 2503 // In case of different address spaces, we may still get a cast, even with 2504 // IsForDefinition equal to true. Query mangled names table to get 2505 // GlobalValue. 2506 if (!GV) 2507 GV = GetGlobalValue(getMangledName(D)); 2508 2509 // Make sure GetGlobalValue returned non-null. 2510 assert(GV); 2511 2512 // Check to see if we've already emitted this. This is necessary 2513 // for a couple of reasons: first, decls can end up in the 2514 // deferred-decls queue multiple times, and second, decls can end 2515 // up with definitions in unusual ways (e.g. by an extern inline 2516 // function acquiring a strong function redefinition). Just 2517 // ignore these cases. 2518 if (!GV->isDeclaration()) 2519 continue; 2520 2521 // If this is OpenMP, check if it is legal to emit this global normally. 2522 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) 2523 continue; 2524 2525 // Otherwise, emit the definition and move on to the next one. 2526 EmitGlobalDefinition(D, GV); 2527 2528 // If we found out that we need to emit more decls, do that recursively. 2529 // This has the advantage that the decls are emitted in a DFS and related 2530 // ones are close together, which is convenient for testing. 2531 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 2532 EmitDeferred(); 2533 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 2534 } 2535 } 2536 } 2537 2538 void CodeGenModule::EmitVTablesOpportunistically() { 2539 // Try to emit external vtables as available_externally if they have emitted 2540 // all inlined virtual functions. It runs after EmitDeferred() and therefore 2541 // is not allowed to create new references to things that need to be emitted 2542 // lazily. Note that it also uses fact that we eagerly emitting RTTI. 2543 2544 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 2545 && "Only emit opportunistic vtables with optimizations"); 2546 2547 for (const CXXRecordDecl *RD : OpportunisticVTables) { 2548 assert(getVTables().isVTableExternal(RD) && 2549 "This queue should only contain external vtables"); 2550 if (getCXXABI().canSpeculativelyEmitVTable(RD)) 2551 VTables.GenerateClassData(RD); 2552 } 2553 OpportunisticVTables.clear(); 2554 } 2555 2556 void CodeGenModule::EmitGlobalAnnotations() { 2557 if (Annotations.empty()) 2558 return; 2559 2560 // Create a new global variable for the ConstantStruct in the Module. 2561 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 2562 Annotations[0]->getType(), Annotations.size()), Annotations); 2563 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 2564 llvm::GlobalValue::AppendingLinkage, 2565 Array, "llvm.global.annotations"); 2566 gv->setSection(AnnotationSection); 2567 } 2568 2569 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 2570 llvm::Constant *&AStr = AnnotationStrings[Str]; 2571 if (AStr) 2572 return AStr; 2573 2574 // Not found yet, create a new global. 2575 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 2576 auto *gv = 2577 new llvm::GlobalVariable(getModule(), s->getType(), true, 2578 llvm::GlobalValue::PrivateLinkage, s, ".str"); 2579 gv->setSection(AnnotationSection); 2580 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2581 AStr = gv; 2582 return gv; 2583 } 2584 2585 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 2586 SourceManager &SM = getContext().getSourceManager(); 2587 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 2588 if (PLoc.isValid()) 2589 return EmitAnnotationString(PLoc.getFilename()); 2590 return EmitAnnotationString(SM.getBufferName(Loc)); 2591 } 2592 2593 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 2594 SourceManager &SM = getContext().getSourceManager(); 2595 PresumedLoc PLoc = SM.getPresumedLoc(L); 2596 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 2597 SM.getExpansionLineNumber(L); 2598 return llvm::ConstantInt::get(Int32Ty, LineNo); 2599 } 2600 2601 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { 2602 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; 2603 if (Exprs.empty()) 2604 return llvm::ConstantPointerNull::get(GlobalsInt8PtrTy); 2605 2606 llvm::FoldingSetNodeID ID; 2607 for (Expr *E : Exprs) { 2608 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult()); 2609 } 2610 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; 2611 if (Lookup) 2612 return Lookup; 2613 2614 llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; 2615 LLVMArgs.reserve(Exprs.size()); 2616 ConstantEmitter ConstEmiter(*this); 2617 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) { 2618 const auto *CE = cast<clang::ConstantExpr>(E); 2619 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), 2620 CE->getType()); 2621 }); 2622 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs); 2623 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, 2624 llvm::GlobalValue::PrivateLinkage, Struct, 2625 ".args"); 2626 GV->setSection(AnnotationSection); 2627 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2628 auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy); 2629 2630 Lookup = Bitcasted; 2631 return Bitcasted; 2632 } 2633 2634 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 2635 const AnnotateAttr *AA, 2636 SourceLocation L) { 2637 // Get the globals for file name, annotation, and the line number. 2638 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 2639 *UnitGV = EmitAnnotationUnit(L), 2640 *LineNoCst = EmitAnnotationLineNo(L), 2641 *Args = EmitAnnotationArgs(AA); 2642 2643 llvm::Constant *GVInGlobalsAS = GV; 2644 if (GV->getAddressSpace() != 2645 getDataLayout().getDefaultGlobalsAddressSpace()) { 2646 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast( 2647 GV, GV->getValueType()->getPointerTo( 2648 getDataLayout().getDefaultGlobalsAddressSpace())); 2649 } 2650 2651 // Create the ConstantStruct for the global annotation. 2652 llvm::Constant *Fields[] = { 2653 llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy), 2654 llvm::ConstantExpr::getBitCast(AnnoGV, GlobalsInt8PtrTy), 2655 llvm::ConstantExpr::getBitCast(UnitGV, GlobalsInt8PtrTy), 2656 LineNoCst, 2657 Args, 2658 }; 2659 return llvm::ConstantStruct::getAnon(Fields); 2660 } 2661 2662 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 2663 llvm::GlobalValue *GV) { 2664 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2665 // Get the struct elements for these annotations. 2666 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2667 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 2668 } 2669 2670 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, 2671 SourceLocation Loc) const { 2672 const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2673 // NoSanitize by function name. 2674 if (NoSanitizeL.containsFunction(Kind, Fn->getName())) 2675 return true; 2676 // NoSanitize by location. 2677 if (Loc.isValid()) 2678 return NoSanitizeL.containsLocation(Kind, Loc); 2679 // If location is unknown, this may be a compiler-generated function. Assume 2680 // it's located in the main file. 2681 auto &SM = Context.getSourceManager(); 2682 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2683 return NoSanitizeL.containsFile(Kind, MainFile->getName()); 2684 } 2685 return false; 2686 } 2687 2688 bool CodeGenModule::isInNoSanitizeList(llvm::GlobalVariable *GV, 2689 SourceLocation Loc, QualType Ty, 2690 StringRef Category) const { 2691 // For now globals can be ignored only in ASan and KASan. 2692 const SanitizerMask EnabledAsanMask = 2693 LangOpts.Sanitize.Mask & 2694 (SanitizerKind::Address | SanitizerKind::KernelAddress | 2695 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress | 2696 SanitizerKind::MemTag); 2697 if (!EnabledAsanMask) 2698 return false; 2699 const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2700 if (NoSanitizeL.containsGlobal(EnabledAsanMask, GV->getName(), Category)) 2701 return true; 2702 if (NoSanitizeL.containsLocation(EnabledAsanMask, Loc, Category)) 2703 return true; 2704 // Check global type. 2705 if (!Ty.isNull()) { 2706 // Drill down the array types: if global variable of a fixed type is 2707 // not sanitized, we also don't instrument arrays of them. 2708 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 2709 Ty = AT->getElementType(); 2710 Ty = Ty.getCanonicalType().getUnqualifiedType(); 2711 // Only record types (classes, structs etc.) are ignored. 2712 if (Ty->isRecordType()) { 2713 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 2714 if (NoSanitizeL.containsType(EnabledAsanMask, TypeStr, Category)) 2715 return true; 2716 } 2717 } 2718 return false; 2719 } 2720 2721 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 2722 StringRef Category) const { 2723 const auto &XRayFilter = getContext().getXRayFilter(); 2724 using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 2725 auto Attr = ImbueAttr::NONE; 2726 if (Loc.isValid()) 2727 Attr = XRayFilter.shouldImbueLocation(Loc, Category); 2728 if (Attr == ImbueAttr::NONE) 2729 Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 2730 switch (Attr) { 2731 case ImbueAttr::NONE: 2732 return false; 2733 case ImbueAttr::ALWAYS: 2734 Fn->addFnAttr("function-instrument", "xray-always"); 2735 break; 2736 case ImbueAttr::ALWAYS_ARG1: 2737 Fn->addFnAttr("function-instrument", "xray-always"); 2738 Fn->addFnAttr("xray-log-args", "1"); 2739 break; 2740 case ImbueAttr::NEVER: 2741 Fn->addFnAttr("function-instrument", "xray-never"); 2742 break; 2743 } 2744 return true; 2745 } 2746 2747 bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn, 2748 SourceLocation Loc) const { 2749 const auto &ProfileList = getContext().getProfileList(); 2750 // If the profile list is empty, then instrument everything. 2751 if (ProfileList.isEmpty()) 2752 return false; 2753 CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); 2754 // First, check the function name. 2755 Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind); 2756 if (V.hasValue()) 2757 return *V; 2758 // Next, check the source location. 2759 if (Loc.isValid()) { 2760 Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind); 2761 if (V.hasValue()) 2762 return *V; 2763 } 2764 // If location is unknown, this may be a compiler-generated function. Assume 2765 // it's located in the main file. 2766 auto &SM = Context.getSourceManager(); 2767 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2768 Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind); 2769 if (V.hasValue()) 2770 return *V; 2771 } 2772 return ProfileList.getDefault(); 2773 } 2774 2775 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 2776 // Never defer when EmitAllDecls is specified. 2777 if (LangOpts.EmitAllDecls) 2778 return true; 2779 2780 if (CodeGenOpts.KeepStaticConsts) { 2781 const auto *VD = dyn_cast<VarDecl>(Global); 2782 if (VD && VD->getType().isConstQualified() && 2783 VD->getStorageDuration() == SD_Static) 2784 return true; 2785 } 2786 2787 return getContext().DeclMustBeEmitted(Global); 2788 } 2789 2790 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 2791 // In OpenMP 5.0 variables and function may be marked as 2792 // device_type(host/nohost) and we should not emit them eagerly unless we sure 2793 // that they must be emitted on the host/device. To be sure we need to have 2794 // seen a declare target with an explicit mentioning of the function, we know 2795 // we have if the level of the declare target attribute is -1. Note that we 2796 // check somewhere else if we should emit this at all. 2797 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) { 2798 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 2799 OMPDeclareTargetDeclAttr::getActiveAttr(Global); 2800 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1) 2801 return false; 2802 } 2803 2804 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 2805 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 2806 // Implicit template instantiations may change linkage if they are later 2807 // explicitly instantiated, so they should not be emitted eagerly. 2808 return false; 2809 } 2810 if (const auto *VD = dyn_cast<VarDecl>(Global)) 2811 if (Context.getInlineVariableDefinitionKind(VD) == 2812 ASTContext::InlineVariableDefinitionKind::WeakUnknown) 2813 // A definition of an inline constexpr static data member may change 2814 // linkage later if it's redeclared outside the class. 2815 return false; 2816 // If OpenMP is enabled and threadprivates must be generated like TLS, delay 2817 // codegen for global variables, because they may be marked as threadprivate. 2818 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 2819 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 2820 !isTypeConstant(Global->getType(), false) && 2821 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 2822 return false; 2823 2824 return true; 2825 } 2826 2827 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { 2828 StringRef Name = getMangledName(GD); 2829 2830 // The UUID descriptor should be pointer aligned. 2831 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 2832 2833 // Look for an existing global. 2834 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 2835 return ConstantAddress(GV, GV->getValueType(), Alignment); 2836 2837 ConstantEmitter Emitter(*this); 2838 llvm::Constant *Init; 2839 2840 APValue &V = GD->getAsAPValue(); 2841 if (!V.isAbsent()) { 2842 // If possible, emit the APValue version of the initializer. In particular, 2843 // this gets the type of the constant right. 2844 Init = Emitter.emitForInitializer( 2845 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType()); 2846 } else { 2847 // As a fallback, directly construct the constant. 2848 // FIXME: This may get padding wrong under esoteric struct layout rules. 2849 // MSVC appears to create a complete type 'struct __s_GUID' that it 2850 // presumably uses to represent these constants. 2851 MSGuidDecl::Parts Parts = GD->getParts(); 2852 llvm::Constant *Fields[4] = { 2853 llvm::ConstantInt::get(Int32Ty, Parts.Part1), 2854 llvm::ConstantInt::get(Int16Ty, Parts.Part2), 2855 llvm::ConstantInt::get(Int16Ty, Parts.Part3), 2856 llvm::ConstantDataArray::getRaw( 2857 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8, 2858 Int8Ty)}; 2859 Init = llvm::ConstantStruct::getAnon(Fields); 2860 } 2861 2862 auto *GV = new llvm::GlobalVariable( 2863 getModule(), Init->getType(), 2864 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 2865 if (supportsCOMDAT()) 2866 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2867 setDSOLocal(GV); 2868 2869 if (!V.isAbsent()) { 2870 Emitter.finalize(GV); 2871 return ConstantAddress(GV, GV->getValueType(), Alignment); 2872 } 2873 2874 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType()); 2875 llvm::Constant *Addr = llvm::ConstantExpr::getBitCast( 2876 GV, Ty->getPointerTo(GV->getAddressSpace())); 2877 return ConstantAddress(Addr, Ty, Alignment); 2878 } 2879 2880 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject( 2881 const TemplateParamObjectDecl *TPO) { 2882 StringRef Name = getMangledName(TPO); 2883 CharUnits Alignment = getNaturalTypeAlignment(TPO->getType()); 2884 2885 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 2886 return ConstantAddress(GV, GV->getValueType(), Alignment); 2887 2888 ConstantEmitter Emitter(*this); 2889 llvm::Constant *Init = Emitter.emitForInitializer( 2890 TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType()); 2891 2892 if (!Init) { 2893 ErrorUnsupported(TPO, "template parameter object"); 2894 return ConstantAddress::invalid(); 2895 } 2896 2897 auto *GV = new llvm::GlobalVariable( 2898 getModule(), Init->getType(), 2899 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 2900 if (supportsCOMDAT()) 2901 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2902 Emitter.finalize(GV); 2903 2904 return ConstantAddress(GV, GV->getValueType(), Alignment); 2905 } 2906 2907 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 2908 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 2909 assert(AA && "No alias?"); 2910 2911 CharUnits Alignment = getContext().getDeclAlign(VD); 2912 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 2913 2914 // See if there is already something with the target's name in the module. 2915 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 2916 if (Entry) { 2917 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 2918 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 2919 return ConstantAddress(Ptr, DeclTy, Alignment); 2920 } 2921 2922 llvm::Constant *Aliasee; 2923 if (isa<llvm::FunctionType>(DeclTy)) 2924 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 2925 GlobalDecl(cast<FunctionDecl>(VD)), 2926 /*ForVTable=*/false); 2927 else 2928 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 2929 nullptr); 2930 2931 auto *F = cast<llvm::GlobalValue>(Aliasee); 2932 F->setLinkage(llvm::Function::ExternalWeakLinkage); 2933 WeakRefReferences.insert(F); 2934 2935 return ConstantAddress(Aliasee, DeclTy, Alignment); 2936 } 2937 2938 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 2939 const auto *Global = cast<ValueDecl>(GD.getDecl()); 2940 2941 // Weak references don't produce any output by themselves. 2942 if (Global->hasAttr<WeakRefAttr>()) 2943 return; 2944 2945 // If this is an alias definition (which otherwise looks like a declaration) 2946 // emit it now. 2947 if (Global->hasAttr<AliasAttr>()) 2948 return EmitAliasDefinition(GD); 2949 2950 // IFunc like an alias whose value is resolved at runtime by calling resolver. 2951 if (Global->hasAttr<IFuncAttr>()) 2952 return emitIFuncDefinition(GD); 2953 2954 // If this is a cpu_dispatch multiversion function, emit the resolver. 2955 if (Global->hasAttr<CPUDispatchAttr>()) 2956 return emitCPUDispatchDefinition(GD); 2957 2958 // If this is CUDA, be selective about which declarations we emit. 2959 if (LangOpts.CUDA) { 2960 if (LangOpts.CUDAIsDevice) { 2961 if (!Global->hasAttr<CUDADeviceAttr>() && 2962 !Global->hasAttr<CUDAGlobalAttr>() && 2963 !Global->hasAttr<CUDAConstantAttr>() && 2964 !Global->hasAttr<CUDASharedAttr>() && 2965 !Global->getType()->isCUDADeviceBuiltinSurfaceType() && 2966 !Global->getType()->isCUDADeviceBuiltinTextureType()) 2967 return; 2968 } else { 2969 // We need to emit host-side 'shadows' for all global 2970 // device-side variables because the CUDA runtime needs their 2971 // size and host-side address in order to provide access to 2972 // their device-side incarnations. 2973 2974 // So device-only functions are the only things we skip. 2975 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 2976 Global->hasAttr<CUDADeviceAttr>()) 2977 return; 2978 2979 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 2980 "Expected Variable or Function"); 2981 } 2982 } 2983 2984 if (LangOpts.OpenMP) { 2985 // If this is OpenMP, check if it is legal to emit this global normally. 2986 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 2987 return; 2988 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 2989 if (MustBeEmitted(Global)) 2990 EmitOMPDeclareReduction(DRD); 2991 return; 2992 } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { 2993 if (MustBeEmitted(Global)) 2994 EmitOMPDeclareMapper(DMD); 2995 return; 2996 } 2997 } 2998 2999 // Ignore declarations, they will be emitted on their first use. 3000 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 3001 // Forward declarations are emitted lazily on first use. 3002 if (!FD->doesThisDeclarationHaveABody()) { 3003 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 3004 return; 3005 3006 StringRef MangledName = getMangledName(GD); 3007 3008 // Compute the function info and LLVM type. 3009 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3010 llvm::Type *Ty = getTypes().GetFunctionType(FI); 3011 3012 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 3013 /*DontDefer=*/false); 3014 return; 3015 } 3016 } else { 3017 const auto *VD = cast<VarDecl>(Global); 3018 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 3019 if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 3020 !Context.isMSStaticDataMemberInlineDefinition(VD)) { 3021 if (LangOpts.OpenMP) { 3022 // Emit declaration of the must-be-emitted declare target variable. 3023 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3024 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 3025 bool UnifiedMemoryEnabled = 3026 getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); 3027 if (*Res == OMPDeclareTargetDeclAttr::MT_To && 3028 !UnifiedMemoryEnabled) { 3029 (void)GetAddrOfGlobalVar(VD); 3030 } else { 3031 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 3032 (*Res == OMPDeclareTargetDeclAttr::MT_To && 3033 UnifiedMemoryEnabled)) && 3034 "Link clause or to clause with unified memory expected."); 3035 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 3036 } 3037 3038 return; 3039 } 3040 } 3041 // If this declaration may have caused an inline variable definition to 3042 // change linkage, make sure that it's emitted. 3043 if (Context.getInlineVariableDefinitionKind(VD) == 3044 ASTContext::InlineVariableDefinitionKind::Strong) 3045 GetAddrOfGlobalVar(VD); 3046 return; 3047 } 3048 } 3049 3050 // Defer code generation to first use when possible, e.g. if this is an inline 3051 // function. If the global must always be emitted, do it eagerly if possible 3052 // to benefit from cache locality. 3053 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 3054 // Emit the definition if it can't be deferred. 3055 EmitGlobalDefinition(GD); 3056 return; 3057 } 3058 3059 // If we're deferring emission of a C++ variable with an 3060 // initializer, remember the order in which it appeared in the file. 3061 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 3062 cast<VarDecl>(Global)->hasInit()) { 3063 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 3064 CXXGlobalInits.push_back(nullptr); 3065 } 3066 3067 StringRef MangledName = getMangledName(GD); 3068 if (GetGlobalValue(MangledName) != nullptr) { 3069 // The value has already been used and should therefore be emitted. 3070 addDeferredDeclToEmit(GD); 3071 } else if (MustBeEmitted(Global)) { 3072 // The value must be emitted, but cannot be emitted eagerly. 3073 assert(!MayBeEmittedEagerly(Global)); 3074 addDeferredDeclToEmit(GD); 3075 } else { 3076 // Otherwise, remember that we saw a deferred decl with this name. The 3077 // first use of the mangled name will cause it to move into 3078 // DeferredDeclsToEmit. 3079 DeferredDecls[MangledName] = GD; 3080 } 3081 } 3082 3083 // Check if T is a class type with a destructor that's not dllimport. 3084 static bool HasNonDllImportDtor(QualType T) { 3085 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 3086 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 3087 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 3088 return true; 3089 3090 return false; 3091 } 3092 3093 namespace { 3094 struct FunctionIsDirectlyRecursive 3095 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { 3096 const StringRef Name; 3097 const Builtin::Context &BI; 3098 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) 3099 : Name(N), BI(C) {} 3100 3101 bool VisitCallExpr(const CallExpr *E) { 3102 const FunctionDecl *FD = E->getDirectCallee(); 3103 if (!FD) 3104 return false; 3105 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3106 if (Attr && Name == Attr->getLabel()) 3107 return true; 3108 unsigned BuiltinID = FD->getBuiltinID(); 3109 if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 3110 return false; 3111 StringRef BuiltinName = BI.getName(BuiltinID); 3112 if (BuiltinName.startswith("__builtin_") && 3113 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 3114 return true; 3115 } 3116 return false; 3117 } 3118 3119 bool VisitStmt(const Stmt *S) { 3120 for (const Stmt *Child : S->children()) 3121 if (Child && this->Visit(Child)) 3122 return true; 3123 return false; 3124 } 3125 }; 3126 3127 // Make sure we're not referencing non-imported vars or functions. 3128 struct DLLImportFunctionVisitor 3129 : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 3130 bool SafeToInline = true; 3131 3132 bool shouldVisitImplicitCode() const { return true; } 3133 3134 bool VisitVarDecl(VarDecl *VD) { 3135 if (VD->getTLSKind()) { 3136 // A thread-local variable cannot be imported. 3137 SafeToInline = false; 3138 return SafeToInline; 3139 } 3140 3141 // A variable definition might imply a destructor call. 3142 if (VD->isThisDeclarationADefinition()) 3143 SafeToInline = !HasNonDllImportDtor(VD->getType()); 3144 3145 return SafeToInline; 3146 } 3147 3148 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 3149 if (const auto *D = E->getTemporary()->getDestructor()) 3150 SafeToInline = D->hasAttr<DLLImportAttr>(); 3151 return SafeToInline; 3152 } 3153 3154 bool VisitDeclRefExpr(DeclRefExpr *E) { 3155 ValueDecl *VD = E->getDecl(); 3156 if (isa<FunctionDecl>(VD)) 3157 SafeToInline = VD->hasAttr<DLLImportAttr>(); 3158 else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 3159 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 3160 return SafeToInline; 3161 } 3162 3163 bool VisitCXXConstructExpr(CXXConstructExpr *E) { 3164 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 3165 return SafeToInline; 3166 } 3167 3168 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3169 CXXMethodDecl *M = E->getMethodDecl(); 3170 if (!M) { 3171 // Call through a pointer to member function. This is safe to inline. 3172 SafeToInline = true; 3173 } else { 3174 SafeToInline = M->hasAttr<DLLImportAttr>(); 3175 } 3176 return SafeToInline; 3177 } 3178 3179 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 3180 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 3181 return SafeToInline; 3182 } 3183 3184 bool VisitCXXNewExpr(CXXNewExpr *E) { 3185 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 3186 return SafeToInline; 3187 } 3188 }; 3189 } 3190 3191 // isTriviallyRecursive - Check if this function calls another 3192 // decl that, because of the asm attribute or the other decl being a builtin, 3193 // ends up pointing to itself. 3194 bool 3195 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 3196 StringRef Name; 3197 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 3198 // asm labels are a special kind of mangling we have to support. 3199 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3200 if (!Attr) 3201 return false; 3202 Name = Attr->getLabel(); 3203 } else { 3204 Name = FD->getName(); 3205 } 3206 3207 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 3208 const Stmt *Body = FD->getBody(); 3209 return Body ? Walker.Visit(Body) : false; 3210 } 3211 3212 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 3213 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 3214 return true; 3215 const auto *F = cast<FunctionDecl>(GD.getDecl()); 3216 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 3217 return false; 3218 3219 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { 3220 // Check whether it would be safe to inline this dllimport function. 3221 DLLImportFunctionVisitor Visitor; 3222 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 3223 if (!Visitor.SafeToInline) 3224 return false; 3225 3226 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 3227 // Implicit destructor invocations aren't captured in the AST, so the 3228 // check above can't see them. Check for them manually here. 3229 for (const Decl *Member : Dtor->getParent()->decls()) 3230 if (isa<FieldDecl>(Member)) 3231 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 3232 return false; 3233 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 3234 if (HasNonDllImportDtor(B.getType())) 3235 return false; 3236 } 3237 } 3238 3239 // Inline builtins declaration must be emitted. They often are fortified 3240 // functions. 3241 if (F->isInlineBuiltinDeclaration()) 3242 return true; 3243 3244 // PR9614. Avoid cases where the source code is lying to us. An available 3245 // externally function should have an equivalent function somewhere else, 3246 // but a function that calls itself through asm label/`__builtin_` trickery is 3247 // clearly not equivalent to the real implementation. 3248 // This happens in glibc's btowc and in some configure checks. 3249 return !isTriviallyRecursive(F); 3250 } 3251 3252 bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 3253 return CodeGenOpts.OptimizationLevel > 0; 3254 } 3255 3256 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 3257 llvm::GlobalValue *GV) { 3258 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3259 3260 if (FD->isCPUSpecificMultiVersion()) { 3261 auto *Spec = FD->getAttr<CPUSpecificAttr>(); 3262 for (unsigned I = 0; I < Spec->cpus_size(); ++I) 3263 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 3264 // Requires multiple emits. 3265 } else if (FD->isTargetClonesMultiVersion()) { 3266 auto *Clone = FD->getAttr<TargetClonesAttr>(); 3267 for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I) 3268 if (Clone->isFirstOfVersion(I)) 3269 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 3270 EmitTargetClonesResolver(GD); 3271 } else 3272 EmitGlobalFunctionDefinition(GD, GV); 3273 } 3274 3275 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 3276 const auto *D = cast<ValueDecl>(GD.getDecl()); 3277 3278 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 3279 Context.getSourceManager(), 3280 "Generating code for declaration"); 3281 3282 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3283 // At -O0, don't generate IR for functions with available_externally 3284 // linkage. 3285 if (!shouldEmitFunction(GD)) 3286 return; 3287 3288 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { 3289 std::string Name; 3290 llvm::raw_string_ostream OS(Name); 3291 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), 3292 /*Qualified=*/true); 3293 return Name; 3294 }); 3295 3296 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 3297 // Make sure to emit the definition(s) before we emit the thunks. 3298 // This is necessary for the generation of certain thunks. 3299 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) 3300 ABI->emitCXXStructor(GD); 3301 else if (FD->isMultiVersion()) 3302 EmitMultiVersionFunctionDefinition(GD, GV); 3303 else 3304 EmitGlobalFunctionDefinition(GD, GV); 3305 3306 if (Method->isVirtual()) 3307 getVTables().EmitThunks(GD); 3308 3309 return; 3310 } 3311 3312 if (FD->isMultiVersion()) 3313 return EmitMultiVersionFunctionDefinition(GD, GV); 3314 return EmitGlobalFunctionDefinition(GD, GV); 3315 } 3316 3317 if (const auto *VD = dyn_cast<VarDecl>(D)) 3318 return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 3319 3320 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 3321 } 3322 3323 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 3324 llvm::Function *NewFn); 3325 3326 static unsigned 3327 TargetMVPriority(const TargetInfo &TI, 3328 const CodeGenFunction::MultiVersionResolverOption &RO) { 3329 unsigned Priority = 0; 3330 for (StringRef Feat : RO.Conditions.Features) 3331 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 3332 3333 if (!RO.Conditions.Architecture.empty()) 3334 Priority = std::max( 3335 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 3336 return Priority; 3337 } 3338 3339 // Multiversion functions should be at most 'WeakODRLinkage' so that a different 3340 // TU can forward declare the function without causing problems. Particularly 3341 // in the cases of CPUDispatch, this causes issues. This also makes sure we 3342 // work with internal linkage functions, so that the same function name can be 3343 // used with internal linkage in multiple TUs. 3344 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, 3345 GlobalDecl GD) { 3346 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 3347 if (FD->getFormalLinkage() == InternalLinkage) 3348 return llvm::GlobalValue::InternalLinkage; 3349 return llvm::GlobalValue::WeakODRLinkage; 3350 } 3351 3352 void CodeGenModule::EmitTargetClonesResolver(GlobalDecl GD) { 3353 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3354 assert(FD && "Not a FunctionDecl?"); 3355 const auto *TC = FD->getAttr<TargetClonesAttr>(); 3356 assert(TC && "Not a target_clones Function?"); 3357 3358 QualType CanonTy = Context.getCanonicalType(FD->getType()); 3359 llvm::Type *DeclTy = getTypes().ConvertType(CanonTy); 3360 3361 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 3362 const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD); 3363 DeclTy = getTypes().GetFunctionType(FInfo); 3364 } 3365 3366 llvm::Function *ResolverFunc; 3367 if (getTarget().supportsIFunc()) { 3368 auto *IFunc = cast<llvm::GlobalIFunc>( 3369 GetOrCreateMultiVersionResolver(GD, DeclTy, FD)); 3370 ResolverFunc = cast<llvm::Function>(IFunc->getResolver()); 3371 } else 3372 ResolverFunc = 3373 cast<llvm::Function>(GetOrCreateMultiVersionResolver(GD, DeclTy, FD)); 3374 3375 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3376 for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size(); 3377 ++VersionIndex) { 3378 if (!TC->isFirstOfVersion(VersionIndex)) 3379 continue; 3380 StringRef Version = TC->getFeatureStr(VersionIndex); 3381 StringRef MangledName = 3382 getMangledName(GD.getWithMultiVersionIndex(VersionIndex)); 3383 llvm::Constant *Func = GetGlobalValue(MangledName); 3384 assert(Func && 3385 "Should have already been created before calling resolver emit"); 3386 3387 StringRef Architecture; 3388 llvm::SmallVector<StringRef, 1> Feature; 3389 3390 if (Version.startswith("arch=")) 3391 Architecture = Version.drop_front(sizeof("arch=") - 1); 3392 else if (Version != "default") 3393 Feature.push_back(Version); 3394 3395 Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature); 3396 } 3397 3398 const TargetInfo &TI = getTarget(); 3399 std::stable_sort( 3400 Options.begin(), Options.end(), 3401 [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 3402 const CodeGenFunction::MultiVersionResolverOption &RHS) { 3403 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 3404 }); 3405 CodeGenFunction CGF(*this); 3406 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3407 } 3408 3409 void CodeGenModule::emitMultiVersionFunctions() { 3410 std::vector<GlobalDecl> MVFuncsToEmit; 3411 MultiVersionFuncs.swap(MVFuncsToEmit); 3412 for (GlobalDecl GD : MVFuncsToEmit) { 3413 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3414 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 3415 getContext().forEachMultiversionedFunctionVersion( 3416 FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 3417 GlobalDecl CurGD{ 3418 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 3419 StringRef MangledName = getMangledName(CurGD); 3420 llvm::Constant *Func = GetGlobalValue(MangledName); 3421 if (!Func) { 3422 if (CurFD->isDefined()) { 3423 EmitGlobalFunctionDefinition(CurGD, nullptr); 3424 Func = GetGlobalValue(MangledName); 3425 } else { 3426 const CGFunctionInfo &FI = 3427 getTypes().arrangeGlobalDeclaration(GD); 3428 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 3429 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 3430 /*DontDefer=*/false, ForDefinition); 3431 } 3432 assert(Func && "This should have just been created"); 3433 } 3434 3435 const auto *TA = CurFD->getAttr<TargetAttr>(); 3436 llvm::SmallVector<StringRef, 8> Feats; 3437 TA->getAddedFeatures(Feats); 3438 3439 Options.emplace_back(cast<llvm::Function>(Func), 3440 TA->getArchitecture(), Feats); 3441 }); 3442 3443 llvm::Function *ResolverFunc; 3444 const TargetInfo &TI = getTarget(); 3445 3446 if (TI.supportsIFunc() || FD->isTargetMultiVersion()) { 3447 ResolverFunc = cast<llvm::Function>( 3448 GetGlobalValue((getMangledName(GD) + ".resolver").str())); 3449 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 3450 } else { 3451 ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD))); 3452 } 3453 3454 if (supportsCOMDAT()) 3455 ResolverFunc->setComdat( 3456 getModule().getOrInsertComdat(ResolverFunc->getName())); 3457 3458 llvm::stable_sort( 3459 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 3460 const CodeGenFunction::MultiVersionResolverOption &RHS) { 3461 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 3462 }); 3463 CodeGenFunction CGF(*this); 3464 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3465 } 3466 3467 // Ensure that any additions to the deferred decls list caused by emitting a 3468 // variant are emitted. This can happen when the variant itself is inline and 3469 // calls a function without linkage. 3470 if (!MVFuncsToEmit.empty()) 3471 EmitDeferred(); 3472 3473 // Ensure that any additions to the multiversion funcs list from either the 3474 // deferred decls or the multiversion functions themselves are emitted. 3475 if (!MultiVersionFuncs.empty()) 3476 emitMultiVersionFunctions(); 3477 } 3478 3479 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 3480 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3481 assert(FD && "Not a FunctionDecl?"); 3482 const auto *DD = FD->getAttr<CPUDispatchAttr>(); 3483 assert(DD && "Not a cpu_dispatch Function?"); 3484 llvm::Type *DeclTy = getTypes().ConvertType(FD->getType()); 3485 3486 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 3487 const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD); 3488 DeclTy = getTypes().GetFunctionType(FInfo); 3489 } 3490 3491 StringRef ResolverName = getMangledName(GD); 3492 3493 llvm::Type *ResolverType; 3494 GlobalDecl ResolverGD; 3495 if (getTarget().supportsIFunc()) 3496 ResolverType = llvm::FunctionType::get( 3497 llvm::PointerType::get(DeclTy, 3498 Context.getTargetAddressSpace(FD->getType())), 3499 false); 3500 else { 3501 ResolverType = DeclTy; 3502 ResolverGD = GD; 3503 } 3504 3505 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 3506 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); 3507 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 3508 if (supportsCOMDAT()) 3509 ResolverFunc->setComdat( 3510 getModule().getOrInsertComdat(ResolverFunc->getName())); 3511 3512 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3513 const TargetInfo &Target = getTarget(); 3514 unsigned Index = 0; 3515 for (const IdentifierInfo *II : DD->cpus()) { 3516 // Get the name of the target function so we can look it up/create it. 3517 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 3518 getCPUSpecificMangling(*this, II->getName()); 3519 3520 llvm::Constant *Func = GetGlobalValue(MangledName); 3521 3522 if (!Func) { 3523 GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 3524 if (ExistingDecl.getDecl() && 3525 ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 3526 EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 3527 Func = GetGlobalValue(MangledName); 3528 } else { 3529 if (!ExistingDecl.getDecl()) 3530 ExistingDecl = GD.getWithMultiVersionIndex(Index); 3531 3532 Func = GetOrCreateLLVMFunction( 3533 MangledName, DeclTy, ExistingDecl, 3534 /*ForVTable=*/false, /*DontDefer=*/true, 3535 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 3536 } 3537 } 3538 3539 llvm::SmallVector<StringRef, 32> Features; 3540 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 3541 llvm::transform(Features, Features.begin(), 3542 [](StringRef Str) { return Str.substr(1); }); 3543 llvm::erase_if(Features, [&Target](StringRef Feat) { 3544 return !Target.validateCpuSupports(Feat); 3545 }); 3546 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 3547 ++Index; 3548 } 3549 3550 llvm::stable_sort( 3551 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 3552 const CodeGenFunction::MultiVersionResolverOption &RHS) { 3553 return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) > 3554 llvm::X86::getCpuSupportsMask(RHS.Conditions.Features); 3555 }); 3556 3557 // If the list contains multiple 'default' versions, such as when it contains 3558 // 'pentium' and 'generic', don't emit the call to the generic one (since we 3559 // always run on at least a 'pentium'). We do this by deleting the 'least 3560 // advanced' (read, lowest mangling letter). 3561 while (Options.size() > 1 && 3562 llvm::X86::getCpuSupportsMask( 3563 (Options.end() - 2)->Conditions.Features) == 0) { 3564 StringRef LHSName = (Options.end() - 2)->Function->getName(); 3565 StringRef RHSName = (Options.end() - 1)->Function->getName(); 3566 if (LHSName.compare(RHSName) < 0) 3567 Options.erase(Options.end() - 2); 3568 else 3569 Options.erase(Options.end() - 1); 3570 } 3571 3572 CodeGenFunction CGF(*this); 3573 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3574 3575 if (getTarget().supportsIFunc()) { 3576 std::string AliasName = getMangledNameImpl( 3577 *this, GD, FD, /*OmitMultiVersionMangling=*/true); 3578 llvm::Constant *AliasFunc = GetGlobalValue(AliasName); 3579 if (!AliasFunc) { 3580 auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction( 3581 AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true, 3582 /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition)); 3583 auto *GA = llvm::GlobalAlias::create(DeclTy, 0, 3584 getMultiversionLinkage(*this, GD), 3585 AliasName, IFunc, &getModule()); 3586 SetCommonAttributes(GD, GA); 3587 } 3588 } 3589 } 3590 3591 /// If a dispatcher for the specified mangled name is not in the module, create 3592 /// and return an llvm Function with the specified type. 3593 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver( 3594 GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) { 3595 std::string MangledName = 3596 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 3597 3598 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 3599 // a separate resolver). 3600 std::string ResolverName = MangledName; 3601 if (getTarget().supportsIFunc()) 3602 ResolverName += ".ifunc"; 3603 else if (FD->isTargetMultiVersion()) 3604 ResolverName += ".resolver"; 3605 3606 // If this already exists, just return that one. 3607 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 3608 return ResolverGV; 3609 3610 // Since this is the first time we've created this IFunc, make sure 3611 // that we put this multiversioned function into the list to be 3612 // replaced later if necessary (target multiversioning only). 3613 if (FD->isTargetMultiVersion()) 3614 MultiVersionFuncs.push_back(GD); 3615 else if (FD->isTargetClonesMultiVersion()) { 3616 // In target_clones multiversioning, make sure we emit this if used. 3617 auto DDI = 3618 DeferredDecls.find(getMangledName(GD.getWithMultiVersionIndex(0))); 3619 if (DDI != DeferredDecls.end()) { 3620 addDeferredDeclToEmit(GD); 3621 DeferredDecls.erase(DDI); 3622 } else { 3623 // Emit the symbol of the 1st variant, so that the deferred decls know we 3624 // need it, otherwise the only global value will be the resolver/ifunc, 3625 // which end up getting broken if we search for them with GetGlobalValue'. 3626 GetOrCreateLLVMFunction( 3627 getMangledName(GD.getWithMultiVersionIndex(0)), DeclTy, FD, 3628 /*ForVTable=*/false, /*DontDefer=*/true, 3629 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 3630 } 3631 } 3632 3633 if (getTarget().supportsIFunc()) { 3634 llvm::Type *ResolverType = llvm::FunctionType::get( 3635 llvm::PointerType::get( 3636 DeclTy, getContext().getTargetAddressSpace(FD->getType())), 3637 false); 3638 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3639 MangledName + ".resolver", ResolverType, GlobalDecl{}, 3640 /*ForVTable=*/false); 3641 llvm::GlobalIFunc *GIF = 3642 llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD), 3643 "", Resolver, &getModule()); 3644 GIF->setName(ResolverName); 3645 SetCommonAttributes(FD, GIF); 3646 3647 return GIF; 3648 } 3649 3650 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3651 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 3652 assert(isa<llvm::GlobalValue>(Resolver) && 3653 "Resolver should be created for the first time"); 3654 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 3655 return Resolver; 3656 } 3657 3658 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 3659 /// module, create and return an llvm Function with the specified type. If there 3660 /// is something in the module with the specified name, return it potentially 3661 /// bitcasted to the right type. 3662 /// 3663 /// If D is non-null, it specifies a decl that correspond to this. This is used 3664 /// to set the attributes on the function when it is first created. 3665 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 3666 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 3667 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 3668 ForDefinition_t IsForDefinition) { 3669 const Decl *D = GD.getDecl(); 3670 3671 // Any attempts to use a MultiVersion function should result in retrieving 3672 // the iFunc instead. Name Mangling will handle the rest of the changes. 3673 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 3674 // For the device mark the function as one that should be emitted. 3675 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime && 3676 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 3677 !DontDefer && !IsForDefinition) { 3678 if (const FunctionDecl *FDDef = FD->getDefinition()) { 3679 GlobalDecl GDDef; 3680 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 3681 GDDef = GlobalDecl(CD, GD.getCtorType()); 3682 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 3683 GDDef = GlobalDecl(DD, GD.getDtorType()); 3684 else 3685 GDDef = GlobalDecl(FDDef); 3686 EmitGlobal(GDDef); 3687 } 3688 } 3689 3690 if (FD->isMultiVersion()) { 3691 if (FD->hasAttr<TargetAttr>()) 3692 UpdateMultiVersionNames(GD, FD); 3693 if (!IsForDefinition) 3694 return GetOrCreateMultiVersionResolver(GD, Ty, FD); 3695 } 3696 } 3697 3698 // Lookup the entry, lazily creating it if necessary. 3699 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3700 if (Entry) { 3701 if (WeakRefReferences.erase(Entry)) { 3702 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 3703 if (FD && !FD->hasAttr<WeakAttr>()) 3704 Entry->setLinkage(llvm::Function::ExternalLinkage); 3705 } 3706 3707 // Handle dropped DLL attributes. 3708 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) { 3709 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 3710 setDSOLocal(Entry); 3711 } 3712 3713 // If there are two attempts to define the same mangled name, issue an 3714 // error. 3715 if (IsForDefinition && !Entry->isDeclaration()) { 3716 GlobalDecl OtherGD; 3717 // Check that GD is not yet in DiagnosedConflictingDefinitions is required 3718 // to make sure that we issue an error only once. 3719 if (lookupRepresentativeDecl(MangledName, OtherGD) && 3720 (GD.getCanonicalDecl().getDecl() != 3721 OtherGD.getCanonicalDecl().getDecl()) && 3722 DiagnosedConflictingDefinitions.insert(GD).second) { 3723 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 3724 << MangledName; 3725 getDiags().Report(OtherGD.getDecl()->getLocation(), 3726 diag::note_previous_definition); 3727 } 3728 } 3729 3730 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 3731 (Entry->getValueType() == Ty)) { 3732 return Entry; 3733 } 3734 3735 // Make sure the result is of the correct type. 3736 // (If function is requested for a definition, we always need to create a new 3737 // function, not just return a bitcast.) 3738 if (!IsForDefinition) 3739 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 3740 } 3741 3742 // This function doesn't have a complete type (for example, the return 3743 // type is an incomplete struct). Use a fake type instead, and make 3744 // sure not to try to set attributes. 3745 bool IsIncompleteFunction = false; 3746 3747 llvm::FunctionType *FTy; 3748 if (isa<llvm::FunctionType>(Ty)) { 3749 FTy = cast<llvm::FunctionType>(Ty); 3750 } else { 3751 FTy = llvm::FunctionType::get(VoidTy, false); 3752 IsIncompleteFunction = true; 3753 } 3754 3755 llvm::Function *F = 3756 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 3757 Entry ? StringRef() : MangledName, &getModule()); 3758 3759 // If we already created a function with the same mangled name (but different 3760 // type) before, take its name and add it to the list of functions to be 3761 // replaced with F at the end of CodeGen. 3762 // 3763 // This happens if there is a prototype for a function (e.g. "int f()") and 3764 // then a definition of a different type (e.g. "int f(int x)"). 3765 if (Entry) { 3766 F->takeName(Entry); 3767 3768 // This might be an implementation of a function without a prototype, in 3769 // which case, try to do special replacement of calls which match the new 3770 // prototype. The really key thing here is that we also potentially drop 3771 // arguments from the call site so as to make a direct call, which makes the 3772 // inliner happier and suppresses a number of optimizer warnings (!) about 3773 // dropping arguments. 3774 if (!Entry->use_empty()) { 3775 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 3776 Entry->removeDeadConstantUsers(); 3777 } 3778 3779 llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 3780 F, Entry->getValueType()->getPointerTo()); 3781 addGlobalValReplacement(Entry, BC); 3782 } 3783 3784 assert(F->getName() == MangledName && "name was uniqued!"); 3785 if (D) 3786 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 3787 if (ExtraAttrs.hasFnAttrs()) { 3788 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex); 3789 F->addFnAttrs(B); 3790 } 3791 3792 if (!DontDefer) { 3793 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 3794 // each other bottoming out with the base dtor. Therefore we emit non-base 3795 // dtors on usage, even if there is no dtor definition in the TU. 3796 if (D && isa<CXXDestructorDecl>(D) && 3797 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 3798 GD.getDtorType())) 3799 addDeferredDeclToEmit(GD); 3800 3801 // This is the first use or definition of a mangled name. If there is a 3802 // deferred decl with this name, remember that we need to emit it at the end 3803 // of the file. 3804 auto DDI = DeferredDecls.find(MangledName); 3805 if (DDI != DeferredDecls.end()) { 3806 // Move the potentially referenced deferred decl to the 3807 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 3808 // don't need it anymore). 3809 addDeferredDeclToEmit(DDI->second); 3810 DeferredDecls.erase(DDI); 3811 3812 // Otherwise, there are cases we have to worry about where we're 3813 // using a declaration for which we must emit a definition but where 3814 // we might not find a top-level definition: 3815 // - member functions defined inline in their classes 3816 // - friend functions defined inline in some class 3817 // - special member functions with implicit definitions 3818 // If we ever change our AST traversal to walk into class methods, 3819 // this will be unnecessary. 3820 // 3821 // We also don't emit a definition for a function if it's going to be an 3822 // entry in a vtable, unless it's already marked as used. 3823 } else if (getLangOpts().CPlusPlus && D) { 3824 // Look for a declaration that's lexically in a record. 3825 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 3826 FD = FD->getPreviousDecl()) { 3827 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 3828 if (FD->doesThisDeclarationHaveABody()) { 3829 addDeferredDeclToEmit(GD.getWithDecl(FD)); 3830 break; 3831 } 3832 } 3833 } 3834 } 3835 } 3836 3837 // Make sure the result is of the requested type. 3838 if (!IsIncompleteFunction) { 3839 assert(F->getFunctionType() == Ty); 3840 return F; 3841 } 3842 3843 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 3844 return llvm::ConstantExpr::getBitCast(F, PTy); 3845 } 3846 3847 /// GetAddrOfFunction - Return the address of the given function. If Ty is 3848 /// non-null, then this function will use the specified type if it has to 3849 /// create it (this occurs when we see a definition of the function). 3850 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 3851 llvm::Type *Ty, 3852 bool ForVTable, 3853 bool DontDefer, 3854 ForDefinition_t IsForDefinition) { 3855 assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() && 3856 "consteval function should never be emitted"); 3857 // If there was no specific requested type, just convert it now. 3858 if (!Ty) { 3859 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3860 Ty = getTypes().ConvertType(FD->getType()); 3861 } 3862 3863 // Devirtualized destructor calls may come through here instead of via 3864 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 3865 // of the complete destructor when necessary. 3866 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 3867 if (getTarget().getCXXABI().isMicrosoft() && 3868 GD.getDtorType() == Dtor_Complete && 3869 DD->getParent()->getNumVBases() == 0) 3870 GD = GlobalDecl(DD, Dtor_Base); 3871 } 3872 3873 StringRef MangledName = getMangledName(GD); 3874 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 3875 /*IsThunk=*/false, llvm::AttributeList(), 3876 IsForDefinition); 3877 // Returns kernel handle for HIP kernel stub function. 3878 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice && 3879 cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) { 3880 auto *Handle = getCUDARuntime().getKernelHandle( 3881 cast<llvm::Function>(F->stripPointerCasts()), GD); 3882 if (IsForDefinition) 3883 return F; 3884 return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo()); 3885 } 3886 return F; 3887 } 3888 3889 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) { 3890 llvm::GlobalValue *F = 3891 cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts()); 3892 3893 return llvm::ConstantExpr::getBitCast(llvm::NoCFIValue::get(F), 3894 llvm::Type::getInt8PtrTy(VMContext)); 3895 } 3896 3897 static const FunctionDecl * 3898 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 3899 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 3900 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3901 3902 IdentifierInfo &CII = C.Idents.get(Name); 3903 for (const auto *Result : DC->lookup(&CII)) 3904 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 3905 return FD; 3906 3907 if (!C.getLangOpts().CPlusPlus) 3908 return nullptr; 3909 3910 // Demangle the premangled name from getTerminateFn() 3911 IdentifierInfo &CXXII = 3912 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 3913 ? C.Idents.get("terminate") 3914 : C.Idents.get(Name); 3915 3916 for (const auto &N : {"__cxxabiv1", "std"}) { 3917 IdentifierInfo &NS = C.Idents.get(N); 3918 for (const auto *Result : DC->lookup(&NS)) { 3919 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 3920 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result)) 3921 for (const auto *Result : LSD->lookup(&NS)) 3922 if ((ND = dyn_cast<NamespaceDecl>(Result))) 3923 break; 3924 3925 if (ND) 3926 for (const auto *Result : ND->lookup(&CXXII)) 3927 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 3928 return FD; 3929 } 3930 } 3931 3932 return nullptr; 3933 } 3934 3935 /// CreateRuntimeFunction - Create a new runtime function with the specified 3936 /// type and name. 3937 llvm::FunctionCallee 3938 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 3939 llvm::AttributeList ExtraAttrs, bool Local, 3940 bool AssumeConvergent) { 3941 if (AssumeConvergent) { 3942 ExtraAttrs = 3943 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent); 3944 } 3945 3946 llvm::Constant *C = 3947 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 3948 /*DontDefer=*/false, /*IsThunk=*/false, 3949 ExtraAttrs); 3950 3951 if (auto *F = dyn_cast<llvm::Function>(C)) { 3952 if (F->empty()) { 3953 F->setCallingConv(getRuntimeCC()); 3954 3955 // In Windows Itanium environments, try to mark runtime functions 3956 // dllimport. For Mingw and MSVC, don't. We don't really know if the user 3957 // will link their standard library statically or dynamically. Marking 3958 // functions imported when they are not imported can cause linker errors 3959 // and warnings. 3960 if (!Local && getTriple().isWindowsItaniumEnvironment() && 3961 !getCodeGenOpts().LTOVisibilityPublicStd) { 3962 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 3963 if (!FD || FD->hasAttr<DLLImportAttr>()) { 3964 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3965 F->setLinkage(llvm::GlobalValue::ExternalLinkage); 3966 } 3967 } 3968 setDSOLocal(F); 3969 } 3970 } 3971 3972 return {FTy, C}; 3973 } 3974 3975 /// isTypeConstant - Determine whether an object of this type can be emitted 3976 /// as a constant. 3977 /// 3978 /// If ExcludeCtor is true, the duration when the object's constructor runs 3979 /// will not be considered. The caller will need to verify that the object is 3980 /// not written to during its construction. 3981 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 3982 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 3983 return false; 3984 3985 if (Context.getLangOpts().CPlusPlus) { 3986 if (const CXXRecordDecl *Record 3987 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 3988 return ExcludeCtor && !Record->hasMutableFields() && 3989 Record->hasTrivialDestructor(); 3990 } 3991 3992 return true; 3993 } 3994 3995 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 3996 /// create and return an llvm GlobalVariable with the specified type and address 3997 /// space. If there is something in the module with the specified name, return 3998 /// it potentially bitcasted to the right type. 3999 /// 4000 /// If D is non-null, it specifies a decl that correspond to this. This is used 4001 /// to set the attributes on the global when it is first created. 4002 /// 4003 /// If IsForDefinition is true, it is guaranteed that an actual global with 4004 /// type Ty will be returned, not conversion of a variable with the same 4005 /// mangled name but some other type. 4006 llvm::Constant * 4007 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, 4008 LangAS AddrSpace, const VarDecl *D, 4009 ForDefinition_t IsForDefinition) { 4010 // Lookup the entry, lazily creating it if necessary. 4011 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4012 unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace); 4013 if (Entry) { 4014 if (WeakRefReferences.erase(Entry)) { 4015 if (D && !D->hasAttr<WeakAttr>()) 4016 Entry->setLinkage(llvm::Function::ExternalLinkage); 4017 } 4018 4019 // Handle dropped DLL attributes. 4020 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 4021 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 4022 4023 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 4024 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 4025 4026 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) 4027 return Entry; 4028 4029 // If there are two attempts to define the same mangled name, issue an 4030 // error. 4031 if (IsForDefinition && !Entry->isDeclaration()) { 4032 GlobalDecl OtherGD; 4033 const VarDecl *OtherD; 4034 4035 // Check that D is not yet in DiagnosedConflictingDefinitions is required 4036 // to make sure that we issue an error only once. 4037 if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 4038 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 4039 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 4040 OtherD->hasInit() && 4041 DiagnosedConflictingDefinitions.insert(D).second) { 4042 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 4043 << MangledName; 4044 getDiags().Report(OtherGD.getDecl()->getLocation(), 4045 diag::note_previous_definition); 4046 } 4047 } 4048 4049 // Make sure the result is of the correct type. 4050 if (Entry->getType()->getAddressSpace() != TargetAS) { 4051 return llvm::ConstantExpr::getAddrSpaceCast(Entry, 4052 Ty->getPointerTo(TargetAS)); 4053 } 4054 4055 // (If global is requested for a definition, we always need to create a new 4056 // global, not just return a bitcast.) 4057 if (!IsForDefinition) 4058 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS)); 4059 } 4060 4061 auto DAddrSpace = GetGlobalVarAddressSpace(D); 4062 4063 auto *GV = new llvm::GlobalVariable( 4064 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, 4065 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, 4066 getContext().getTargetAddressSpace(DAddrSpace)); 4067 4068 // If we already created a global with the same mangled name (but different 4069 // type) before, take its name and remove it from its parent. 4070 if (Entry) { 4071 GV->takeName(Entry); 4072 4073 if (!Entry->use_empty()) { 4074 llvm::Constant *NewPtrForOldDecl = 4075 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 4076 Entry->replaceAllUsesWith(NewPtrForOldDecl); 4077 } 4078 4079 Entry->eraseFromParent(); 4080 } 4081 4082 // This is the first use or definition of a mangled name. If there is a 4083 // deferred decl with this name, remember that we need to emit it at the end 4084 // of the file. 4085 auto DDI = DeferredDecls.find(MangledName); 4086 if (DDI != DeferredDecls.end()) { 4087 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 4088 // list, and remove it from DeferredDecls (since we don't need it anymore). 4089 addDeferredDeclToEmit(DDI->second); 4090 DeferredDecls.erase(DDI); 4091 } 4092 4093 // Handle things which are present even on external declarations. 4094 if (D) { 4095 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 4096 getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 4097 4098 // FIXME: This code is overly simple and should be merged with other global 4099 // handling. 4100 GV->setConstant(isTypeConstant(D->getType(), false)); 4101 4102 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4103 4104 setLinkageForGV(GV, D); 4105 4106 if (D->getTLSKind()) { 4107 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4108 CXXThreadLocals.push_back(D); 4109 setTLSMode(GV, *D); 4110 } 4111 4112 setGVProperties(GV, D); 4113 4114 // If required by the ABI, treat declarations of static data members with 4115 // inline initializers as definitions. 4116 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 4117 EmitGlobalVarDefinition(D); 4118 } 4119 4120 // Emit section information for extern variables. 4121 if (D->hasExternalStorage()) { 4122 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 4123 GV->setSection(SA->getName()); 4124 } 4125 4126 // Handle XCore specific ABI requirements. 4127 if (getTriple().getArch() == llvm::Triple::xcore && 4128 D->getLanguageLinkage() == CLanguageLinkage && 4129 D->getType().isConstant(Context) && 4130 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 4131 GV->setSection(".cp.rodata"); 4132 4133 // Check if we a have a const declaration with an initializer, we may be 4134 // able to emit it as available_externally to expose it's value to the 4135 // optimizer. 4136 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 4137 D->getType().isConstQualified() && !GV->hasInitializer() && 4138 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 4139 const auto *Record = 4140 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 4141 bool HasMutableFields = Record && Record->hasMutableFields(); 4142 if (!HasMutableFields) { 4143 const VarDecl *InitDecl; 4144 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4145 if (InitExpr) { 4146 ConstantEmitter emitter(*this); 4147 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 4148 if (Init) { 4149 auto *InitType = Init->getType(); 4150 if (GV->getValueType() != InitType) { 4151 // The type of the initializer does not match the definition. 4152 // This happens when an initializer has a different type from 4153 // the type of the global (because of padding at the end of a 4154 // structure for instance). 4155 GV->setName(StringRef()); 4156 // Make a new global with the correct type, this is now guaranteed 4157 // to work. 4158 auto *NewGV = cast<llvm::GlobalVariable>( 4159 GetAddrOfGlobalVar(D, InitType, IsForDefinition) 4160 ->stripPointerCasts()); 4161 4162 // Erase the old global, since it is no longer used. 4163 GV->eraseFromParent(); 4164 GV = NewGV; 4165 } else { 4166 GV->setInitializer(Init); 4167 GV->setConstant(true); 4168 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 4169 } 4170 emitter.finalize(GV); 4171 } 4172 } 4173 } 4174 } 4175 } 4176 4177 if (GV->isDeclaration()) { 4178 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 4179 // External HIP managed variables needed to be recorded for transformation 4180 // in both device and host compilations. 4181 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && 4182 D->hasExternalStorage()) 4183 getCUDARuntime().handleVarRegistration(D, *GV); 4184 } 4185 4186 LangAS ExpectedAS = 4187 D ? D->getType().getAddressSpace() 4188 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 4189 assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); 4190 if (DAddrSpace != ExpectedAS) { 4191 return getTargetCodeGenInfo().performAddrSpaceCast( 4192 *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS)); 4193 } 4194 4195 return GV; 4196 } 4197 4198 llvm::Constant * 4199 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 4200 const Decl *D = GD.getDecl(); 4201 4202 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 4203 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 4204 /*DontDefer=*/false, IsForDefinition); 4205 4206 if (isa<CXXMethodDecl>(D)) { 4207 auto FInfo = 4208 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 4209 auto Ty = getTypes().GetFunctionType(*FInfo); 4210 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4211 IsForDefinition); 4212 } 4213 4214 if (isa<FunctionDecl>(D)) { 4215 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4216 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4217 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4218 IsForDefinition); 4219 } 4220 4221 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 4222 } 4223 4224 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 4225 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 4226 unsigned Alignment) { 4227 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 4228 llvm::GlobalVariable *OldGV = nullptr; 4229 4230 if (GV) { 4231 // Check if the variable has the right type. 4232 if (GV->getValueType() == Ty) 4233 return GV; 4234 4235 // Because C++ name mangling, the only way we can end up with an already 4236 // existing global with the same name is if it has been declared extern "C". 4237 assert(GV->isDeclaration() && "Declaration has wrong type!"); 4238 OldGV = GV; 4239 } 4240 4241 // Create a new variable. 4242 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 4243 Linkage, nullptr, Name); 4244 4245 if (OldGV) { 4246 // Replace occurrences of the old variable if needed. 4247 GV->takeName(OldGV); 4248 4249 if (!OldGV->use_empty()) { 4250 llvm::Constant *NewPtrForOldDecl = 4251 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 4252 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 4253 } 4254 4255 OldGV->eraseFromParent(); 4256 } 4257 4258 if (supportsCOMDAT() && GV->isWeakForLinker() && 4259 !GV->hasAvailableExternallyLinkage()) 4260 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 4261 4262 GV->setAlignment(llvm::MaybeAlign(Alignment)); 4263 4264 return GV; 4265 } 4266 4267 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 4268 /// given global variable. If Ty is non-null and if the global doesn't exist, 4269 /// then it will be created with the specified type instead of whatever the 4270 /// normal requested type would be. If IsForDefinition is true, it is guaranteed 4271 /// that an actual global with type Ty will be returned, not conversion of a 4272 /// variable with the same mangled name but some other type. 4273 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 4274 llvm::Type *Ty, 4275 ForDefinition_t IsForDefinition) { 4276 assert(D->hasGlobalStorage() && "Not a global variable"); 4277 QualType ASTTy = D->getType(); 4278 if (!Ty) 4279 Ty = getTypes().ConvertTypeForMem(ASTTy); 4280 4281 StringRef MangledName = getMangledName(D); 4282 return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D, 4283 IsForDefinition); 4284 } 4285 4286 /// CreateRuntimeVariable - Create a new runtime global variable with the 4287 /// specified type and name. 4288 llvm::Constant * 4289 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 4290 StringRef Name) { 4291 LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global 4292 : LangAS::Default; 4293 auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr); 4294 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 4295 return Ret; 4296 } 4297 4298 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 4299 assert(!D->getInit() && "Cannot emit definite definitions here!"); 4300 4301 StringRef MangledName = getMangledName(D); 4302 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 4303 4304 // We already have a definition, not declaration, with the same mangled name. 4305 // Emitting of declaration is not required (and actually overwrites emitted 4306 // definition). 4307 if (GV && !GV->isDeclaration()) 4308 return; 4309 4310 // If we have not seen a reference to this variable yet, place it into the 4311 // deferred declarations table to be emitted if needed later. 4312 if (!MustBeEmitted(D) && !GV) { 4313 DeferredDecls[MangledName] = D; 4314 return; 4315 } 4316 4317 // The tentative definition is the only definition. 4318 EmitGlobalVarDefinition(D); 4319 } 4320 4321 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 4322 EmitExternalVarDeclaration(D); 4323 } 4324 4325 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 4326 return Context.toCharUnitsFromBits( 4327 getDataLayout().getTypeStoreSizeInBits(Ty)); 4328 } 4329 4330 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 4331 if (LangOpts.OpenCL) { 4332 LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 4333 assert(AS == LangAS::opencl_global || 4334 AS == LangAS::opencl_global_device || 4335 AS == LangAS::opencl_global_host || 4336 AS == LangAS::opencl_constant || 4337 AS == LangAS::opencl_local || 4338 AS >= LangAS::FirstTargetAddressSpace); 4339 return AS; 4340 } 4341 4342 if (LangOpts.SYCLIsDevice && 4343 (!D || D->getType().getAddressSpace() == LangAS::Default)) 4344 return LangAS::sycl_global; 4345 4346 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 4347 if (D && D->hasAttr<CUDAConstantAttr>()) 4348 return LangAS::cuda_constant; 4349 else if (D && D->hasAttr<CUDASharedAttr>()) 4350 return LangAS::cuda_shared; 4351 else if (D && D->hasAttr<CUDADeviceAttr>()) 4352 return LangAS::cuda_device; 4353 else if (D && D->getType().isConstQualified()) 4354 return LangAS::cuda_constant; 4355 else 4356 return LangAS::cuda_device; 4357 } 4358 4359 if (LangOpts.OpenMP) { 4360 LangAS AS; 4361 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 4362 return AS; 4363 } 4364 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 4365 } 4366 4367 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { 4368 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 4369 if (LangOpts.OpenCL) 4370 return LangAS::opencl_constant; 4371 if (LangOpts.SYCLIsDevice) 4372 return LangAS::sycl_global; 4373 if (auto AS = getTarget().getConstantAddressSpace()) 4374 return AS.getValue(); 4375 return LangAS::Default; 4376 } 4377 4378 // In address space agnostic languages, string literals are in default address 4379 // space in AST. However, certain targets (e.g. amdgcn) request them to be 4380 // emitted in constant address space in LLVM IR. To be consistent with other 4381 // parts of AST, string literal global variables in constant address space 4382 // need to be casted to default address space before being put into address 4383 // map and referenced by other part of CodeGen. 4384 // In OpenCL, string literals are in constant address space in AST, therefore 4385 // they should not be casted to default address space. 4386 static llvm::Constant * 4387 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 4388 llvm::GlobalVariable *GV) { 4389 llvm::Constant *Cast = GV; 4390 if (!CGM.getLangOpts().OpenCL) { 4391 auto AS = CGM.GetGlobalConstantAddressSpace(); 4392 if (AS != LangAS::Default) 4393 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 4394 CGM, GV, AS, LangAS::Default, 4395 GV->getValueType()->getPointerTo( 4396 CGM.getContext().getTargetAddressSpace(LangAS::Default))); 4397 } 4398 return Cast; 4399 } 4400 4401 template<typename SomeDecl> 4402 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 4403 llvm::GlobalValue *GV) { 4404 if (!getLangOpts().CPlusPlus) 4405 return; 4406 4407 // Must have 'used' attribute, or else inline assembly can't rely on 4408 // the name existing. 4409 if (!D->template hasAttr<UsedAttr>()) 4410 return; 4411 4412 // Must have internal linkage and an ordinary name. 4413 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 4414 return; 4415 4416 // Must be in an extern "C" context. Entities declared directly within 4417 // a record are not extern "C" even if the record is in such a context. 4418 const SomeDecl *First = D->getFirstDecl(); 4419 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 4420 return; 4421 4422 // OK, this is an internal linkage entity inside an extern "C" linkage 4423 // specification. Make a note of that so we can give it the "expected" 4424 // mangled name if nothing else is using that name. 4425 std::pair<StaticExternCMap::iterator, bool> R = 4426 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 4427 4428 // If we have multiple internal linkage entities with the same name 4429 // in extern "C" regions, none of them gets that name. 4430 if (!R.second) 4431 R.first->second = nullptr; 4432 } 4433 4434 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 4435 if (!CGM.supportsCOMDAT()) 4436 return false; 4437 4438 if (D.hasAttr<SelectAnyAttr>()) 4439 return true; 4440 4441 GVALinkage Linkage; 4442 if (auto *VD = dyn_cast<VarDecl>(&D)) 4443 Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 4444 else 4445 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 4446 4447 switch (Linkage) { 4448 case GVA_Internal: 4449 case GVA_AvailableExternally: 4450 case GVA_StrongExternal: 4451 return false; 4452 case GVA_DiscardableODR: 4453 case GVA_StrongODR: 4454 return true; 4455 } 4456 llvm_unreachable("No such linkage"); 4457 } 4458 4459 void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 4460 llvm::GlobalObject &GO) { 4461 if (!shouldBeInCOMDAT(*this, D)) 4462 return; 4463 GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 4464 } 4465 4466 /// Pass IsTentative as true if you want to create a tentative definition. 4467 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 4468 bool IsTentative) { 4469 // OpenCL global variables of sampler type are translated to function calls, 4470 // therefore no need to be translated. 4471 QualType ASTTy = D->getType(); 4472 if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 4473 return; 4474 4475 // If this is OpenMP device, check if it is legal to emit this global 4476 // normally. 4477 if (LangOpts.OpenMPIsDevice && OpenMPRuntime && 4478 OpenMPRuntime->emitTargetGlobalVariable(D)) 4479 return; 4480 4481 llvm::TrackingVH<llvm::Constant> Init; 4482 bool NeedsGlobalCtor = false; 4483 bool NeedsGlobalDtor = 4484 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 4485 4486 const VarDecl *InitDecl; 4487 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4488 4489 Optional<ConstantEmitter> emitter; 4490 4491 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 4492 // as part of their declaration." Sema has already checked for 4493 // error cases, so we just need to set Init to UndefValue. 4494 bool IsCUDASharedVar = 4495 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 4496 // Shadows of initialized device-side global variables are also left 4497 // undefined. 4498 // Managed Variables should be initialized on both host side and device side. 4499 bool IsCUDAShadowVar = 4500 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4501 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 4502 D->hasAttr<CUDASharedAttr>()); 4503 bool IsCUDADeviceShadowVar = 4504 getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4505 (D->getType()->isCUDADeviceBuiltinSurfaceType() || 4506 D->getType()->isCUDADeviceBuiltinTextureType()); 4507 if (getLangOpts().CUDA && 4508 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) 4509 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 4510 else if (D->hasAttr<LoaderUninitializedAttr>()) 4511 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 4512 else if (!InitExpr) { 4513 // This is a tentative definition; tentative definitions are 4514 // implicitly initialized with { 0 }. 4515 // 4516 // Note that tentative definitions are only emitted at the end of 4517 // a translation unit, so they should never have incomplete 4518 // type. In addition, EmitTentativeDefinition makes sure that we 4519 // never attempt to emit a tentative definition if a real one 4520 // exists. A use may still exists, however, so we still may need 4521 // to do a RAUW. 4522 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 4523 Init = EmitNullConstant(D->getType()); 4524 } else { 4525 initializedGlobalDecl = GlobalDecl(D); 4526 emitter.emplace(*this); 4527 llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl); 4528 if (!Initializer) { 4529 QualType T = InitExpr->getType(); 4530 if (D->getType()->isReferenceType()) 4531 T = D->getType(); 4532 4533 if (getLangOpts().CPlusPlus) { 4534 Init = EmitNullConstant(T); 4535 NeedsGlobalCtor = true; 4536 } else { 4537 ErrorUnsupported(D, "static initializer"); 4538 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 4539 } 4540 } else { 4541 Init = Initializer; 4542 // We don't need an initializer, so remove the entry for the delayed 4543 // initializer position (just in case this entry was delayed) if we 4544 // also don't need to register a destructor. 4545 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 4546 DelayedCXXInitPosition.erase(D); 4547 } 4548 } 4549 4550 llvm::Type* InitType = Init->getType(); 4551 llvm::Constant *Entry = 4552 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 4553 4554 // Strip off pointer casts if we got them. 4555 Entry = Entry->stripPointerCasts(); 4556 4557 // Entry is now either a Function or GlobalVariable. 4558 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 4559 4560 // We have a definition after a declaration with the wrong type. 4561 // We must make a new GlobalVariable* and update everything that used OldGV 4562 // (a declaration or tentative definition) with the new GlobalVariable* 4563 // (which will be a definition). 4564 // 4565 // This happens if there is a prototype for a global (e.g. 4566 // "extern int x[];") and then a definition of a different type (e.g. 4567 // "int x[10];"). This also happens when an initializer has a different type 4568 // from the type of the global (this happens with unions). 4569 if (!GV || GV->getValueType() != InitType || 4570 GV->getType()->getAddressSpace() != 4571 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 4572 4573 // Move the old entry aside so that we'll create a new one. 4574 Entry->setName(StringRef()); 4575 4576 // Make a new global with the correct type, this is now guaranteed to work. 4577 GV = cast<llvm::GlobalVariable>( 4578 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 4579 ->stripPointerCasts()); 4580 4581 // Replace all uses of the old global with the new global 4582 llvm::Constant *NewPtrForOldDecl = 4583 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, 4584 Entry->getType()); 4585 Entry->replaceAllUsesWith(NewPtrForOldDecl); 4586 4587 // Erase the old global, since it is no longer used. 4588 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 4589 } 4590 4591 MaybeHandleStaticInExternC(D, GV); 4592 4593 if (D->hasAttr<AnnotateAttr>()) 4594 AddGlobalAnnotations(D, GV); 4595 4596 // Set the llvm linkage type as appropriate. 4597 llvm::GlobalValue::LinkageTypes Linkage = 4598 getLLVMLinkageVarDefinition(D, GV->isConstant()); 4599 4600 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 4601 // the device. [...]" 4602 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 4603 // __device__, declares a variable that: [...] 4604 // Is accessible from all the threads within the grid and from the host 4605 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 4606 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 4607 if (GV && LangOpts.CUDA) { 4608 if (LangOpts.CUDAIsDevice) { 4609 if (Linkage != llvm::GlobalValue::InternalLinkage && 4610 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 4611 D->getType()->isCUDADeviceBuiltinSurfaceType() || 4612 D->getType()->isCUDADeviceBuiltinTextureType())) 4613 GV->setExternallyInitialized(true); 4614 } else { 4615 getCUDARuntime().internalizeDeviceSideVar(D, Linkage); 4616 } 4617 getCUDARuntime().handleVarRegistration(D, *GV); 4618 } 4619 4620 GV->setInitializer(Init); 4621 if (emitter) 4622 emitter->finalize(GV); 4623 4624 // If it is safe to mark the global 'constant', do so now. 4625 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 4626 isTypeConstant(D->getType(), true)); 4627 4628 // If it is in a read-only section, mark it 'constant'. 4629 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 4630 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 4631 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 4632 GV->setConstant(true); 4633 } 4634 4635 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4636 4637 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper 4638 // function is only defined alongside the variable, not also alongside 4639 // callers. Normally, all accesses to a thread_local go through the 4640 // thread-wrapper in order to ensure initialization has occurred, underlying 4641 // variable will never be used other than the thread-wrapper, so it can be 4642 // converted to internal linkage. 4643 // 4644 // However, if the variable has the 'constinit' attribute, it _can_ be 4645 // referenced directly, without calling the thread-wrapper, so the linkage 4646 // must not be changed. 4647 // 4648 // Additionally, if the variable isn't plain external linkage, e.g. if it's 4649 // weak or linkonce, the de-duplication semantics are important to preserve, 4650 // so we don't change the linkage. 4651 if (D->getTLSKind() == VarDecl::TLS_Dynamic && 4652 Linkage == llvm::GlobalValue::ExternalLinkage && 4653 Context.getTargetInfo().getTriple().isOSDarwin() && 4654 !D->hasAttr<ConstInitAttr>()) 4655 Linkage = llvm::GlobalValue::InternalLinkage; 4656 4657 GV->setLinkage(Linkage); 4658 if (D->hasAttr<DLLImportAttr>()) 4659 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 4660 else if (D->hasAttr<DLLExportAttr>()) 4661 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 4662 else 4663 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 4664 4665 if (Linkage == llvm::GlobalVariable::CommonLinkage) { 4666 // common vars aren't constant even if declared const. 4667 GV->setConstant(false); 4668 // Tentative definition of global variables may be initialized with 4669 // non-zero null pointers. In this case they should have weak linkage 4670 // since common linkage must have zero initializer and must not have 4671 // explicit section therefore cannot have non-zero initial value. 4672 if (!GV->getInitializer()->isNullValue()) 4673 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 4674 } 4675 4676 setNonAliasAttributes(D, GV); 4677 4678 if (D->getTLSKind() && !GV->isThreadLocal()) { 4679 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4680 CXXThreadLocals.push_back(D); 4681 setTLSMode(GV, *D); 4682 } 4683 4684 maybeSetTrivialComdat(*D, *GV); 4685 4686 // Emit the initializer function if necessary. 4687 if (NeedsGlobalCtor || NeedsGlobalDtor) 4688 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 4689 4690 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 4691 4692 // Emit global variable debug information. 4693 if (CGDebugInfo *DI = getModuleDebugInfo()) 4694 if (getCodeGenOpts().hasReducedDebugInfo()) 4695 DI->EmitGlobalVariable(GV, D); 4696 } 4697 4698 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { 4699 if (CGDebugInfo *DI = getModuleDebugInfo()) 4700 if (getCodeGenOpts().hasReducedDebugInfo()) { 4701 QualType ASTTy = D->getType(); 4702 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); 4703 llvm::Constant *GV = 4704 GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D); 4705 DI->EmitExternalVariable( 4706 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); 4707 } 4708 } 4709 4710 static bool isVarDeclStrongDefinition(const ASTContext &Context, 4711 CodeGenModule &CGM, const VarDecl *D, 4712 bool NoCommon) { 4713 // Don't give variables common linkage if -fno-common was specified unless it 4714 // was overridden by a NoCommon attribute. 4715 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 4716 return true; 4717 4718 // C11 6.9.2/2: 4719 // A declaration of an identifier for an object that has file scope without 4720 // an initializer, and without a storage-class specifier or with the 4721 // storage-class specifier static, constitutes a tentative definition. 4722 if (D->getInit() || D->hasExternalStorage()) 4723 return true; 4724 4725 // A variable cannot be both common and exist in a section. 4726 if (D->hasAttr<SectionAttr>()) 4727 return true; 4728 4729 // A variable cannot be both common and exist in a section. 4730 // We don't try to determine which is the right section in the front-end. 4731 // If no specialized section name is applicable, it will resort to default. 4732 if (D->hasAttr<PragmaClangBSSSectionAttr>() || 4733 D->hasAttr<PragmaClangDataSectionAttr>() || 4734 D->hasAttr<PragmaClangRelroSectionAttr>() || 4735 D->hasAttr<PragmaClangRodataSectionAttr>()) 4736 return true; 4737 4738 // Thread local vars aren't considered common linkage. 4739 if (D->getTLSKind()) 4740 return true; 4741 4742 // Tentative definitions marked with WeakImportAttr are true definitions. 4743 if (D->hasAttr<WeakImportAttr>()) 4744 return true; 4745 4746 // A variable cannot be both common and exist in a comdat. 4747 if (shouldBeInCOMDAT(CGM, *D)) 4748 return true; 4749 4750 // Declarations with a required alignment do not have common linkage in MSVC 4751 // mode. 4752 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4753 if (D->hasAttr<AlignedAttr>()) 4754 return true; 4755 QualType VarType = D->getType(); 4756 if (Context.isAlignmentRequired(VarType)) 4757 return true; 4758 4759 if (const auto *RT = VarType->getAs<RecordType>()) { 4760 const RecordDecl *RD = RT->getDecl(); 4761 for (const FieldDecl *FD : RD->fields()) { 4762 if (FD->isBitField()) 4763 continue; 4764 if (FD->hasAttr<AlignedAttr>()) 4765 return true; 4766 if (Context.isAlignmentRequired(FD->getType())) 4767 return true; 4768 } 4769 } 4770 } 4771 4772 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 4773 // common symbols, so symbols with greater alignment requirements cannot be 4774 // common. 4775 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 4776 // alignments for common symbols via the aligncomm directive, so this 4777 // restriction only applies to MSVC environments. 4778 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 4779 Context.getTypeAlignIfKnown(D->getType()) > 4780 Context.toBits(CharUnits::fromQuantity(32))) 4781 return true; 4782 4783 return false; 4784 } 4785 4786 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 4787 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 4788 if (Linkage == GVA_Internal) 4789 return llvm::Function::InternalLinkage; 4790 4791 if (D->hasAttr<WeakAttr>()) { 4792 if (IsConstantVariable) 4793 return llvm::GlobalVariable::WeakODRLinkage; 4794 else 4795 return llvm::GlobalVariable::WeakAnyLinkage; 4796 } 4797 4798 if (const auto *FD = D->getAsFunction()) 4799 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 4800 return llvm::GlobalVariable::LinkOnceAnyLinkage; 4801 4802 // We are guaranteed to have a strong definition somewhere else, 4803 // so we can use available_externally linkage. 4804 if (Linkage == GVA_AvailableExternally) 4805 return llvm::GlobalValue::AvailableExternallyLinkage; 4806 4807 // Note that Apple's kernel linker doesn't support symbol 4808 // coalescing, so we need to avoid linkonce and weak linkages there. 4809 // Normally, this means we just map to internal, but for explicit 4810 // instantiations we'll map to external. 4811 4812 // In C++, the compiler has to emit a definition in every translation unit 4813 // that references the function. We should use linkonce_odr because 4814 // a) if all references in this translation unit are optimized away, we 4815 // don't need to codegen it. b) if the function persists, it needs to be 4816 // merged with other definitions. c) C++ has the ODR, so we know the 4817 // definition is dependable. 4818 if (Linkage == GVA_DiscardableODR) 4819 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 4820 : llvm::Function::InternalLinkage; 4821 4822 // An explicit instantiation of a template has weak linkage, since 4823 // explicit instantiations can occur in multiple translation units 4824 // and must all be equivalent. However, we are not allowed to 4825 // throw away these explicit instantiations. 4826 // 4827 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, 4828 // so say that CUDA templates are either external (for kernels) or internal. 4829 // This lets llvm perform aggressive inter-procedural optimizations. For 4830 // -fgpu-rdc case, device function calls across multiple TU's are allowed, 4831 // therefore we need to follow the normal linkage paradigm. 4832 if (Linkage == GVA_StrongODR) { 4833 if (getLangOpts().AppleKext) 4834 return llvm::Function::ExternalLinkage; 4835 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 4836 !getLangOpts().GPURelocatableDeviceCode) 4837 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 4838 : llvm::Function::InternalLinkage; 4839 return llvm::Function::WeakODRLinkage; 4840 } 4841 4842 // C++ doesn't have tentative definitions and thus cannot have common 4843 // linkage. 4844 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 4845 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 4846 CodeGenOpts.NoCommon)) 4847 return llvm::GlobalVariable::CommonLinkage; 4848 4849 // selectany symbols are externally visible, so use weak instead of 4850 // linkonce. MSVC optimizes away references to const selectany globals, so 4851 // all definitions should be the same and ODR linkage should be used. 4852 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 4853 if (D->hasAttr<SelectAnyAttr>()) 4854 return llvm::GlobalVariable::WeakODRLinkage; 4855 4856 // Otherwise, we have strong external linkage. 4857 assert(Linkage == GVA_StrongExternal); 4858 return llvm::GlobalVariable::ExternalLinkage; 4859 } 4860 4861 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 4862 const VarDecl *VD, bool IsConstant) { 4863 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 4864 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 4865 } 4866 4867 /// Replace the uses of a function that was declared with a non-proto type. 4868 /// We want to silently drop extra arguments from call sites 4869 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 4870 llvm::Function *newFn) { 4871 // Fast path. 4872 if (old->use_empty()) return; 4873 4874 llvm::Type *newRetTy = newFn->getReturnType(); 4875 SmallVector<llvm::Value*, 4> newArgs; 4876 4877 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 4878 ui != ue; ) { 4879 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 4880 llvm::User *user = use->getUser(); 4881 4882 // Recognize and replace uses of bitcasts. Most calls to 4883 // unprototyped functions will use bitcasts. 4884 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 4885 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 4886 replaceUsesOfNonProtoConstant(bitcast, newFn); 4887 continue; 4888 } 4889 4890 // Recognize calls to the function. 4891 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 4892 if (!callSite) continue; 4893 if (!callSite->isCallee(&*use)) 4894 continue; 4895 4896 // If the return types don't match exactly, then we can't 4897 // transform this call unless it's dead. 4898 if (callSite->getType() != newRetTy && !callSite->use_empty()) 4899 continue; 4900 4901 // Get the call site's attribute list. 4902 SmallVector<llvm::AttributeSet, 8> newArgAttrs; 4903 llvm::AttributeList oldAttrs = callSite->getAttributes(); 4904 4905 // If the function was passed too few arguments, don't transform. 4906 unsigned newNumArgs = newFn->arg_size(); 4907 if (callSite->arg_size() < newNumArgs) 4908 continue; 4909 4910 // If extra arguments were passed, we silently drop them. 4911 // If any of the types mismatch, we don't transform. 4912 unsigned argNo = 0; 4913 bool dontTransform = false; 4914 for (llvm::Argument &A : newFn->args()) { 4915 if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 4916 dontTransform = true; 4917 break; 4918 } 4919 4920 // Add any parameter attributes. 4921 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo)); 4922 argNo++; 4923 } 4924 if (dontTransform) 4925 continue; 4926 4927 // Okay, we can transform this. Create the new call instruction and copy 4928 // over the required information. 4929 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 4930 4931 // Copy over any operand bundles. 4932 SmallVector<llvm::OperandBundleDef, 1> newBundles; 4933 callSite->getOperandBundlesAsDefs(newBundles); 4934 4935 llvm::CallBase *newCall; 4936 if (isa<llvm::CallInst>(callSite)) { 4937 newCall = 4938 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 4939 } else { 4940 auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 4941 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 4942 oldInvoke->getUnwindDest(), newArgs, 4943 newBundles, "", callSite); 4944 } 4945 newArgs.clear(); // for the next iteration 4946 4947 if (!newCall->getType()->isVoidTy()) 4948 newCall->takeName(callSite); 4949 newCall->setAttributes( 4950 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(), 4951 oldAttrs.getRetAttrs(), newArgAttrs)); 4952 newCall->setCallingConv(callSite->getCallingConv()); 4953 4954 // Finally, remove the old call, replacing any uses with the new one. 4955 if (!callSite->use_empty()) 4956 callSite->replaceAllUsesWith(newCall); 4957 4958 // Copy debug location attached to CI. 4959 if (callSite->getDebugLoc()) 4960 newCall->setDebugLoc(callSite->getDebugLoc()); 4961 4962 callSite->eraseFromParent(); 4963 } 4964 } 4965 4966 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 4967 /// implement a function with no prototype, e.g. "int foo() {}". If there are 4968 /// existing call uses of the old function in the module, this adjusts them to 4969 /// call the new function directly. 4970 /// 4971 /// This is not just a cleanup: the always_inline pass requires direct calls to 4972 /// functions to be able to inline them. If there is a bitcast in the way, it 4973 /// won't inline them. Instcombine normally deletes these calls, but it isn't 4974 /// run at -O0. 4975 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 4976 llvm::Function *NewFn) { 4977 // If we're redefining a global as a function, don't transform it. 4978 if (!isa<llvm::Function>(Old)) return; 4979 4980 replaceUsesOfNonProtoConstant(Old, NewFn); 4981 } 4982 4983 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 4984 auto DK = VD->isThisDeclarationADefinition(); 4985 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 4986 return; 4987 4988 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 4989 // If we have a definition, this might be a deferred decl. If the 4990 // instantiation is explicit, make sure we emit it at the end. 4991 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 4992 GetAddrOfGlobalVar(VD); 4993 4994 EmitTopLevelDecl(VD); 4995 } 4996 4997 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 4998 llvm::GlobalValue *GV) { 4999 const auto *D = cast<FunctionDecl>(GD.getDecl()); 5000 5001 // Compute the function info and LLVM type. 5002 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 5003 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 5004 5005 // Get or create the prototype for the function. 5006 if (!GV || (GV->getValueType() != Ty)) 5007 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 5008 /*DontDefer=*/true, 5009 ForDefinition)); 5010 5011 // Already emitted. 5012 if (!GV->isDeclaration()) 5013 return; 5014 5015 // We need to set linkage and visibility on the function before 5016 // generating code for it because various parts of IR generation 5017 // want to propagate this information down (e.g. to local static 5018 // declarations). 5019 auto *Fn = cast<llvm::Function>(GV); 5020 setFunctionLinkage(GD, Fn); 5021 5022 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 5023 setGVProperties(Fn, GD); 5024 5025 MaybeHandleStaticInExternC(D, Fn); 5026 5027 maybeSetTrivialComdat(*D, *Fn); 5028 5029 // Set CodeGen attributes that represent floating point environment. 5030 setLLVMFunctionFEnvAttributes(D, Fn); 5031 5032 CodeGenFunction(*this).GenerateCode(GD, Fn, FI); 5033 5034 setNonAliasAttributes(GD, Fn); 5035 SetLLVMFunctionAttributesForDefinition(D, Fn); 5036 5037 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 5038 AddGlobalCtor(Fn, CA->getPriority()); 5039 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 5040 AddGlobalDtor(Fn, DA->getPriority(), true); 5041 if (D->hasAttr<AnnotateAttr>()) 5042 AddGlobalAnnotations(D, Fn); 5043 } 5044 5045 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 5046 const auto *D = cast<ValueDecl>(GD.getDecl()); 5047 const AliasAttr *AA = D->getAttr<AliasAttr>(); 5048 assert(AA && "Not an alias?"); 5049 5050 StringRef MangledName = getMangledName(GD); 5051 5052 if (AA->getAliasee() == MangledName) { 5053 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5054 return; 5055 } 5056 5057 // If there is a definition in the module, then it wins over the alias. 5058 // This is dubious, but allow it to be safe. Just ignore the alias. 5059 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5060 if (Entry && !Entry->isDeclaration()) 5061 return; 5062 5063 Aliases.push_back(GD); 5064 5065 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5066 5067 // Create a reference to the named value. This ensures that it is emitted 5068 // if a deferred decl. 5069 llvm::Constant *Aliasee; 5070 llvm::GlobalValue::LinkageTypes LT; 5071 if (isa<llvm::FunctionType>(DeclTy)) { 5072 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 5073 /*ForVTable=*/false); 5074 LT = getFunctionLinkage(GD); 5075 } else { 5076 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 5077 /*D=*/nullptr); 5078 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl())) 5079 LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified()); 5080 else 5081 LT = getFunctionLinkage(GD); 5082 } 5083 5084 // Create the new alias itself, but don't set a name yet. 5085 unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 5086 auto *GA = 5087 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 5088 5089 if (Entry) { 5090 if (GA->getAliasee() == Entry) { 5091 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5092 return; 5093 } 5094 5095 assert(Entry->isDeclaration()); 5096 5097 // If there is a declaration in the module, then we had an extern followed 5098 // by the alias, as in: 5099 // extern int test6(); 5100 // ... 5101 // int test6() __attribute__((alias("test7"))); 5102 // 5103 // Remove it and replace uses of it with the alias. 5104 GA->takeName(Entry); 5105 5106 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 5107 Entry->getType())); 5108 Entry->eraseFromParent(); 5109 } else { 5110 GA->setName(MangledName); 5111 } 5112 5113 // Set attributes which are particular to an alias; this is a 5114 // specialization of the attributes which may be set on a global 5115 // variable/function. 5116 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 5117 D->isWeakImported()) { 5118 GA->setLinkage(llvm::Function::WeakAnyLinkage); 5119 } 5120 5121 if (const auto *VD = dyn_cast<VarDecl>(D)) 5122 if (VD->getTLSKind()) 5123 setTLSMode(GA, *VD); 5124 5125 SetCommonAttributes(GD, GA); 5126 } 5127 5128 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 5129 const auto *D = cast<ValueDecl>(GD.getDecl()); 5130 const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 5131 assert(IFA && "Not an ifunc?"); 5132 5133 StringRef MangledName = getMangledName(GD); 5134 5135 if (IFA->getResolver() == MangledName) { 5136 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5137 return; 5138 } 5139 5140 // Report an error if some definition overrides ifunc. 5141 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5142 if (Entry && !Entry->isDeclaration()) { 5143 GlobalDecl OtherGD; 5144 if (lookupRepresentativeDecl(MangledName, OtherGD) && 5145 DiagnosedConflictingDefinitions.insert(GD).second) { 5146 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 5147 << MangledName; 5148 Diags.Report(OtherGD.getDecl()->getLocation(), 5149 diag::note_previous_definition); 5150 } 5151 return; 5152 } 5153 5154 Aliases.push_back(GD); 5155 5156 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5157 llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy); 5158 llvm::Constant *Resolver = 5159 GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {}, 5160 /*ForVTable=*/false); 5161 llvm::GlobalIFunc *GIF = 5162 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 5163 "", Resolver, &getModule()); 5164 if (Entry) { 5165 if (GIF->getResolver() == Entry) { 5166 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5167 return; 5168 } 5169 assert(Entry->isDeclaration()); 5170 5171 // If there is a declaration in the module, then we had an extern followed 5172 // by the ifunc, as in: 5173 // extern int test(); 5174 // ... 5175 // int test() __attribute__((ifunc("resolver"))); 5176 // 5177 // Remove it and replace uses of it with the ifunc. 5178 GIF->takeName(Entry); 5179 5180 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 5181 Entry->getType())); 5182 Entry->eraseFromParent(); 5183 } else 5184 GIF->setName(MangledName); 5185 5186 SetCommonAttributes(GD, GIF); 5187 } 5188 5189 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 5190 ArrayRef<llvm::Type*> Tys) { 5191 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 5192 Tys); 5193 } 5194 5195 static llvm::StringMapEntry<llvm::GlobalVariable *> & 5196 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 5197 const StringLiteral *Literal, bool TargetIsLSB, 5198 bool &IsUTF16, unsigned &StringLength) { 5199 StringRef String = Literal->getString(); 5200 unsigned NumBytes = String.size(); 5201 5202 // Check for simple case. 5203 if (!Literal->containsNonAsciiOrNull()) { 5204 StringLength = NumBytes; 5205 return *Map.insert(std::make_pair(String, nullptr)).first; 5206 } 5207 5208 // Otherwise, convert the UTF8 literals into a string of shorts. 5209 IsUTF16 = true; 5210 5211 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 5212 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5213 llvm::UTF16 *ToPtr = &ToBuf[0]; 5214 5215 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5216 ToPtr + NumBytes, llvm::strictConversion); 5217 5218 // ConvertUTF8toUTF16 returns the length in ToPtr. 5219 StringLength = ToPtr - &ToBuf[0]; 5220 5221 // Add an explicit null. 5222 *ToPtr = 0; 5223 return *Map.insert(std::make_pair( 5224 StringRef(reinterpret_cast<const char *>(ToBuf.data()), 5225 (StringLength + 1) * 2), 5226 nullptr)).first; 5227 } 5228 5229 ConstantAddress 5230 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 5231 unsigned StringLength = 0; 5232 bool isUTF16 = false; 5233 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 5234 GetConstantCFStringEntry(CFConstantStringMap, Literal, 5235 getDataLayout().isLittleEndian(), isUTF16, 5236 StringLength); 5237 5238 if (auto *C = Entry.second) 5239 return ConstantAddress( 5240 C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment())); 5241 5242 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 5243 llvm::Constant *Zeros[] = { Zero, Zero }; 5244 5245 const ASTContext &Context = getContext(); 5246 const llvm::Triple &Triple = getTriple(); 5247 5248 const auto CFRuntime = getLangOpts().CFRuntime; 5249 const bool IsSwiftABI = 5250 static_cast<unsigned>(CFRuntime) >= 5251 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 5252 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 5253 5254 // If we don't already have it, get __CFConstantStringClassReference. 5255 if (!CFConstantStringClassRef) { 5256 const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 5257 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 5258 Ty = llvm::ArrayType::get(Ty, 0); 5259 5260 switch (CFRuntime) { 5261 default: break; 5262 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH; 5263 case LangOptions::CoreFoundationABI::Swift5_0: 5264 CFConstantStringClassName = 5265 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 5266 : "$s10Foundation19_NSCFConstantStringCN"; 5267 Ty = IntPtrTy; 5268 break; 5269 case LangOptions::CoreFoundationABI::Swift4_2: 5270 CFConstantStringClassName = 5271 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 5272 : "$S10Foundation19_NSCFConstantStringCN"; 5273 Ty = IntPtrTy; 5274 break; 5275 case LangOptions::CoreFoundationABI::Swift4_1: 5276 CFConstantStringClassName = 5277 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 5278 : "__T010Foundation19_NSCFConstantStringCN"; 5279 Ty = IntPtrTy; 5280 break; 5281 } 5282 5283 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 5284 5285 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 5286 llvm::GlobalValue *GV = nullptr; 5287 5288 if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 5289 IdentifierInfo &II = Context.Idents.get(GV->getName()); 5290 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 5291 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 5292 5293 const VarDecl *VD = nullptr; 5294 for (const auto *Result : DC->lookup(&II)) 5295 if ((VD = dyn_cast<VarDecl>(Result))) 5296 break; 5297 5298 if (Triple.isOSBinFormatELF()) { 5299 if (!VD) 5300 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5301 } else { 5302 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5303 if (!VD || !VD->hasAttr<DLLExportAttr>()) 5304 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 5305 else 5306 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 5307 } 5308 5309 setDSOLocal(GV); 5310 } 5311 } 5312 5313 // Decay array -> ptr 5314 CFConstantStringClassRef = 5315 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 5316 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 5317 } 5318 5319 QualType CFTy = Context.getCFConstantStringType(); 5320 5321 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 5322 5323 ConstantInitBuilder Builder(*this); 5324 auto Fields = Builder.beginStruct(STy); 5325 5326 // Class pointer. 5327 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef)); 5328 5329 // Flags. 5330 if (IsSwiftABI) { 5331 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 5332 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 5333 } else { 5334 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 5335 } 5336 5337 // String pointer. 5338 llvm::Constant *C = nullptr; 5339 if (isUTF16) { 5340 auto Arr = llvm::makeArrayRef( 5341 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 5342 Entry.first().size() / 2); 5343 C = llvm::ConstantDataArray::get(VMContext, Arr); 5344 } else { 5345 C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 5346 } 5347 5348 // Note: -fwritable-strings doesn't make the backing store strings of 5349 // CFStrings writable. (See <rdar://problem/10657500>) 5350 auto *GV = 5351 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 5352 llvm::GlobalValue::PrivateLinkage, C, ".str"); 5353 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5354 // Don't enforce the target's minimum global alignment, since the only use 5355 // of the string is via this class initializer. 5356 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 5357 : Context.getTypeAlignInChars(Context.CharTy); 5358 GV->setAlignment(Align.getAsAlign()); 5359 5360 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 5361 // Without it LLVM can merge the string with a non unnamed_addr one during 5362 // LTO. Doing that changes the section it ends in, which surprises ld64. 5363 if (Triple.isOSBinFormatMachO()) 5364 GV->setSection(isUTF16 ? "__TEXT,__ustring" 5365 : "__TEXT,__cstring,cstring_literals"); 5366 // Make sure the literal ends up in .rodata to allow for safe ICF and for 5367 // the static linker to adjust permissions to read-only later on. 5368 else if (Triple.isOSBinFormatELF()) 5369 GV->setSection(".rodata"); 5370 5371 // String. 5372 llvm::Constant *Str = 5373 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 5374 5375 if (isUTF16) 5376 // Cast the UTF16 string to the correct type. 5377 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 5378 Fields.add(Str); 5379 5380 // String length. 5381 llvm::IntegerType *LengthTy = 5382 llvm::IntegerType::get(getModule().getContext(), 5383 Context.getTargetInfo().getLongWidth()); 5384 if (IsSwiftABI) { 5385 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 5386 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 5387 LengthTy = Int32Ty; 5388 else 5389 LengthTy = IntPtrTy; 5390 } 5391 Fields.addInt(LengthTy, StringLength); 5392 5393 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 5394 // properly aligned on 32-bit platforms. 5395 CharUnits Alignment = 5396 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 5397 5398 // The struct. 5399 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 5400 /*isConstant=*/false, 5401 llvm::GlobalVariable::PrivateLinkage); 5402 GV->addAttribute("objc_arc_inert"); 5403 switch (Triple.getObjectFormat()) { 5404 case llvm::Triple::UnknownObjectFormat: 5405 llvm_unreachable("unknown file format"); 5406 case llvm::Triple::GOFF: 5407 llvm_unreachable("GOFF is not yet implemented"); 5408 case llvm::Triple::XCOFF: 5409 llvm_unreachable("XCOFF is not yet implemented"); 5410 case llvm::Triple::COFF: 5411 case llvm::Triple::ELF: 5412 case llvm::Triple::Wasm: 5413 GV->setSection("cfstring"); 5414 break; 5415 case llvm::Triple::MachO: 5416 GV->setSection("__DATA,__cfstring"); 5417 break; 5418 } 5419 Entry.second = GV; 5420 5421 return ConstantAddress(GV, GV->getValueType(), Alignment); 5422 } 5423 5424 bool CodeGenModule::getExpressionLocationsEnabled() const { 5425 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 5426 } 5427 5428 QualType CodeGenModule::getObjCFastEnumerationStateType() { 5429 if (ObjCFastEnumerationStateType.isNull()) { 5430 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 5431 D->startDefinition(); 5432 5433 QualType FieldTypes[] = { 5434 Context.UnsignedLongTy, 5435 Context.getPointerType(Context.getObjCIdType()), 5436 Context.getPointerType(Context.UnsignedLongTy), 5437 Context.getConstantArrayType(Context.UnsignedLongTy, 5438 llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0) 5439 }; 5440 5441 for (size_t i = 0; i < 4; ++i) { 5442 FieldDecl *Field = FieldDecl::Create(Context, 5443 D, 5444 SourceLocation(), 5445 SourceLocation(), nullptr, 5446 FieldTypes[i], /*TInfo=*/nullptr, 5447 /*BitWidth=*/nullptr, 5448 /*Mutable=*/false, 5449 ICIS_NoInit); 5450 Field->setAccess(AS_public); 5451 D->addDecl(Field); 5452 } 5453 5454 D->completeDefinition(); 5455 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 5456 } 5457 5458 return ObjCFastEnumerationStateType; 5459 } 5460 5461 llvm::Constant * 5462 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 5463 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 5464 5465 // Don't emit it as the address of the string, emit the string data itself 5466 // as an inline array. 5467 if (E->getCharByteWidth() == 1) { 5468 SmallString<64> Str(E->getString()); 5469 5470 // Resize the string to the right size, which is indicated by its type. 5471 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 5472 Str.resize(CAT->getSize().getZExtValue()); 5473 return llvm::ConstantDataArray::getString(VMContext, Str, false); 5474 } 5475 5476 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 5477 llvm::Type *ElemTy = AType->getElementType(); 5478 unsigned NumElements = AType->getNumElements(); 5479 5480 // Wide strings have either 2-byte or 4-byte elements. 5481 if (ElemTy->getPrimitiveSizeInBits() == 16) { 5482 SmallVector<uint16_t, 32> Elements; 5483 Elements.reserve(NumElements); 5484 5485 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5486 Elements.push_back(E->getCodeUnit(i)); 5487 Elements.resize(NumElements); 5488 return llvm::ConstantDataArray::get(VMContext, Elements); 5489 } 5490 5491 assert(ElemTy->getPrimitiveSizeInBits() == 32); 5492 SmallVector<uint32_t, 32> Elements; 5493 Elements.reserve(NumElements); 5494 5495 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5496 Elements.push_back(E->getCodeUnit(i)); 5497 Elements.resize(NumElements); 5498 return llvm::ConstantDataArray::get(VMContext, Elements); 5499 } 5500 5501 static llvm::GlobalVariable * 5502 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 5503 CodeGenModule &CGM, StringRef GlobalName, 5504 CharUnits Alignment) { 5505 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 5506 CGM.GetGlobalConstantAddressSpace()); 5507 5508 llvm::Module &M = CGM.getModule(); 5509 // Create a global variable for this string 5510 auto *GV = new llvm::GlobalVariable( 5511 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 5512 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 5513 GV->setAlignment(Alignment.getAsAlign()); 5514 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5515 if (GV->isWeakForLinker()) { 5516 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 5517 GV->setComdat(M.getOrInsertComdat(GV->getName())); 5518 } 5519 CGM.setDSOLocal(GV); 5520 5521 return GV; 5522 } 5523 5524 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 5525 /// constant array for the given string literal. 5526 ConstantAddress 5527 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 5528 StringRef Name) { 5529 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 5530 5531 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 5532 llvm::GlobalVariable **Entry = nullptr; 5533 if (!LangOpts.WritableStrings) { 5534 Entry = &ConstantStringMap[C]; 5535 if (auto GV = *Entry) { 5536 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5537 GV->setAlignment(Alignment.getAsAlign()); 5538 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5539 GV->getValueType(), Alignment); 5540 } 5541 } 5542 5543 SmallString<256> MangledNameBuffer; 5544 StringRef GlobalVariableName; 5545 llvm::GlobalValue::LinkageTypes LT; 5546 5547 // Mangle the string literal if that's how the ABI merges duplicate strings. 5548 // Don't do it if they are writable, since we don't want writes in one TU to 5549 // affect strings in another. 5550 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 5551 !LangOpts.WritableStrings) { 5552 llvm::raw_svector_ostream Out(MangledNameBuffer); 5553 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 5554 LT = llvm::GlobalValue::LinkOnceODRLinkage; 5555 GlobalVariableName = MangledNameBuffer; 5556 } else { 5557 LT = llvm::GlobalValue::PrivateLinkage; 5558 GlobalVariableName = Name; 5559 } 5560 5561 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 5562 if (Entry) 5563 *Entry = GV; 5564 5565 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 5566 QualType()); 5567 5568 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5569 GV->getValueType(), Alignment); 5570 } 5571 5572 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 5573 /// array for the given ObjCEncodeExpr node. 5574 ConstantAddress 5575 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 5576 std::string Str; 5577 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 5578 5579 return GetAddrOfConstantCString(Str); 5580 } 5581 5582 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 5583 /// the literal and a terminating '\0' character. 5584 /// The result has pointer to array type. 5585 ConstantAddress CodeGenModule::GetAddrOfConstantCString( 5586 const std::string &Str, const char *GlobalName) { 5587 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 5588 CharUnits Alignment = 5589 getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 5590 5591 llvm::Constant *C = 5592 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 5593 5594 // Don't share any string literals if strings aren't constant. 5595 llvm::GlobalVariable **Entry = nullptr; 5596 if (!LangOpts.WritableStrings) { 5597 Entry = &ConstantStringMap[C]; 5598 if (auto GV = *Entry) { 5599 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5600 GV->setAlignment(Alignment.getAsAlign()); 5601 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5602 GV->getValueType(), Alignment); 5603 } 5604 } 5605 5606 // Get the default prefix if a name wasn't specified. 5607 if (!GlobalName) 5608 GlobalName = ".str"; 5609 // Create a global variable for this. 5610 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 5611 GlobalName, Alignment); 5612 if (Entry) 5613 *Entry = GV; 5614 5615 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5616 GV->getValueType(), Alignment); 5617 } 5618 5619 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 5620 const MaterializeTemporaryExpr *E, const Expr *Init) { 5621 assert((E->getStorageDuration() == SD_Static || 5622 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 5623 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 5624 5625 // If we're not materializing a subobject of the temporary, keep the 5626 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 5627 QualType MaterializedType = Init->getType(); 5628 if (Init == E->getSubExpr()) 5629 MaterializedType = E->getType(); 5630 5631 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 5632 5633 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr}); 5634 if (!InsertResult.second) { 5635 // We've seen this before: either we already created it or we're in the 5636 // process of doing so. 5637 if (!InsertResult.first->second) { 5638 // We recursively re-entered this function, probably during emission of 5639 // the initializer. Create a placeholder. We'll clean this up in the 5640 // outer call, at the end of this function. 5641 llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType); 5642 InsertResult.first->second = new llvm::GlobalVariable( 5643 getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, 5644 nullptr); 5645 } 5646 return ConstantAddress( 5647 InsertResult.first->second, 5648 InsertResult.first->second->getType()->getPointerElementType(), Align); 5649 } 5650 5651 // FIXME: If an externally-visible declaration extends multiple temporaries, 5652 // we need to give each temporary the same name in every translation unit (and 5653 // we also need to make the temporaries externally-visible). 5654 SmallString<256> Name; 5655 llvm::raw_svector_ostream Out(Name); 5656 getCXXABI().getMangleContext().mangleReferenceTemporary( 5657 VD, E->getManglingNumber(), Out); 5658 5659 APValue *Value = nullptr; 5660 if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) { 5661 // If the initializer of the extending declaration is a constant 5662 // initializer, we should have a cached constant initializer for this 5663 // temporary. Note that this might have a different value from the value 5664 // computed by evaluating the initializer if the surrounding constant 5665 // expression modifies the temporary. 5666 Value = E->getOrCreateValue(false); 5667 } 5668 5669 // Try evaluating it now, it might have a constant initializer. 5670 Expr::EvalResult EvalResult; 5671 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 5672 !EvalResult.hasSideEffects()) 5673 Value = &EvalResult.Val; 5674 5675 LangAS AddrSpace = 5676 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 5677 5678 Optional<ConstantEmitter> emitter; 5679 llvm::Constant *InitialValue = nullptr; 5680 bool Constant = false; 5681 llvm::Type *Type; 5682 if (Value) { 5683 // The temporary has a constant initializer, use it. 5684 emitter.emplace(*this); 5685 InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 5686 MaterializedType); 5687 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 5688 Type = InitialValue->getType(); 5689 } else { 5690 // No initializer, the initialization will be provided when we 5691 // initialize the declaration which performed lifetime extension. 5692 Type = getTypes().ConvertTypeForMem(MaterializedType); 5693 } 5694 5695 // Create a global variable for this lifetime-extended temporary. 5696 llvm::GlobalValue::LinkageTypes Linkage = 5697 getLLVMLinkageVarDefinition(VD, Constant); 5698 if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 5699 const VarDecl *InitVD; 5700 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 5701 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 5702 // Temporaries defined inside a class get linkonce_odr linkage because the 5703 // class can be defined in multiple translation units. 5704 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 5705 } else { 5706 // There is no need for this temporary to have external linkage if the 5707 // VarDecl has external linkage. 5708 Linkage = llvm::GlobalVariable::InternalLinkage; 5709 } 5710 } 5711 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 5712 auto *GV = new llvm::GlobalVariable( 5713 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 5714 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 5715 if (emitter) emitter->finalize(GV); 5716 setGVProperties(GV, VD); 5717 GV->setAlignment(Align.getAsAlign()); 5718 if (supportsCOMDAT() && GV->isWeakForLinker()) 5719 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 5720 if (VD->getTLSKind()) 5721 setTLSMode(GV, *VD); 5722 llvm::Constant *CV = GV; 5723 if (AddrSpace != LangAS::Default) 5724 CV = getTargetCodeGenInfo().performAddrSpaceCast( 5725 *this, GV, AddrSpace, LangAS::Default, 5726 Type->getPointerTo( 5727 getContext().getTargetAddressSpace(LangAS::Default))); 5728 5729 // Update the map with the new temporary. If we created a placeholder above, 5730 // replace it with the new global now. 5731 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; 5732 if (Entry) { 5733 Entry->replaceAllUsesWith( 5734 llvm::ConstantExpr::getBitCast(CV, Entry->getType())); 5735 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent(); 5736 } 5737 Entry = CV; 5738 5739 return ConstantAddress(CV, Type, Align); 5740 } 5741 5742 /// EmitObjCPropertyImplementations - Emit information for synthesized 5743 /// properties for an implementation. 5744 void CodeGenModule::EmitObjCPropertyImplementations(const 5745 ObjCImplementationDecl *D) { 5746 for (const auto *PID : D->property_impls()) { 5747 // Dynamic is just for type-checking. 5748 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 5749 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 5750 5751 // Determine which methods need to be implemented, some may have 5752 // been overridden. Note that ::isPropertyAccessor is not the method 5753 // we want, that just indicates if the decl came from a 5754 // property. What we want to know is if the method is defined in 5755 // this implementation. 5756 auto *Getter = PID->getGetterMethodDecl(); 5757 if (!Getter || Getter->isSynthesizedAccessorStub()) 5758 CodeGenFunction(*this).GenerateObjCGetter( 5759 const_cast<ObjCImplementationDecl *>(D), PID); 5760 auto *Setter = PID->getSetterMethodDecl(); 5761 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 5762 CodeGenFunction(*this).GenerateObjCSetter( 5763 const_cast<ObjCImplementationDecl *>(D), PID); 5764 } 5765 } 5766 } 5767 5768 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 5769 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 5770 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 5771 ivar; ivar = ivar->getNextIvar()) 5772 if (ivar->getType().isDestructedType()) 5773 return true; 5774 5775 return false; 5776 } 5777 5778 static bool AllTrivialInitializers(CodeGenModule &CGM, 5779 ObjCImplementationDecl *D) { 5780 CodeGenFunction CGF(CGM); 5781 for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 5782 E = D->init_end(); B != E; ++B) { 5783 CXXCtorInitializer *CtorInitExp = *B; 5784 Expr *Init = CtorInitExp->getInit(); 5785 if (!CGF.isTrivialInitializer(Init)) 5786 return false; 5787 } 5788 return true; 5789 } 5790 5791 /// EmitObjCIvarInitializations - Emit information for ivar initialization 5792 /// for an implementation. 5793 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 5794 // We might need a .cxx_destruct even if we don't have any ivar initializers. 5795 if (needsDestructMethod(D)) { 5796 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 5797 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5798 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( 5799 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5800 getContext().VoidTy, nullptr, D, 5801 /*isInstance=*/true, /*isVariadic=*/false, 5802 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5803 /*isImplicitlyDeclared=*/true, 5804 /*isDefined=*/false, ObjCMethodDecl::Required); 5805 D->addInstanceMethod(DTORMethod); 5806 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 5807 D->setHasDestructors(true); 5808 } 5809 5810 // If the implementation doesn't have any ivar initializers, we don't need 5811 // a .cxx_construct. 5812 if (D->getNumIvarInitializers() == 0 || 5813 AllTrivialInitializers(*this, D)) 5814 return; 5815 5816 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 5817 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5818 // The constructor returns 'self'. 5819 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( 5820 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5821 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, 5822 /*isVariadic=*/false, 5823 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5824 /*isImplicitlyDeclared=*/true, 5825 /*isDefined=*/false, ObjCMethodDecl::Required); 5826 D->addInstanceMethod(CTORMethod); 5827 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 5828 D->setHasNonZeroConstructors(true); 5829 } 5830 5831 // EmitLinkageSpec - Emit all declarations in a linkage spec. 5832 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 5833 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 5834 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 5835 ErrorUnsupported(LSD, "linkage spec"); 5836 return; 5837 } 5838 5839 EmitDeclContext(LSD); 5840 } 5841 5842 void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 5843 for (auto *I : DC->decls()) { 5844 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 5845 // are themselves considered "top-level", so EmitTopLevelDecl on an 5846 // ObjCImplDecl does not recursively visit them. We need to do that in 5847 // case they're nested inside another construct (LinkageSpecDecl / 5848 // ExportDecl) that does stop them from being considered "top-level". 5849 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 5850 for (auto *M : OID->methods()) 5851 EmitTopLevelDecl(M); 5852 } 5853 5854 EmitTopLevelDecl(I); 5855 } 5856 } 5857 5858 /// EmitTopLevelDecl - Emit code for a single top level declaration. 5859 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 5860 // Ignore dependent declarations. 5861 if (D->isTemplated()) 5862 return; 5863 5864 // Consteval function shouldn't be emitted. 5865 if (auto *FD = dyn_cast<FunctionDecl>(D)) 5866 if (FD->isConsteval()) 5867 return; 5868 5869 switch (D->getKind()) { 5870 case Decl::CXXConversion: 5871 case Decl::CXXMethod: 5872 case Decl::Function: 5873 EmitGlobal(cast<FunctionDecl>(D)); 5874 // Always provide some coverage mapping 5875 // even for the functions that aren't emitted. 5876 AddDeferredUnusedCoverageMapping(D); 5877 break; 5878 5879 case Decl::CXXDeductionGuide: 5880 // Function-like, but does not result in code emission. 5881 break; 5882 5883 case Decl::Var: 5884 case Decl::Decomposition: 5885 case Decl::VarTemplateSpecialization: 5886 EmitGlobal(cast<VarDecl>(D)); 5887 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 5888 for (auto *B : DD->bindings()) 5889 if (auto *HD = B->getHoldingVar()) 5890 EmitGlobal(HD); 5891 break; 5892 5893 // Indirect fields from global anonymous structs and unions can be 5894 // ignored; only the actual variable requires IR gen support. 5895 case Decl::IndirectField: 5896 break; 5897 5898 // C++ Decls 5899 case Decl::Namespace: 5900 EmitDeclContext(cast<NamespaceDecl>(D)); 5901 break; 5902 case Decl::ClassTemplateSpecialization: { 5903 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 5904 if (CGDebugInfo *DI = getModuleDebugInfo()) 5905 if (Spec->getSpecializationKind() == 5906 TSK_ExplicitInstantiationDefinition && 5907 Spec->hasDefinition()) 5908 DI->completeTemplateDefinition(*Spec); 5909 } LLVM_FALLTHROUGH; 5910 case Decl::CXXRecord: { 5911 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); 5912 if (CGDebugInfo *DI = getModuleDebugInfo()) { 5913 if (CRD->hasDefinition()) 5914 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 5915 if (auto *ES = D->getASTContext().getExternalSource()) 5916 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 5917 DI->completeUnusedClass(*CRD); 5918 } 5919 // Emit any static data members, they may be definitions. 5920 for (auto *I : CRD->decls()) 5921 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 5922 EmitTopLevelDecl(I); 5923 break; 5924 } 5925 // No code generation needed. 5926 case Decl::UsingShadow: 5927 case Decl::ClassTemplate: 5928 case Decl::VarTemplate: 5929 case Decl::Concept: 5930 case Decl::VarTemplatePartialSpecialization: 5931 case Decl::FunctionTemplate: 5932 case Decl::TypeAliasTemplate: 5933 case Decl::Block: 5934 case Decl::Empty: 5935 case Decl::Binding: 5936 break; 5937 case Decl::Using: // using X; [C++] 5938 if (CGDebugInfo *DI = getModuleDebugInfo()) 5939 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 5940 break; 5941 case Decl::UsingEnum: // using enum X; [C++] 5942 if (CGDebugInfo *DI = getModuleDebugInfo()) 5943 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D)); 5944 break; 5945 case Decl::NamespaceAlias: 5946 if (CGDebugInfo *DI = getModuleDebugInfo()) 5947 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 5948 break; 5949 case Decl::UsingDirective: // using namespace X; [C++] 5950 if (CGDebugInfo *DI = getModuleDebugInfo()) 5951 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 5952 break; 5953 case Decl::CXXConstructor: 5954 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 5955 break; 5956 case Decl::CXXDestructor: 5957 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 5958 break; 5959 5960 case Decl::StaticAssert: 5961 // Nothing to do. 5962 break; 5963 5964 // Objective-C Decls 5965 5966 // Forward declarations, no (immediate) code generation. 5967 case Decl::ObjCInterface: 5968 case Decl::ObjCCategory: 5969 break; 5970 5971 case Decl::ObjCProtocol: { 5972 auto *Proto = cast<ObjCProtocolDecl>(D); 5973 if (Proto->isThisDeclarationADefinition()) 5974 ObjCRuntime->GenerateProtocol(Proto); 5975 break; 5976 } 5977 5978 case Decl::ObjCCategoryImpl: 5979 // Categories have properties but don't support synthesize so we 5980 // can ignore them here. 5981 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 5982 break; 5983 5984 case Decl::ObjCImplementation: { 5985 auto *OMD = cast<ObjCImplementationDecl>(D); 5986 EmitObjCPropertyImplementations(OMD); 5987 EmitObjCIvarInitializations(OMD); 5988 ObjCRuntime->GenerateClass(OMD); 5989 // Emit global variable debug information. 5990 if (CGDebugInfo *DI = getModuleDebugInfo()) 5991 if (getCodeGenOpts().hasReducedDebugInfo()) 5992 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 5993 OMD->getClassInterface()), OMD->getLocation()); 5994 break; 5995 } 5996 case Decl::ObjCMethod: { 5997 auto *OMD = cast<ObjCMethodDecl>(D); 5998 // If this is not a prototype, emit the body. 5999 if (OMD->getBody()) 6000 CodeGenFunction(*this).GenerateObjCMethod(OMD); 6001 break; 6002 } 6003 case Decl::ObjCCompatibleAlias: 6004 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 6005 break; 6006 6007 case Decl::PragmaComment: { 6008 const auto *PCD = cast<PragmaCommentDecl>(D); 6009 switch (PCD->getCommentKind()) { 6010 case PCK_Unknown: 6011 llvm_unreachable("unexpected pragma comment kind"); 6012 case PCK_Linker: 6013 AppendLinkerOptions(PCD->getArg()); 6014 break; 6015 case PCK_Lib: 6016 AddDependentLib(PCD->getArg()); 6017 break; 6018 case PCK_Compiler: 6019 case PCK_ExeStr: 6020 case PCK_User: 6021 break; // We ignore all of these. 6022 } 6023 break; 6024 } 6025 6026 case Decl::PragmaDetectMismatch: { 6027 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 6028 AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 6029 break; 6030 } 6031 6032 case Decl::LinkageSpec: 6033 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 6034 break; 6035 6036 case Decl::FileScopeAsm: { 6037 // File-scope asm is ignored during device-side CUDA compilation. 6038 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 6039 break; 6040 // File-scope asm is ignored during device-side OpenMP compilation. 6041 if (LangOpts.OpenMPIsDevice) 6042 break; 6043 // File-scope asm is ignored during device-side SYCL compilation. 6044 if (LangOpts.SYCLIsDevice) 6045 break; 6046 auto *AD = cast<FileScopeAsmDecl>(D); 6047 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 6048 break; 6049 } 6050 6051 case Decl::Import: { 6052 auto *Import = cast<ImportDecl>(D); 6053 6054 // If we've already imported this module, we're done. 6055 if (!ImportedModules.insert(Import->getImportedModule())) 6056 break; 6057 6058 // Emit debug information for direct imports. 6059 if (!Import->getImportedOwningModule()) { 6060 if (CGDebugInfo *DI = getModuleDebugInfo()) 6061 DI->EmitImportDecl(*Import); 6062 } 6063 6064 // Find all of the submodules and emit the module initializers. 6065 llvm::SmallPtrSet<clang::Module *, 16> Visited; 6066 SmallVector<clang::Module *, 16> Stack; 6067 Visited.insert(Import->getImportedModule()); 6068 Stack.push_back(Import->getImportedModule()); 6069 6070 while (!Stack.empty()) { 6071 clang::Module *Mod = Stack.pop_back_val(); 6072 if (!EmittedModuleInitializers.insert(Mod).second) 6073 continue; 6074 6075 for (auto *D : Context.getModuleInitializers(Mod)) 6076 EmitTopLevelDecl(D); 6077 6078 // Visit the submodules of this module. 6079 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 6080 SubEnd = Mod->submodule_end(); 6081 Sub != SubEnd; ++Sub) { 6082 // Skip explicit children; they need to be explicitly imported to emit 6083 // the initializers. 6084 if ((*Sub)->IsExplicit) 6085 continue; 6086 6087 if (Visited.insert(*Sub).second) 6088 Stack.push_back(*Sub); 6089 } 6090 } 6091 break; 6092 } 6093 6094 case Decl::Export: 6095 EmitDeclContext(cast<ExportDecl>(D)); 6096 break; 6097 6098 case Decl::OMPThreadPrivate: 6099 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 6100 break; 6101 6102 case Decl::OMPAllocate: 6103 EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D)); 6104 break; 6105 6106 case Decl::OMPDeclareReduction: 6107 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 6108 break; 6109 6110 case Decl::OMPDeclareMapper: 6111 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 6112 break; 6113 6114 case Decl::OMPRequires: 6115 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 6116 break; 6117 6118 case Decl::Typedef: 6119 case Decl::TypeAlias: // using foo = bar; [C++11] 6120 if (CGDebugInfo *DI = getModuleDebugInfo()) 6121 DI->EmitAndRetainType( 6122 getContext().getTypedefType(cast<TypedefNameDecl>(D))); 6123 break; 6124 6125 case Decl::Record: 6126 if (CGDebugInfo *DI = getModuleDebugInfo()) 6127 if (cast<RecordDecl>(D)->getDefinition()) 6128 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6129 break; 6130 6131 case Decl::Enum: 6132 if (CGDebugInfo *DI = getModuleDebugInfo()) 6133 if (cast<EnumDecl>(D)->getDefinition()) 6134 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); 6135 break; 6136 6137 default: 6138 // Make sure we handled everything we should, every other kind is a 6139 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 6140 // function. Need to recode Decl::Kind to do that easily. 6141 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 6142 break; 6143 } 6144 } 6145 6146 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 6147 // Do we need to generate coverage mapping? 6148 if (!CodeGenOpts.CoverageMapping) 6149 return; 6150 switch (D->getKind()) { 6151 case Decl::CXXConversion: 6152 case Decl::CXXMethod: 6153 case Decl::Function: 6154 case Decl::ObjCMethod: 6155 case Decl::CXXConstructor: 6156 case Decl::CXXDestructor: { 6157 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 6158 break; 6159 SourceManager &SM = getContext().getSourceManager(); 6160 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 6161 break; 6162 auto I = DeferredEmptyCoverageMappingDecls.find(D); 6163 if (I == DeferredEmptyCoverageMappingDecls.end()) 6164 DeferredEmptyCoverageMappingDecls[D] = true; 6165 break; 6166 } 6167 default: 6168 break; 6169 }; 6170 } 6171 6172 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 6173 // Do we need to generate coverage mapping? 6174 if (!CodeGenOpts.CoverageMapping) 6175 return; 6176 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 6177 if (Fn->isTemplateInstantiation()) 6178 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 6179 } 6180 auto I = DeferredEmptyCoverageMappingDecls.find(D); 6181 if (I == DeferredEmptyCoverageMappingDecls.end()) 6182 DeferredEmptyCoverageMappingDecls[D] = false; 6183 else 6184 I->second = false; 6185 } 6186 6187 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 6188 // We call takeVector() here to avoid use-after-free. 6189 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 6190 // we deserialize function bodies to emit coverage info for them, and that 6191 // deserializes more declarations. How should we handle that case? 6192 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 6193 if (!Entry.second) 6194 continue; 6195 const Decl *D = Entry.first; 6196 switch (D->getKind()) { 6197 case Decl::CXXConversion: 6198 case Decl::CXXMethod: 6199 case Decl::Function: 6200 case Decl::ObjCMethod: { 6201 CodeGenPGO PGO(*this); 6202 GlobalDecl GD(cast<FunctionDecl>(D)); 6203 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6204 getFunctionLinkage(GD)); 6205 break; 6206 } 6207 case Decl::CXXConstructor: { 6208 CodeGenPGO PGO(*this); 6209 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 6210 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6211 getFunctionLinkage(GD)); 6212 break; 6213 } 6214 case Decl::CXXDestructor: { 6215 CodeGenPGO PGO(*this); 6216 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 6217 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6218 getFunctionLinkage(GD)); 6219 break; 6220 } 6221 default: 6222 break; 6223 }; 6224 } 6225 } 6226 6227 void CodeGenModule::EmitMainVoidAlias() { 6228 // In order to transition away from "__original_main" gracefully, emit an 6229 // alias for "main" in the no-argument case so that libc can detect when 6230 // new-style no-argument main is in used. 6231 if (llvm::Function *F = getModule().getFunction("main")) { 6232 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && 6233 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) 6234 addUsedGlobal(llvm::GlobalAlias::create("__main_void", F)); 6235 } 6236 } 6237 6238 /// Turns the given pointer into a constant. 6239 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 6240 const void *Ptr) { 6241 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 6242 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 6243 return llvm::ConstantInt::get(i64, PtrInt); 6244 } 6245 6246 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 6247 llvm::NamedMDNode *&GlobalMetadata, 6248 GlobalDecl D, 6249 llvm::GlobalValue *Addr) { 6250 if (!GlobalMetadata) 6251 GlobalMetadata = 6252 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 6253 6254 // TODO: should we report variant information for ctors/dtors? 6255 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 6256 llvm::ConstantAsMetadata::get(GetPointerConstant( 6257 CGM.getLLVMContext(), D.getDecl()))}; 6258 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 6259 } 6260 6261 /// For each function which is declared within an extern "C" region and marked 6262 /// as 'used', but has internal linkage, create an alias from the unmangled 6263 /// name to the mangled name if possible. People expect to be able to refer 6264 /// to such functions with an unmangled name from inline assembly within the 6265 /// same translation unit. 6266 void CodeGenModule::EmitStaticExternCAliases() { 6267 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 6268 return; 6269 for (auto &I : StaticExternCValues) { 6270 IdentifierInfo *Name = I.first; 6271 llvm::GlobalValue *Val = I.second; 6272 if (Val && !getModule().getNamedValue(Name->getName())) 6273 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 6274 } 6275 } 6276 6277 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 6278 GlobalDecl &Result) const { 6279 auto Res = Manglings.find(MangledName); 6280 if (Res == Manglings.end()) 6281 return false; 6282 Result = Res->getValue(); 6283 return true; 6284 } 6285 6286 /// Emits metadata nodes associating all the global values in the 6287 /// current module with the Decls they came from. This is useful for 6288 /// projects using IR gen as a subroutine. 6289 /// 6290 /// Since there's currently no way to associate an MDNode directly 6291 /// with an llvm::GlobalValue, we create a global named metadata 6292 /// with the name 'clang.global.decl.ptrs'. 6293 void CodeGenModule::EmitDeclMetadata() { 6294 llvm::NamedMDNode *GlobalMetadata = nullptr; 6295 6296 for (auto &I : MangledDeclNames) { 6297 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 6298 // Some mangled names don't necessarily have an associated GlobalValue 6299 // in this module, e.g. if we mangled it for DebugInfo. 6300 if (Addr) 6301 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 6302 } 6303 } 6304 6305 /// Emits metadata nodes for all the local variables in the current 6306 /// function. 6307 void CodeGenFunction::EmitDeclMetadata() { 6308 if (LocalDeclMap.empty()) return; 6309 6310 llvm::LLVMContext &Context = getLLVMContext(); 6311 6312 // Find the unique metadata ID for this name. 6313 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 6314 6315 llvm::NamedMDNode *GlobalMetadata = nullptr; 6316 6317 for (auto &I : LocalDeclMap) { 6318 const Decl *D = I.first; 6319 llvm::Value *Addr = I.second.getPointer(); 6320 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 6321 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 6322 Alloca->setMetadata( 6323 DeclPtrKind, llvm::MDNode::get( 6324 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 6325 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 6326 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 6327 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 6328 } 6329 } 6330 } 6331 6332 void CodeGenModule::EmitVersionIdentMetadata() { 6333 llvm::NamedMDNode *IdentMetadata = 6334 TheModule.getOrInsertNamedMetadata("llvm.ident"); 6335 std::string Version = getClangFullVersion(); 6336 llvm::LLVMContext &Ctx = TheModule.getContext(); 6337 6338 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 6339 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 6340 } 6341 6342 void CodeGenModule::EmitCommandLineMetadata() { 6343 llvm::NamedMDNode *CommandLineMetadata = 6344 TheModule.getOrInsertNamedMetadata("llvm.commandline"); 6345 std::string CommandLine = getCodeGenOpts().RecordCommandLine; 6346 llvm::LLVMContext &Ctx = TheModule.getContext(); 6347 6348 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 6349 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 6350 } 6351 6352 void CodeGenModule::EmitCoverageFile() { 6353 if (getCodeGenOpts().CoverageDataFile.empty() && 6354 getCodeGenOpts().CoverageNotesFile.empty()) 6355 return; 6356 6357 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 6358 if (!CUNode) 6359 return; 6360 6361 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 6362 llvm::LLVMContext &Ctx = TheModule.getContext(); 6363 auto *CoverageDataFile = 6364 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 6365 auto *CoverageNotesFile = 6366 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 6367 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 6368 llvm::MDNode *CU = CUNode->getOperand(i); 6369 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 6370 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 6371 } 6372 } 6373 6374 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 6375 bool ForEH) { 6376 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 6377 // FIXME: should we even be calling this method if RTTI is disabled 6378 // and it's not for EH? 6379 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice || 6380 (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 6381 getTriple().isNVPTX())) 6382 return llvm::Constant::getNullValue(Int8PtrTy); 6383 6384 if (ForEH && Ty->isObjCObjectPointerType() && 6385 LangOpts.ObjCRuntime.isGNUFamily()) 6386 return ObjCRuntime->GetEHType(Ty); 6387 6388 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 6389 } 6390 6391 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 6392 // Do not emit threadprivates in simd-only mode. 6393 if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 6394 return; 6395 for (auto RefExpr : D->varlists()) { 6396 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 6397 bool PerformInit = 6398 VD->getAnyInitializer() && 6399 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 6400 /*ForRef=*/false); 6401 6402 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 6403 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 6404 VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 6405 CXXGlobalInits.push_back(InitFunction); 6406 } 6407 } 6408 6409 llvm::Metadata * 6410 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 6411 StringRef Suffix) { 6412 if (auto *FnType = T->getAs<FunctionProtoType>()) 6413 T = getContext().getFunctionType( 6414 FnType->getReturnType(), FnType->getParamTypes(), 6415 FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 6416 6417 llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 6418 if (InternalId) 6419 return InternalId; 6420 6421 if (isExternallyVisible(T->getLinkage())) { 6422 std::string OutName; 6423 llvm::raw_string_ostream Out(OutName); 6424 getCXXABI().getMangleContext().mangleTypeName(T, Out); 6425 Out << Suffix; 6426 6427 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 6428 } else { 6429 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 6430 llvm::ArrayRef<llvm::Metadata *>()); 6431 } 6432 6433 return InternalId; 6434 } 6435 6436 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 6437 return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 6438 } 6439 6440 llvm::Metadata * 6441 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 6442 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 6443 } 6444 6445 // Generalize pointer types to a void pointer with the qualifiers of the 6446 // originally pointed-to type, e.g. 'const char *' and 'char * const *' 6447 // generalize to 'const void *' while 'char *' and 'const char **' generalize to 6448 // 'void *'. 6449 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 6450 if (!Ty->isPointerType()) 6451 return Ty; 6452 6453 return Ctx.getPointerType( 6454 QualType(Ctx.VoidTy).withCVRQualifiers( 6455 Ty->getPointeeType().getCVRQualifiers())); 6456 } 6457 6458 // Apply type generalization to a FunctionType's return and argument types 6459 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 6460 if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 6461 SmallVector<QualType, 8> GeneralizedParams; 6462 for (auto &Param : FnType->param_types()) 6463 GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 6464 6465 return Ctx.getFunctionType( 6466 GeneralizeType(Ctx, FnType->getReturnType()), 6467 GeneralizedParams, FnType->getExtProtoInfo()); 6468 } 6469 6470 if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 6471 return Ctx.getFunctionNoProtoType( 6472 GeneralizeType(Ctx, FnType->getReturnType())); 6473 6474 llvm_unreachable("Encountered unknown FunctionType"); 6475 } 6476 6477 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 6478 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 6479 GeneralizedMetadataIdMap, ".generalized"); 6480 } 6481 6482 /// Returns whether this module needs the "all-vtables" type identifier. 6483 bool CodeGenModule::NeedAllVtablesTypeId() const { 6484 // Returns true if at least one of vtable-based CFI checkers is enabled and 6485 // is not in the trapping mode. 6486 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 6487 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 6488 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 6489 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 6490 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 6491 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 6492 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 6493 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 6494 } 6495 6496 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 6497 CharUnits Offset, 6498 const CXXRecordDecl *RD) { 6499 llvm::Metadata *MD = 6500 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 6501 VTable->addTypeMetadata(Offset.getQuantity(), MD); 6502 6503 if (CodeGenOpts.SanitizeCfiCrossDso) 6504 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 6505 VTable->addTypeMetadata(Offset.getQuantity(), 6506 llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 6507 6508 if (NeedAllVtablesTypeId()) { 6509 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 6510 VTable->addTypeMetadata(Offset.getQuantity(), MD); 6511 } 6512 } 6513 6514 llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 6515 if (!SanStats) 6516 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 6517 6518 return *SanStats; 6519 } 6520 6521 llvm::Value * 6522 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 6523 CodeGenFunction &CGF) { 6524 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 6525 auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 6526 auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 6527 auto *Call = CGF.EmitRuntimeCall( 6528 CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C}); 6529 return Call; 6530 } 6531 6532 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( 6533 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { 6534 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 6535 /* forPointeeType= */ true); 6536 } 6537 6538 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, 6539 LValueBaseInfo *BaseInfo, 6540 TBAAAccessInfo *TBAAInfo, 6541 bool forPointeeType) { 6542 if (TBAAInfo) 6543 *TBAAInfo = getTBAAAccessInfo(T); 6544 6545 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But 6546 // that doesn't return the information we need to compute BaseInfo. 6547 6548 // Honor alignment typedef attributes even on incomplete types. 6549 // We also honor them straight for C++ class types, even as pointees; 6550 // there's an expressivity gap here. 6551 if (auto TT = T->getAs<TypedefType>()) { 6552 if (auto Align = TT->getDecl()->getMaxAlignment()) { 6553 if (BaseInfo) 6554 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 6555 return getContext().toCharUnitsFromBits(Align); 6556 } 6557 } 6558 6559 bool AlignForArray = T->isArrayType(); 6560 6561 // Analyze the base element type, so we don't get confused by incomplete 6562 // array types. 6563 T = getContext().getBaseElementType(T); 6564 6565 if (T->isIncompleteType()) { 6566 // We could try to replicate the logic from 6567 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the 6568 // type is incomplete, so it's impossible to test. We could try to reuse 6569 // getTypeAlignIfKnown, but that doesn't return the information we need 6570 // to set BaseInfo. So just ignore the possibility that the alignment is 6571 // greater than one. 6572 if (BaseInfo) 6573 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 6574 return CharUnits::One(); 6575 } 6576 6577 if (BaseInfo) 6578 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 6579 6580 CharUnits Alignment; 6581 const CXXRecordDecl *RD; 6582 if (T.getQualifiers().hasUnaligned()) { 6583 Alignment = CharUnits::One(); 6584 } else if (forPointeeType && !AlignForArray && 6585 (RD = T->getAsCXXRecordDecl())) { 6586 // For C++ class pointees, we don't know whether we're pointing at a 6587 // base or a complete object, so we generally need to use the 6588 // non-virtual alignment. 6589 Alignment = getClassPointerAlignment(RD); 6590 } else { 6591 Alignment = getContext().getTypeAlignInChars(T); 6592 } 6593 6594 // Cap to the global maximum type alignment unless the alignment 6595 // was somehow explicit on the type. 6596 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 6597 if (Alignment.getQuantity() > MaxAlign && 6598 !getContext().isAlignmentRequired(T)) 6599 Alignment = CharUnits::fromQuantity(MaxAlign); 6600 } 6601 return Alignment; 6602 } 6603 6604 bool CodeGenModule::stopAutoInit() { 6605 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; 6606 if (StopAfter) { 6607 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is 6608 // used 6609 if (NumAutoVarInit >= StopAfter) { 6610 return true; 6611 } 6612 if (!NumAutoVarInit) { 6613 unsigned DiagID = getDiags().getCustomDiagID( 6614 DiagnosticsEngine::Warning, 6615 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 6616 "number of times ftrivial-auto-var-init=%1 gets applied."); 6617 getDiags().Report(DiagID) 6618 << StopAfter 6619 << (getContext().getLangOpts().getTrivialAutoVarInit() == 6620 LangOptions::TrivialAutoVarInitKind::Zero 6621 ? "zero" 6622 : "pattern"); 6623 } 6624 ++NumAutoVarInit; 6625 } 6626 return false; 6627 } 6628 6629 void CodeGenModule::printPostfixForExternalizedStaticVar( 6630 llvm::raw_ostream &OS) const { 6631 OS << "__static__" << getContext().getCUIDHash(); 6632 } 6633