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