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()); 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 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 4124 return llvm::ConstantExpr::getBitCast(F, PTy); 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(llvm::NoCFIValue::get(F), 4174 llvm::Type::getInt8PtrTy(VMContext)); 4175 } 4176 4177 static const FunctionDecl * 4178 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 4179 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 4180 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 4181 4182 IdentifierInfo &CII = C.Idents.get(Name); 4183 for (const auto *Result : DC->lookup(&CII)) 4184 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 4185 return FD; 4186 4187 if (!C.getLangOpts().CPlusPlus) 4188 return nullptr; 4189 4190 // Demangle the premangled name from getTerminateFn() 4191 IdentifierInfo &CXXII = 4192 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 4193 ? C.Idents.get("terminate") 4194 : C.Idents.get(Name); 4195 4196 for (const auto &N : {"__cxxabiv1", "std"}) { 4197 IdentifierInfo &NS = C.Idents.get(N); 4198 for (const auto *Result : DC->lookup(&NS)) { 4199 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 4200 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result)) 4201 for (const auto *Result : LSD->lookup(&NS)) 4202 if ((ND = dyn_cast<NamespaceDecl>(Result))) 4203 break; 4204 4205 if (ND) 4206 for (const auto *Result : ND->lookup(&CXXII)) 4207 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 4208 return FD; 4209 } 4210 } 4211 4212 return nullptr; 4213 } 4214 4215 /// CreateRuntimeFunction - Create a new runtime function with the specified 4216 /// type and name. 4217 llvm::FunctionCallee 4218 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 4219 llvm::AttributeList ExtraAttrs, bool Local, 4220 bool AssumeConvergent) { 4221 if (AssumeConvergent) { 4222 ExtraAttrs = 4223 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent); 4224 } 4225 4226 llvm::Constant *C = 4227 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 4228 /*DontDefer=*/false, /*IsThunk=*/false, 4229 ExtraAttrs); 4230 4231 if (auto *F = dyn_cast<llvm::Function>(C)) { 4232 if (F->empty()) { 4233 F->setCallingConv(getRuntimeCC()); 4234 4235 // In Windows Itanium environments, try to mark runtime functions 4236 // dllimport. For Mingw and MSVC, don't. We don't really know if the user 4237 // will link their standard library statically or dynamically. Marking 4238 // functions imported when they are not imported can cause linker errors 4239 // and warnings. 4240 if (!Local && getTriple().isWindowsItaniumEnvironment() && 4241 !getCodeGenOpts().LTOVisibilityPublicStd) { 4242 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 4243 if (!FD || FD->hasAttr<DLLImportAttr>()) { 4244 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 4245 F->setLinkage(llvm::GlobalValue::ExternalLinkage); 4246 } 4247 } 4248 setDSOLocal(F); 4249 } 4250 } 4251 4252 return {FTy, C}; 4253 } 4254 4255 /// isTypeConstant - Determine whether an object of this type can be emitted 4256 /// as a constant. 4257 /// 4258 /// If ExcludeCtor is true, the duration when the object's constructor runs 4259 /// will not be considered. The caller will need to verify that the object is 4260 /// not written to during its construction. 4261 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 4262 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 4263 return false; 4264 4265 if (Context.getLangOpts().CPlusPlus) { 4266 if (const CXXRecordDecl *Record 4267 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 4268 return ExcludeCtor && !Record->hasMutableFields() && 4269 Record->hasTrivialDestructor(); 4270 } 4271 4272 return true; 4273 } 4274 4275 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 4276 /// create and return an llvm GlobalVariable with the specified type and address 4277 /// space. If there is something in the module with the specified name, return 4278 /// it potentially bitcasted to the right type. 4279 /// 4280 /// If D is non-null, it specifies a decl that correspond to this. This is used 4281 /// to set the attributes on the global when it is first created. 4282 /// 4283 /// If IsForDefinition is true, it is guaranteed that an actual global with 4284 /// type Ty will be returned, not conversion of a variable with the same 4285 /// mangled name but some other type. 4286 llvm::Constant * 4287 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, 4288 LangAS AddrSpace, const VarDecl *D, 4289 ForDefinition_t IsForDefinition) { 4290 // Lookup the entry, lazily creating it if necessary. 4291 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4292 unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace); 4293 if (Entry) { 4294 if (WeakRefReferences.erase(Entry)) { 4295 if (D && !D->hasAttr<WeakAttr>()) 4296 Entry->setLinkage(llvm::Function::ExternalLinkage); 4297 } 4298 4299 // Handle dropped DLL attributes. 4300 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && 4301 !shouldMapVisibilityToDLLExport(D)) 4302 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 4303 4304 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 4305 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 4306 4307 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) 4308 return Entry; 4309 4310 // If there are two attempts to define the same mangled name, issue an 4311 // error. 4312 if (IsForDefinition && !Entry->isDeclaration()) { 4313 GlobalDecl OtherGD; 4314 const VarDecl *OtherD; 4315 4316 // Check that D is not yet in DiagnosedConflictingDefinitions is required 4317 // to make sure that we issue an error only once. 4318 if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 4319 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 4320 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 4321 OtherD->hasInit() && 4322 DiagnosedConflictingDefinitions.insert(D).second) { 4323 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 4324 << MangledName; 4325 getDiags().Report(OtherGD.getDecl()->getLocation(), 4326 diag::note_previous_definition); 4327 } 4328 } 4329 4330 // Make sure the result is of the correct type. 4331 if (Entry->getType()->getAddressSpace() != TargetAS) { 4332 return llvm::ConstantExpr::getAddrSpaceCast(Entry, 4333 Ty->getPointerTo(TargetAS)); 4334 } 4335 4336 // (If global is requested for a definition, we always need to create a new 4337 // global, not just return a bitcast.) 4338 if (!IsForDefinition) 4339 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS)); 4340 } 4341 4342 auto DAddrSpace = GetGlobalVarAddressSpace(D); 4343 4344 auto *GV = new llvm::GlobalVariable( 4345 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, 4346 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, 4347 getContext().getTargetAddressSpace(DAddrSpace)); 4348 4349 // If we already created a global with the same mangled name (but different 4350 // type) before, take its name and remove it from its parent. 4351 if (Entry) { 4352 GV->takeName(Entry); 4353 4354 if (!Entry->use_empty()) { 4355 llvm::Constant *NewPtrForOldDecl = 4356 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 4357 Entry->replaceAllUsesWith(NewPtrForOldDecl); 4358 } 4359 4360 Entry->eraseFromParent(); 4361 } 4362 4363 // This is the first use or definition of a mangled name. If there is a 4364 // deferred decl with this name, remember that we need to emit it at the end 4365 // of the file. 4366 auto DDI = DeferredDecls.find(MangledName); 4367 if (DDI != DeferredDecls.end()) { 4368 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 4369 // list, and remove it from DeferredDecls (since we don't need it anymore). 4370 addDeferredDeclToEmit(DDI->second); 4371 EmittedDeferredDecls[DDI->first] = DDI->second; 4372 DeferredDecls.erase(DDI); 4373 } 4374 4375 // Handle things which are present even on external declarations. 4376 if (D) { 4377 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 4378 getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 4379 4380 // FIXME: This code is overly simple and should be merged with other global 4381 // handling. 4382 GV->setConstant(isTypeConstant(D->getType(), false)); 4383 4384 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4385 4386 setLinkageForGV(GV, D); 4387 4388 if (D->getTLSKind()) { 4389 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4390 CXXThreadLocals.push_back(D); 4391 setTLSMode(GV, *D); 4392 } 4393 4394 setGVProperties(GV, D); 4395 4396 // If required by the ABI, treat declarations of static data members with 4397 // inline initializers as definitions. 4398 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 4399 EmitGlobalVarDefinition(D); 4400 } 4401 4402 // Emit section information for extern variables. 4403 if (D->hasExternalStorage()) { 4404 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 4405 GV->setSection(SA->getName()); 4406 } 4407 4408 // Handle XCore specific ABI requirements. 4409 if (getTriple().getArch() == llvm::Triple::xcore && 4410 D->getLanguageLinkage() == CLanguageLinkage && 4411 D->getType().isConstant(Context) && 4412 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 4413 GV->setSection(".cp.rodata"); 4414 4415 // Check if we a have a const declaration with an initializer, we may be 4416 // able to emit it as available_externally to expose it's value to the 4417 // optimizer. 4418 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 4419 D->getType().isConstQualified() && !GV->hasInitializer() && 4420 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 4421 const auto *Record = 4422 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 4423 bool HasMutableFields = Record && Record->hasMutableFields(); 4424 if (!HasMutableFields) { 4425 const VarDecl *InitDecl; 4426 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4427 if (InitExpr) { 4428 ConstantEmitter emitter(*this); 4429 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 4430 if (Init) { 4431 auto *InitType = Init->getType(); 4432 if (GV->getValueType() != InitType) { 4433 // The type of the initializer does not match the definition. 4434 // This happens when an initializer has a different type from 4435 // the type of the global (because of padding at the end of a 4436 // structure for instance). 4437 GV->setName(StringRef()); 4438 // Make a new global with the correct type, this is now guaranteed 4439 // to work. 4440 auto *NewGV = cast<llvm::GlobalVariable>( 4441 GetAddrOfGlobalVar(D, InitType, IsForDefinition) 4442 ->stripPointerCasts()); 4443 4444 // Erase the old global, since it is no longer used. 4445 GV->eraseFromParent(); 4446 GV = NewGV; 4447 } else { 4448 GV->setInitializer(Init); 4449 GV->setConstant(true); 4450 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 4451 } 4452 emitter.finalize(GV); 4453 } 4454 } 4455 } 4456 } 4457 } 4458 4459 if (GV->isDeclaration()) { 4460 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 4461 // External HIP managed variables needed to be recorded for transformation 4462 // in both device and host compilations. 4463 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && 4464 D->hasExternalStorage()) 4465 getCUDARuntime().handleVarRegistration(D, *GV); 4466 } 4467 4468 if (D) 4469 SanitizerMD->reportGlobal(GV, *D); 4470 4471 LangAS ExpectedAS = 4472 D ? D->getType().getAddressSpace() 4473 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 4474 assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); 4475 if (DAddrSpace != ExpectedAS) { 4476 return getTargetCodeGenInfo().performAddrSpaceCast( 4477 *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS)); 4478 } 4479 4480 return GV; 4481 } 4482 4483 llvm::Constant * 4484 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 4485 const Decl *D = GD.getDecl(); 4486 4487 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 4488 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 4489 /*DontDefer=*/false, IsForDefinition); 4490 4491 if (isa<CXXMethodDecl>(D)) { 4492 auto FInfo = 4493 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 4494 auto Ty = getTypes().GetFunctionType(*FInfo); 4495 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4496 IsForDefinition); 4497 } 4498 4499 if (isa<FunctionDecl>(D)) { 4500 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4501 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4502 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4503 IsForDefinition); 4504 } 4505 4506 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 4507 } 4508 4509 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 4510 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 4511 unsigned Alignment) { 4512 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 4513 llvm::GlobalVariable *OldGV = nullptr; 4514 4515 if (GV) { 4516 // Check if the variable has the right type. 4517 if (GV->getValueType() == Ty) 4518 return GV; 4519 4520 // Because C++ name mangling, the only way we can end up with an already 4521 // existing global with the same name is if it has been declared extern "C". 4522 assert(GV->isDeclaration() && "Declaration has wrong type!"); 4523 OldGV = GV; 4524 } 4525 4526 // Create a new variable. 4527 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 4528 Linkage, nullptr, Name); 4529 4530 if (OldGV) { 4531 // Replace occurrences of the old variable if needed. 4532 GV->takeName(OldGV); 4533 4534 if (!OldGV->use_empty()) { 4535 llvm::Constant *NewPtrForOldDecl = 4536 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 4537 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 4538 } 4539 4540 OldGV->eraseFromParent(); 4541 } 4542 4543 if (supportsCOMDAT() && GV->isWeakForLinker() && 4544 !GV->hasAvailableExternallyLinkage()) 4545 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 4546 4547 GV->setAlignment(llvm::MaybeAlign(Alignment)); 4548 4549 return GV; 4550 } 4551 4552 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 4553 /// given global variable. If Ty is non-null and if the global doesn't exist, 4554 /// then it will be created with the specified type instead of whatever the 4555 /// normal requested type would be. If IsForDefinition is true, it is guaranteed 4556 /// that an actual global with type Ty will be returned, not conversion of a 4557 /// variable with the same mangled name but some other type. 4558 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 4559 llvm::Type *Ty, 4560 ForDefinition_t IsForDefinition) { 4561 assert(D->hasGlobalStorage() && "Not a global variable"); 4562 QualType ASTTy = D->getType(); 4563 if (!Ty) 4564 Ty = getTypes().ConvertTypeForMem(ASTTy); 4565 4566 StringRef MangledName = getMangledName(D); 4567 return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D, 4568 IsForDefinition); 4569 } 4570 4571 /// CreateRuntimeVariable - Create a new runtime global variable with the 4572 /// specified type and name. 4573 llvm::Constant * 4574 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 4575 StringRef Name) { 4576 LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global 4577 : LangAS::Default; 4578 auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr); 4579 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 4580 return Ret; 4581 } 4582 4583 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 4584 assert(!D->getInit() && "Cannot emit definite definitions here!"); 4585 4586 StringRef MangledName = getMangledName(D); 4587 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 4588 4589 // We already have a definition, not declaration, with the same mangled name. 4590 // Emitting of declaration is not required (and actually overwrites emitted 4591 // definition). 4592 if (GV && !GV->isDeclaration()) 4593 return; 4594 4595 // If we have not seen a reference to this variable yet, place it into the 4596 // deferred declarations table to be emitted if needed later. 4597 if (!MustBeEmitted(D) && !GV) { 4598 DeferredDecls[MangledName] = D; 4599 return; 4600 } 4601 4602 // The tentative definition is the only definition. 4603 EmitGlobalVarDefinition(D); 4604 } 4605 4606 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 4607 EmitExternalVarDeclaration(D); 4608 } 4609 4610 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 4611 return Context.toCharUnitsFromBits( 4612 getDataLayout().getTypeStoreSizeInBits(Ty)); 4613 } 4614 4615 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 4616 if (LangOpts.OpenCL) { 4617 LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 4618 assert(AS == LangAS::opencl_global || 4619 AS == LangAS::opencl_global_device || 4620 AS == LangAS::opencl_global_host || 4621 AS == LangAS::opencl_constant || 4622 AS == LangAS::opencl_local || 4623 AS >= LangAS::FirstTargetAddressSpace); 4624 return AS; 4625 } 4626 4627 if (LangOpts.SYCLIsDevice && 4628 (!D || D->getType().getAddressSpace() == LangAS::Default)) 4629 return LangAS::sycl_global; 4630 4631 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 4632 if (D && D->hasAttr<CUDAConstantAttr>()) 4633 return LangAS::cuda_constant; 4634 else if (D && D->hasAttr<CUDASharedAttr>()) 4635 return LangAS::cuda_shared; 4636 else if (D && D->hasAttr<CUDADeviceAttr>()) 4637 return LangAS::cuda_device; 4638 else if (D && D->getType().isConstQualified()) 4639 return LangAS::cuda_constant; 4640 else 4641 return LangAS::cuda_device; 4642 } 4643 4644 if (LangOpts.OpenMP) { 4645 LangAS AS; 4646 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 4647 return AS; 4648 } 4649 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 4650 } 4651 4652 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { 4653 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 4654 if (LangOpts.OpenCL) 4655 return LangAS::opencl_constant; 4656 if (LangOpts.SYCLIsDevice) 4657 return LangAS::sycl_global; 4658 if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV()) 4659 // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V) 4660 // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up 4661 // with OpVariable instructions with Generic storage class which is not 4662 // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V 4663 // UniformConstant storage class is not viable as pointers to it may not be 4664 // casted to Generic pointers which are used to model HIP's "flat" pointers. 4665 return LangAS::cuda_device; 4666 if (auto AS = getTarget().getConstantAddressSpace()) 4667 return *AS; 4668 return LangAS::Default; 4669 } 4670 4671 // In address space agnostic languages, string literals are in default address 4672 // space in AST. However, certain targets (e.g. amdgcn) request them to be 4673 // emitted in constant address space in LLVM IR. To be consistent with other 4674 // parts of AST, string literal global variables in constant address space 4675 // need to be casted to default address space before being put into address 4676 // map and referenced by other part of CodeGen. 4677 // In OpenCL, string literals are in constant address space in AST, therefore 4678 // they should not be casted to default address space. 4679 static llvm::Constant * 4680 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 4681 llvm::GlobalVariable *GV) { 4682 llvm::Constant *Cast = GV; 4683 if (!CGM.getLangOpts().OpenCL) { 4684 auto AS = CGM.GetGlobalConstantAddressSpace(); 4685 if (AS != LangAS::Default) 4686 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 4687 CGM, GV, AS, LangAS::Default, 4688 GV->getValueType()->getPointerTo( 4689 CGM.getContext().getTargetAddressSpace(LangAS::Default))); 4690 } 4691 return Cast; 4692 } 4693 4694 template<typename SomeDecl> 4695 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 4696 llvm::GlobalValue *GV) { 4697 if (!getLangOpts().CPlusPlus) 4698 return; 4699 4700 // Must have 'used' attribute, or else inline assembly can't rely on 4701 // the name existing. 4702 if (!D->template hasAttr<UsedAttr>()) 4703 return; 4704 4705 // Must have internal linkage and an ordinary name. 4706 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 4707 return; 4708 4709 // Must be in an extern "C" context. Entities declared directly within 4710 // a record are not extern "C" even if the record is in such a context. 4711 const SomeDecl *First = D->getFirstDecl(); 4712 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 4713 return; 4714 4715 // OK, this is an internal linkage entity inside an extern "C" linkage 4716 // specification. Make a note of that so we can give it the "expected" 4717 // mangled name if nothing else is using that name. 4718 std::pair<StaticExternCMap::iterator, bool> R = 4719 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 4720 4721 // If we have multiple internal linkage entities with the same name 4722 // in extern "C" regions, none of them gets that name. 4723 if (!R.second) 4724 R.first->second = nullptr; 4725 } 4726 4727 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 4728 if (!CGM.supportsCOMDAT()) 4729 return false; 4730 4731 if (D.hasAttr<SelectAnyAttr>()) 4732 return true; 4733 4734 GVALinkage Linkage; 4735 if (auto *VD = dyn_cast<VarDecl>(&D)) 4736 Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 4737 else 4738 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 4739 4740 switch (Linkage) { 4741 case GVA_Internal: 4742 case GVA_AvailableExternally: 4743 case GVA_StrongExternal: 4744 return false; 4745 case GVA_DiscardableODR: 4746 case GVA_StrongODR: 4747 return true; 4748 } 4749 llvm_unreachable("No such linkage"); 4750 } 4751 4752 void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 4753 llvm::GlobalObject &GO) { 4754 if (!shouldBeInCOMDAT(*this, D)) 4755 return; 4756 GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 4757 } 4758 4759 /// Pass IsTentative as true if you want to create a tentative definition. 4760 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 4761 bool IsTentative) { 4762 // OpenCL global variables of sampler type are translated to function calls, 4763 // therefore no need to be translated. 4764 QualType ASTTy = D->getType(); 4765 if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 4766 return; 4767 4768 // If this is OpenMP device, check if it is legal to emit this global 4769 // normally. 4770 if (LangOpts.OpenMPIsDevice && OpenMPRuntime && 4771 OpenMPRuntime->emitTargetGlobalVariable(D)) 4772 return; 4773 4774 llvm::TrackingVH<llvm::Constant> Init; 4775 bool NeedsGlobalCtor = false; 4776 bool NeedsGlobalDtor = 4777 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 4778 4779 const VarDecl *InitDecl; 4780 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4781 4782 Optional<ConstantEmitter> emitter; 4783 4784 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 4785 // as part of their declaration." Sema has already checked for 4786 // error cases, so we just need to set Init to UndefValue. 4787 bool IsCUDASharedVar = 4788 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 4789 // Shadows of initialized device-side global variables are also left 4790 // undefined. 4791 // Managed Variables should be initialized on both host side and device side. 4792 bool IsCUDAShadowVar = 4793 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4794 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 4795 D->hasAttr<CUDASharedAttr>()); 4796 bool IsCUDADeviceShadowVar = 4797 getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4798 (D->getType()->isCUDADeviceBuiltinSurfaceType() || 4799 D->getType()->isCUDADeviceBuiltinTextureType()); 4800 if (getLangOpts().CUDA && 4801 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) 4802 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 4803 else if (D->hasAttr<LoaderUninitializedAttr>()) 4804 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 4805 else if (!InitExpr) { 4806 // This is a tentative definition; tentative definitions are 4807 // implicitly initialized with { 0 }. 4808 // 4809 // Note that tentative definitions are only emitted at the end of 4810 // a translation unit, so they should never have incomplete 4811 // type. In addition, EmitTentativeDefinition makes sure that we 4812 // never attempt to emit a tentative definition if a real one 4813 // exists. A use may still exists, however, so we still may need 4814 // to do a RAUW. 4815 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 4816 Init = EmitNullConstant(D->getType()); 4817 } else { 4818 initializedGlobalDecl = GlobalDecl(D); 4819 emitter.emplace(*this); 4820 llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl); 4821 if (!Initializer) { 4822 QualType T = InitExpr->getType(); 4823 if (D->getType()->isReferenceType()) 4824 T = D->getType(); 4825 4826 if (getLangOpts().CPlusPlus) { 4827 if (InitDecl->hasFlexibleArrayInit(getContext())) 4828 ErrorUnsupported(D, "flexible array initializer"); 4829 Init = EmitNullConstant(T); 4830 NeedsGlobalCtor = true; 4831 } else { 4832 ErrorUnsupported(D, "static initializer"); 4833 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 4834 } 4835 } else { 4836 Init = Initializer; 4837 // We don't need an initializer, so remove the entry for the delayed 4838 // initializer position (just in case this entry was delayed) if we 4839 // also don't need to register a destructor. 4840 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 4841 DelayedCXXInitPosition.erase(D); 4842 4843 #ifndef NDEBUG 4844 CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) + 4845 InitDecl->getFlexibleArrayInitChars(getContext()); 4846 CharUnits CstSize = CharUnits::fromQuantity( 4847 getDataLayout().getTypeAllocSize(Init->getType())); 4848 assert(VarSize == CstSize && "Emitted constant has unexpected size"); 4849 #endif 4850 } 4851 } 4852 4853 llvm::Type* InitType = Init->getType(); 4854 llvm::Constant *Entry = 4855 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 4856 4857 // Strip off pointer casts if we got them. 4858 Entry = Entry->stripPointerCasts(); 4859 4860 // Entry is now either a Function or GlobalVariable. 4861 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 4862 4863 // We have a definition after a declaration with the wrong type. 4864 // We must make a new GlobalVariable* and update everything that used OldGV 4865 // (a declaration or tentative definition) with the new GlobalVariable* 4866 // (which will be a definition). 4867 // 4868 // This happens if there is a prototype for a global (e.g. 4869 // "extern int x[];") and then a definition of a different type (e.g. 4870 // "int x[10];"). This also happens when an initializer has a different type 4871 // from the type of the global (this happens with unions). 4872 if (!GV || GV->getValueType() != InitType || 4873 GV->getType()->getAddressSpace() != 4874 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 4875 4876 // Move the old entry aside so that we'll create a new one. 4877 Entry->setName(StringRef()); 4878 4879 // Make a new global with the correct type, this is now guaranteed to work. 4880 GV = cast<llvm::GlobalVariable>( 4881 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 4882 ->stripPointerCasts()); 4883 4884 // Replace all uses of the old global with the new global 4885 llvm::Constant *NewPtrForOldDecl = 4886 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, 4887 Entry->getType()); 4888 Entry->replaceAllUsesWith(NewPtrForOldDecl); 4889 4890 // Erase the old global, since it is no longer used. 4891 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 4892 } 4893 4894 MaybeHandleStaticInExternC(D, GV); 4895 4896 if (D->hasAttr<AnnotateAttr>()) 4897 AddGlobalAnnotations(D, GV); 4898 4899 // Set the llvm linkage type as appropriate. 4900 llvm::GlobalValue::LinkageTypes Linkage = 4901 getLLVMLinkageVarDefinition(D, GV->isConstant()); 4902 4903 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 4904 // the device. [...]" 4905 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 4906 // __device__, declares a variable that: [...] 4907 // Is accessible from all the threads within the grid and from the host 4908 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 4909 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 4910 if (GV && LangOpts.CUDA) { 4911 if (LangOpts.CUDAIsDevice) { 4912 if (Linkage != llvm::GlobalValue::InternalLinkage && 4913 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 4914 D->getType()->isCUDADeviceBuiltinSurfaceType() || 4915 D->getType()->isCUDADeviceBuiltinTextureType())) 4916 GV->setExternallyInitialized(true); 4917 } else { 4918 getCUDARuntime().internalizeDeviceSideVar(D, Linkage); 4919 } 4920 getCUDARuntime().handleVarRegistration(D, *GV); 4921 } 4922 4923 GV->setInitializer(Init); 4924 if (emitter) 4925 emitter->finalize(GV); 4926 4927 // If it is safe to mark the global 'constant', do so now. 4928 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 4929 isTypeConstant(D->getType(), true)); 4930 4931 // If it is in a read-only section, mark it 'constant'. 4932 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 4933 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 4934 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 4935 GV->setConstant(true); 4936 } 4937 4938 CharUnits AlignVal = getContext().getDeclAlign(D); 4939 // Check for alignment specifed in an 'omp allocate' directive. 4940 if (llvm::Optional<CharUnits> AlignValFromAllocate = 4941 getOMPAllocateAlignment(D)) 4942 AlignVal = *AlignValFromAllocate; 4943 GV->setAlignment(AlignVal.getAsAlign()); 4944 4945 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper 4946 // function is only defined alongside the variable, not also alongside 4947 // callers. Normally, all accesses to a thread_local go through the 4948 // thread-wrapper in order to ensure initialization has occurred, underlying 4949 // variable will never be used other than the thread-wrapper, so it can be 4950 // converted to internal linkage. 4951 // 4952 // However, if the variable has the 'constinit' attribute, it _can_ be 4953 // referenced directly, without calling the thread-wrapper, so the linkage 4954 // must not be changed. 4955 // 4956 // Additionally, if the variable isn't plain external linkage, e.g. if it's 4957 // weak or linkonce, the de-duplication semantics are important to preserve, 4958 // so we don't change the linkage. 4959 if (D->getTLSKind() == VarDecl::TLS_Dynamic && 4960 Linkage == llvm::GlobalValue::ExternalLinkage && 4961 Context.getTargetInfo().getTriple().isOSDarwin() && 4962 !D->hasAttr<ConstInitAttr>()) 4963 Linkage = llvm::GlobalValue::InternalLinkage; 4964 4965 GV->setLinkage(Linkage); 4966 if (D->hasAttr<DLLImportAttr>()) 4967 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 4968 else if (D->hasAttr<DLLExportAttr>()) 4969 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 4970 else 4971 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 4972 4973 if (Linkage == llvm::GlobalVariable::CommonLinkage) { 4974 // common vars aren't constant even if declared const. 4975 GV->setConstant(false); 4976 // Tentative definition of global variables may be initialized with 4977 // non-zero null pointers. In this case they should have weak linkage 4978 // since common linkage must have zero initializer and must not have 4979 // explicit section therefore cannot have non-zero initial value. 4980 if (!GV->getInitializer()->isNullValue()) 4981 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 4982 } 4983 4984 setNonAliasAttributes(D, GV); 4985 4986 if (D->getTLSKind() && !GV->isThreadLocal()) { 4987 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4988 CXXThreadLocals.push_back(D); 4989 setTLSMode(GV, *D); 4990 } 4991 4992 maybeSetTrivialComdat(*D, *GV); 4993 4994 // Emit the initializer function if necessary. 4995 if (NeedsGlobalCtor || NeedsGlobalDtor) 4996 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 4997 4998 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor); 4999 5000 // Emit global variable debug information. 5001 if (CGDebugInfo *DI = getModuleDebugInfo()) 5002 if (getCodeGenOpts().hasReducedDebugInfo()) 5003 DI->EmitGlobalVariable(GV, D); 5004 } 5005 5006 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { 5007 if (CGDebugInfo *DI = getModuleDebugInfo()) 5008 if (getCodeGenOpts().hasReducedDebugInfo()) { 5009 QualType ASTTy = D->getType(); 5010 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); 5011 llvm::Constant *GV = 5012 GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D); 5013 DI->EmitExternalVariable( 5014 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); 5015 } 5016 } 5017 5018 static bool isVarDeclStrongDefinition(const ASTContext &Context, 5019 CodeGenModule &CGM, const VarDecl *D, 5020 bool NoCommon) { 5021 // Don't give variables common linkage if -fno-common was specified unless it 5022 // was overridden by a NoCommon attribute. 5023 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 5024 return true; 5025 5026 // C11 6.9.2/2: 5027 // A declaration of an identifier for an object that has file scope without 5028 // an initializer, and without a storage-class specifier or with the 5029 // storage-class specifier static, constitutes a tentative definition. 5030 if (D->getInit() || D->hasExternalStorage()) 5031 return true; 5032 5033 // A variable cannot be both common and exist in a section. 5034 if (D->hasAttr<SectionAttr>()) 5035 return true; 5036 5037 // A variable cannot be both common and exist in a section. 5038 // We don't try to determine which is the right section in the front-end. 5039 // If no specialized section name is applicable, it will resort to default. 5040 if (D->hasAttr<PragmaClangBSSSectionAttr>() || 5041 D->hasAttr<PragmaClangDataSectionAttr>() || 5042 D->hasAttr<PragmaClangRelroSectionAttr>() || 5043 D->hasAttr<PragmaClangRodataSectionAttr>()) 5044 return true; 5045 5046 // Thread local vars aren't considered common linkage. 5047 if (D->getTLSKind()) 5048 return true; 5049 5050 // Tentative definitions marked with WeakImportAttr are true definitions. 5051 if (D->hasAttr<WeakImportAttr>()) 5052 return true; 5053 5054 // A variable cannot be both common and exist in a comdat. 5055 if (shouldBeInCOMDAT(CGM, *D)) 5056 return true; 5057 5058 // Declarations with a required alignment do not have common linkage in MSVC 5059 // mode. 5060 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5061 if (D->hasAttr<AlignedAttr>()) 5062 return true; 5063 QualType VarType = D->getType(); 5064 if (Context.isAlignmentRequired(VarType)) 5065 return true; 5066 5067 if (const auto *RT = VarType->getAs<RecordType>()) { 5068 const RecordDecl *RD = RT->getDecl(); 5069 for (const FieldDecl *FD : RD->fields()) { 5070 if (FD->isBitField()) 5071 continue; 5072 if (FD->hasAttr<AlignedAttr>()) 5073 return true; 5074 if (Context.isAlignmentRequired(FD->getType())) 5075 return true; 5076 } 5077 } 5078 } 5079 5080 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 5081 // common symbols, so symbols with greater alignment requirements cannot be 5082 // common. 5083 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 5084 // alignments for common symbols via the aligncomm directive, so this 5085 // restriction only applies to MSVC environments. 5086 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 5087 Context.getTypeAlignIfKnown(D->getType()) > 5088 Context.toBits(CharUnits::fromQuantity(32))) 5089 return true; 5090 5091 return false; 5092 } 5093 5094 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 5095 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 5096 if (Linkage == GVA_Internal) 5097 return llvm::Function::InternalLinkage; 5098 5099 if (D->hasAttr<WeakAttr>()) 5100 return llvm::GlobalVariable::WeakAnyLinkage; 5101 5102 if (const auto *FD = D->getAsFunction()) 5103 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 5104 return llvm::GlobalVariable::LinkOnceAnyLinkage; 5105 5106 // We are guaranteed to have a strong definition somewhere else, 5107 // so we can use available_externally linkage. 5108 if (Linkage == GVA_AvailableExternally) 5109 return llvm::GlobalValue::AvailableExternallyLinkage; 5110 5111 // Note that Apple's kernel linker doesn't support symbol 5112 // coalescing, so we need to avoid linkonce and weak linkages there. 5113 // Normally, this means we just map to internal, but for explicit 5114 // instantiations we'll map to external. 5115 5116 // In C++, the compiler has to emit a definition in every translation unit 5117 // that references the function. We should use linkonce_odr because 5118 // a) if all references in this translation unit are optimized away, we 5119 // don't need to codegen it. b) if the function persists, it needs to be 5120 // merged with other definitions. c) C++ has the ODR, so we know the 5121 // definition is dependable. 5122 if (Linkage == GVA_DiscardableODR) 5123 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 5124 : llvm::Function::InternalLinkage; 5125 5126 // An explicit instantiation of a template has weak linkage, since 5127 // explicit instantiations can occur in multiple translation units 5128 // and must all be equivalent. However, we are not allowed to 5129 // throw away these explicit instantiations. 5130 // 5131 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, 5132 // so say that CUDA templates are either external (for kernels) or internal. 5133 // This lets llvm perform aggressive inter-procedural optimizations. For 5134 // -fgpu-rdc case, device function calls across multiple TU's are allowed, 5135 // therefore we need to follow the normal linkage paradigm. 5136 if (Linkage == GVA_StrongODR) { 5137 if (getLangOpts().AppleKext) 5138 return llvm::Function::ExternalLinkage; 5139 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 5140 !getLangOpts().GPURelocatableDeviceCode) 5141 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 5142 : llvm::Function::InternalLinkage; 5143 return llvm::Function::WeakODRLinkage; 5144 } 5145 5146 // C++ doesn't have tentative definitions and thus cannot have common 5147 // linkage. 5148 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 5149 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 5150 CodeGenOpts.NoCommon)) 5151 return llvm::GlobalVariable::CommonLinkage; 5152 5153 // selectany symbols are externally visible, so use weak instead of 5154 // linkonce. MSVC optimizes away references to const selectany globals, so 5155 // all definitions should be the same and ODR linkage should be used. 5156 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 5157 if (D->hasAttr<SelectAnyAttr>()) 5158 return llvm::GlobalVariable::WeakODRLinkage; 5159 5160 // Otherwise, we have strong external linkage. 5161 assert(Linkage == GVA_StrongExternal); 5162 return llvm::GlobalVariable::ExternalLinkage; 5163 } 5164 5165 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 5166 const VarDecl *VD, bool IsConstant) { 5167 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 5168 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 5169 } 5170 5171 /// Replace the uses of a function that was declared with a non-proto type. 5172 /// We want to silently drop extra arguments from call sites 5173 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 5174 llvm::Function *newFn) { 5175 // Fast path. 5176 if (old->use_empty()) return; 5177 5178 llvm::Type *newRetTy = newFn->getReturnType(); 5179 SmallVector<llvm::Value*, 4> newArgs; 5180 5181 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 5182 ui != ue; ) { 5183 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 5184 llvm::User *user = use->getUser(); 5185 5186 // Recognize and replace uses of bitcasts. Most calls to 5187 // unprototyped functions will use bitcasts. 5188 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 5189 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 5190 replaceUsesOfNonProtoConstant(bitcast, newFn); 5191 continue; 5192 } 5193 5194 // Recognize calls to the function. 5195 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 5196 if (!callSite) continue; 5197 if (!callSite->isCallee(&*use)) 5198 continue; 5199 5200 // If the return types don't match exactly, then we can't 5201 // transform this call unless it's dead. 5202 if (callSite->getType() != newRetTy && !callSite->use_empty()) 5203 continue; 5204 5205 // Get the call site's attribute list. 5206 SmallVector<llvm::AttributeSet, 8> newArgAttrs; 5207 llvm::AttributeList oldAttrs = callSite->getAttributes(); 5208 5209 // If the function was passed too few arguments, don't transform. 5210 unsigned newNumArgs = newFn->arg_size(); 5211 if (callSite->arg_size() < newNumArgs) 5212 continue; 5213 5214 // If extra arguments were passed, we silently drop them. 5215 // If any of the types mismatch, we don't transform. 5216 unsigned argNo = 0; 5217 bool dontTransform = false; 5218 for (llvm::Argument &A : newFn->args()) { 5219 if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 5220 dontTransform = true; 5221 break; 5222 } 5223 5224 // Add any parameter attributes. 5225 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo)); 5226 argNo++; 5227 } 5228 if (dontTransform) 5229 continue; 5230 5231 // Okay, we can transform this. Create the new call instruction and copy 5232 // over the required information. 5233 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 5234 5235 // Copy over any operand bundles. 5236 SmallVector<llvm::OperandBundleDef, 1> newBundles; 5237 callSite->getOperandBundlesAsDefs(newBundles); 5238 5239 llvm::CallBase *newCall; 5240 if (isa<llvm::CallInst>(callSite)) { 5241 newCall = 5242 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 5243 } else { 5244 auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 5245 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 5246 oldInvoke->getUnwindDest(), newArgs, 5247 newBundles, "", callSite); 5248 } 5249 newArgs.clear(); // for the next iteration 5250 5251 if (!newCall->getType()->isVoidTy()) 5252 newCall->takeName(callSite); 5253 newCall->setAttributes( 5254 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(), 5255 oldAttrs.getRetAttrs(), newArgAttrs)); 5256 newCall->setCallingConv(callSite->getCallingConv()); 5257 5258 // Finally, remove the old call, replacing any uses with the new one. 5259 if (!callSite->use_empty()) 5260 callSite->replaceAllUsesWith(newCall); 5261 5262 // Copy debug location attached to CI. 5263 if (callSite->getDebugLoc()) 5264 newCall->setDebugLoc(callSite->getDebugLoc()); 5265 5266 callSite->eraseFromParent(); 5267 } 5268 } 5269 5270 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 5271 /// implement a function with no prototype, e.g. "int foo() {}". If there are 5272 /// existing call uses of the old function in the module, this adjusts them to 5273 /// call the new function directly. 5274 /// 5275 /// This is not just a cleanup: the always_inline pass requires direct calls to 5276 /// functions to be able to inline them. If there is a bitcast in the way, it 5277 /// won't inline them. Instcombine normally deletes these calls, but it isn't 5278 /// run at -O0. 5279 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 5280 llvm::Function *NewFn) { 5281 // If we're redefining a global as a function, don't transform it. 5282 if (!isa<llvm::Function>(Old)) return; 5283 5284 replaceUsesOfNonProtoConstant(Old, NewFn); 5285 } 5286 5287 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 5288 auto DK = VD->isThisDeclarationADefinition(); 5289 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 5290 return; 5291 5292 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 5293 // If we have a definition, this might be a deferred decl. If the 5294 // instantiation is explicit, make sure we emit it at the end. 5295 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 5296 GetAddrOfGlobalVar(VD); 5297 5298 EmitTopLevelDecl(VD); 5299 } 5300 5301 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 5302 llvm::GlobalValue *GV) { 5303 const auto *D = cast<FunctionDecl>(GD.getDecl()); 5304 5305 // Compute the function info and LLVM type. 5306 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 5307 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 5308 5309 // Get or create the prototype for the function. 5310 if (!GV || (GV->getValueType() != Ty)) 5311 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 5312 /*DontDefer=*/true, 5313 ForDefinition)); 5314 5315 // Already emitted. 5316 if (!GV->isDeclaration()) 5317 return; 5318 5319 // We need to set linkage and visibility on the function before 5320 // generating code for it because various parts of IR generation 5321 // want to propagate this information down (e.g. to local static 5322 // declarations). 5323 auto *Fn = cast<llvm::Function>(GV); 5324 setFunctionLinkage(GD, Fn); 5325 5326 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 5327 setGVProperties(Fn, GD); 5328 5329 MaybeHandleStaticInExternC(D, Fn); 5330 5331 maybeSetTrivialComdat(*D, *Fn); 5332 5333 // Set CodeGen attributes that represent floating point environment. 5334 setLLVMFunctionFEnvAttributes(D, Fn); 5335 5336 CodeGenFunction(*this).GenerateCode(GD, Fn, FI); 5337 5338 setNonAliasAttributes(GD, Fn); 5339 SetLLVMFunctionAttributesForDefinition(D, Fn); 5340 5341 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 5342 AddGlobalCtor(Fn, CA->getPriority()); 5343 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 5344 AddGlobalDtor(Fn, DA->getPriority(), true); 5345 if (D->hasAttr<AnnotateAttr>()) 5346 AddGlobalAnnotations(D, Fn); 5347 } 5348 5349 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 5350 const auto *D = cast<ValueDecl>(GD.getDecl()); 5351 const AliasAttr *AA = D->getAttr<AliasAttr>(); 5352 assert(AA && "Not an alias?"); 5353 5354 StringRef MangledName = getMangledName(GD); 5355 5356 if (AA->getAliasee() == MangledName) { 5357 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5358 return; 5359 } 5360 5361 // If there is a definition in the module, then it wins over the alias. 5362 // This is dubious, but allow it to be safe. Just ignore the alias. 5363 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5364 if (Entry && !Entry->isDeclaration()) 5365 return; 5366 5367 Aliases.push_back(GD); 5368 5369 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5370 5371 // Create a reference to the named value. This ensures that it is emitted 5372 // if a deferred decl. 5373 llvm::Constant *Aliasee; 5374 llvm::GlobalValue::LinkageTypes LT; 5375 if (isa<llvm::FunctionType>(DeclTy)) { 5376 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 5377 /*ForVTable=*/false); 5378 LT = getFunctionLinkage(GD); 5379 } else { 5380 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 5381 /*D=*/nullptr); 5382 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl())) 5383 LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified()); 5384 else 5385 LT = getFunctionLinkage(GD); 5386 } 5387 5388 // Create the new alias itself, but don't set a name yet. 5389 unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 5390 auto *GA = 5391 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 5392 5393 if (Entry) { 5394 if (GA->getAliasee() == Entry) { 5395 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5396 return; 5397 } 5398 5399 assert(Entry->isDeclaration()); 5400 5401 // If there is a declaration in the module, then we had an extern followed 5402 // by the alias, as in: 5403 // extern int test6(); 5404 // ... 5405 // int test6() __attribute__((alias("test7"))); 5406 // 5407 // Remove it and replace uses of it with the alias. 5408 GA->takeName(Entry); 5409 5410 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 5411 Entry->getType())); 5412 Entry->eraseFromParent(); 5413 } else { 5414 GA->setName(MangledName); 5415 } 5416 5417 // Set attributes which are particular to an alias; this is a 5418 // specialization of the attributes which may be set on a global 5419 // variable/function. 5420 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 5421 D->isWeakImported()) { 5422 GA->setLinkage(llvm::Function::WeakAnyLinkage); 5423 } 5424 5425 if (const auto *VD = dyn_cast<VarDecl>(D)) 5426 if (VD->getTLSKind()) 5427 setTLSMode(GA, *VD); 5428 5429 SetCommonAttributes(GD, GA); 5430 5431 // Emit global alias debug information. 5432 if (isa<VarDecl>(D)) 5433 if (CGDebugInfo *DI = getModuleDebugInfo()) 5434 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD); 5435 } 5436 5437 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 5438 const auto *D = cast<ValueDecl>(GD.getDecl()); 5439 const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 5440 assert(IFA && "Not an ifunc?"); 5441 5442 StringRef MangledName = getMangledName(GD); 5443 5444 if (IFA->getResolver() == MangledName) { 5445 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5446 return; 5447 } 5448 5449 // Report an error if some definition overrides ifunc. 5450 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5451 if (Entry && !Entry->isDeclaration()) { 5452 GlobalDecl OtherGD; 5453 if (lookupRepresentativeDecl(MangledName, OtherGD) && 5454 DiagnosedConflictingDefinitions.insert(GD).second) { 5455 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 5456 << MangledName; 5457 Diags.Report(OtherGD.getDecl()->getLocation(), 5458 diag::note_previous_definition); 5459 } 5460 return; 5461 } 5462 5463 Aliases.push_back(GD); 5464 5465 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5466 llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy); 5467 llvm::Constant *Resolver = 5468 GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {}, 5469 /*ForVTable=*/false); 5470 llvm::GlobalIFunc *GIF = 5471 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 5472 "", Resolver, &getModule()); 5473 if (Entry) { 5474 if (GIF->getResolver() == Entry) { 5475 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5476 return; 5477 } 5478 assert(Entry->isDeclaration()); 5479 5480 // If there is a declaration in the module, then we had an extern followed 5481 // by the ifunc, as in: 5482 // extern int test(); 5483 // ... 5484 // int test() __attribute__((ifunc("resolver"))); 5485 // 5486 // Remove it and replace uses of it with the ifunc. 5487 GIF->takeName(Entry); 5488 5489 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 5490 Entry->getType())); 5491 Entry->eraseFromParent(); 5492 } else 5493 GIF->setName(MangledName); 5494 5495 SetCommonAttributes(GD, GIF); 5496 } 5497 5498 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 5499 ArrayRef<llvm::Type*> Tys) { 5500 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 5501 Tys); 5502 } 5503 5504 static llvm::StringMapEntry<llvm::GlobalVariable *> & 5505 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 5506 const StringLiteral *Literal, bool TargetIsLSB, 5507 bool &IsUTF16, unsigned &StringLength) { 5508 StringRef String = Literal->getString(); 5509 unsigned NumBytes = String.size(); 5510 5511 // Check for simple case. 5512 if (!Literal->containsNonAsciiOrNull()) { 5513 StringLength = NumBytes; 5514 return *Map.insert(std::make_pair(String, nullptr)).first; 5515 } 5516 5517 // Otherwise, convert the UTF8 literals into a string of shorts. 5518 IsUTF16 = true; 5519 5520 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 5521 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5522 llvm::UTF16 *ToPtr = &ToBuf[0]; 5523 5524 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5525 ToPtr + NumBytes, llvm::strictConversion); 5526 5527 // ConvertUTF8toUTF16 returns the length in ToPtr. 5528 StringLength = ToPtr - &ToBuf[0]; 5529 5530 // Add an explicit null. 5531 *ToPtr = 0; 5532 return *Map.insert(std::make_pair( 5533 StringRef(reinterpret_cast<const char *>(ToBuf.data()), 5534 (StringLength + 1) * 2), 5535 nullptr)).first; 5536 } 5537 5538 ConstantAddress 5539 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 5540 unsigned StringLength = 0; 5541 bool isUTF16 = false; 5542 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 5543 GetConstantCFStringEntry(CFConstantStringMap, Literal, 5544 getDataLayout().isLittleEndian(), isUTF16, 5545 StringLength); 5546 5547 if (auto *C = Entry.second) 5548 return ConstantAddress( 5549 C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment())); 5550 5551 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 5552 llvm::Constant *Zeros[] = { Zero, Zero }; 5553 5554 const ASTContext &Context = getContext(); 5555 const llvm::Triple &Triple = getTriple(); 5556 5557 const auto CFRuntime = getLangOpts().CFRuntime; 5558 const bool IsSwiftABI = 5559 static_cast<unsigned>(CFRuntime) >= 5560 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 5561 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 5562 5563 // If we don't already have it, get __CFConstantStringClassReference. 5564 if (!CFConstantStringClassRef) { 5565 const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 5566 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 5567 Ty = llvm::ArrayType::get(Ty, 0); 5568 5569 switch (CFRuntime) { 5570 default: break; 5571 case LangOptions::CoreFoundationABI::Swift: [[fallthrough]]; 5572 case LangOptions::CoreFoundationABI::Swift5_0: 5573 CFConstantStringClassName = 5574 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 5575 : "$s10Foundation19_NSCFConstantStringCN"; 5576 Ty = IntPtrTy; 5577 break; 5578 case LangOptions::CoreFoundationABI::Swift4_2: 5579 CFConstantStringClassName = 5580 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 5581 : "$S10Foundation19_NSCFConstantStringCN"; 5582 Ty = IntPtrTy; 5583 break; 5584 case LangOptions::CoreFoundationABI::Swift4_1: 5585 CFConstantStringClassName = 5586 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 5587 : "__T010Foundation19_NSCFConstantStringCN"; 5588 Ty = IntPtrTy; 5589 break; 5590 } 5591 5592 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 5593 5594 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 5595 llvm::GlobalValue *GV = nullptr; 5596 5597 if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 5598 IdentifierInfo &II = Context.Idents.get(GV->getName()); 5599 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 5600 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 5601 5602 const VarDecl *VD = nullptr; 5603 for (const auto *Result : DC->lookup(&II)) 5604 if ((VD = dyn_cast<VarDecl>(Result))) 5605 break; 5606 5607 if (Triple.isOSBinFormatELF()) { 5608 if (!VD) 5609 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5610 } else { 5611 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5612 if (!VD || !VD->hasAttr<DLLExportAttr>()) 5613 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 5614 else 5615 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 5616 } 5617 5618 setDSOLocal(GV); 5619 } 5620 } 5621 5622 // Decay array -> ptr 5623 CFConstantStringClassRef = 5624 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 5625 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 5626 } 5627 5628 QualType CFTy = Context.getCFConstantStringType(); 5629 5630 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 5631 5632 ConstantInitBuilder Builder(*this); 5633 auto Fields = Builder.beginStruct(STy); 5634 5635 // Class pointer. 5636 Fields.add(cast<llvm::Constant>(CFConstantStringClassRef)); 5637 5638 // Flags. 5639 if (IsSwiftABI) { 5640 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 5641 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 5642 } else { 5643 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 5644 } 5645 5646 // String pointer. 5647 llvm::Constant *C = nullptr; 5648 if (isUTF16) { 5649 auto Arr = llvm::makeArrayRef( 5650 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 5651 Entry.first().size() / 2); 5652 C = llvm::ConstantDataArray::get(VMContext, Arr); 5653 } else { 5654 C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 5655 } 5656 5657 // Note: -fwritable-strings doesn't make the backing store strings of 5658 // CFStrings writable. (See <rdar://problem/10657500>) 5659 auto *GV = 5660 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 5661 llvm::GlobalValue::PrivateLinkage, C, ".str"); 5662 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5663 // Don't enforce the target's minimum global alignment, since the only use 5664 // of the string is via this class initializer. 5665 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 5666 : Context.getTypeAlignInChars(Context.CharTy); 5667 GV->setAlignment(Align.getAsAlign()); 5668 5669 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 5670 // Without it LLVM can merge the string with a non unnamed_addr one during 5671 // LTO. Doing that changes the section it ends in, which surprises ld64. 5672 if (Triple.isOSBinFormatMachO()) 5673 GV->setSection(isUTF16 ? "__TEXT,__ustring" 5674 : "__TEXT,__cstring,cstring_literals"); 5675 // Make sure the literal ends up in .rodata to allow for safe ICF and for 5676 // the static linker to adjust permissions to read-only later on. 5677 else if (Triple.isOSBinFormatELF()) 5678 GV->setSection(".rodata"); 5679 5680 // String. 5681 llvm::Constant *Str = 5682 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 5683 5684 if (isUTF16) 5685 // Cast the UTF16 string to the correct type. 5686 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 5687 Fields.add(Str); 5688 5689 // String length. 5690 llvm::IntegerType *LengthTy = 5691 llvm::IntegerType::get(getModule().getContext(), 5692 Context.getTargetInfo().getLongWidth()); 5693 if (IsSwiftABI) { 5694 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 5695 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 5696 LengthTy = Int32Ty; 5697 else 5698 LengthTy = IntPtrTy; 5699 } 5700 Fields.addInt(LengthTy, StringLength); 5701 5702 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 5703 // properly aligned on 32-bit platforms. 5704 CharUnits Alignment = 5705 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 5706 5707 // The struct. 5708 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 5709 /*isConstant=*/false, 5710 llvm::GlobalVariable::PrivateLinkage); 5711 GV->addAttribute("objc_arc_inert"); 5712 switch (Triple.getObjectFormat()) { 5713 case llvm::Triple::UnknownObjectFormat: 5714 llvm_unreachable("unknown file format"); 5715 case llvm::Triple::DXContainer: 5716 case llvm::Triple::GOFF: 5717 case llvm::Triple::SPIRV: 5718 case llvm::Triple::XCOFF: 5719 llvm_unreachable("unimplemented"); 5720 case llvm::Triple::COFF: 5721 case llvm::Triple::ELF: 5722 case llvm::Triple::Wasm: 5723 GV->setSection("cfstring"); 5724 break; 5725 case llvm::Triple::MachO: 5726 GV->setSection("__DATA,__cfstring"); 5727 break; 5728 } 5729 Entry.second = GV; 5730 5731 return ConstantAddress(GV, GV->getValueType(), Alignment); 5732 } 5733 5734 bool CodeGenModule::getExpressionLocationsEnabled() const { 5735 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 5736 } 5737 5738 QualType CodeGenModule::getObjCFastEnumerationStateType() { 5739 if (ObjCFastEnumerationStateType.isNull()) { 5740 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 5741 D->startDefinition(); 5742 5743 QualType FieldTypes[] = { 5744 Context.UnsignedLongTy, 5745 Context.getPointerType(Context.getObjCIdType()), 5746 Context.getPointerType(Context.UnsignedLongTy), 5747 Context.getConstantArrayType(Context.UnsignedLongTy, 5748 llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0) 5749 }; 5750 5751 for (size_t i = 0; i < 4; ++i) { 5752 FieldDecl *Field = FieldDecl::Create(Context, 5753 D, 5754 SourceLocation(), 5755 SourceLocation(), nullptr, 5756 FieldTypes[i], /*TInfo=*/nullptr, 5757 /*BitWidth=*/nullptr, 5758 /*Mutable=*/false, 5759 ICIS_NoInit); 5760 Field->setAccess(AS_public); 5761 D->addDecl(Field); 5762 } 5763 5764 D->completeDefinition(); 5765 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 5766 } 5767 5768 return ObjCFastEnumerationStateType; 5769 } 5770 5771 llvm::Constant * 5772 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 5773 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 5774 5775 // Don't emit it as the address of the string, emit the string data itself 5776 // as an inline array. 5777 if (E->getCharByteWidth() == 1) { 5778 SmallString<64> Str(E->getString()); 5779 5780 // Resize the string to the right size, which is indicated by its type. 5781 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 5782 Str.resize(CAT->getSize().getZExtValue()); 5783 return llvm::ConstantDataArray::getString(VMContext, Str, false); 5784 } 5785 5786 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 5787 llvm::Type *ElemTy = AType->getElementType(); 5788 unsigned NumElements = AType->getNumElements(); 5789 5790 // Wide strings have either 2-byte or 4-byte elements. 5791 if (ElemTy->getPrimitiveSizeInBits() == 16) { 5792 SmallVector<uint16_t, 32> Elements; 5793 Elements.reserve(NumElements); 5794 5795 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5796 Elements.push_back(E->getCodeUnit(i)); 5797 Elements.resize(NumElements); 5798 return llvm::ConstantDataArray::get(VMContext, Elements); 5799 } 5800 5801 assert(ElemTy->getPrimitiveSizeInBits() == 32); 5802 SmallVector<uint32_t, 32> Elements; 5803 Elements.reserve(NumElements); 5804 5805 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5806 Elements.push_back(E->getCodeUnit(i)); 5807 Elements.resize(NumElements); 5808 return llvm::ConstantDataArray::get(VMContext, Elements); 5809 } 5810 5811 static llvm::GlobalVariable * 5812 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 5813 CodeGenModule &CGM, StringRef GlobalName, 5814 CharUnits Alignment) { 5815 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 5816 CGM.GetGlobalConstantAddressSpace()); 5817 5818 llvm::Module &M = CGM.getModule(); 5819 // Create a global variable for this string 5820 auto *GV = new llvm::GlobalVariable( 5821 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 5822 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 5823 GV->setAlignment(Alignment.getAsAlign()); 5824 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5825 if (GV->isWeakForLinker()) { 5826 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 5827 GV->setComdat(M.getOrInsertComdat(GV->getName())); 5828 } 5829 CGM.setDSOLocal(GV); 5830 5831 return GV; 5832 } 5833 5834 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 5835 /// constant array for the given string literal. 5836 ConstantAddress 5837 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 5838 StringRef Name) { 5839 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 5840 5841 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 5842 llvm::GlobalVariable **Entry = nullptr; 5843 if (!LangOpts.WritableStrings) { 5844 Entry = &ConstantStringMap[C]; 5845 if (auto GV = *Entry) { 5846 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5847 GV->setAlignment(Alignment.getAsAlign()); 5848 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5849 GV->getValueType(), Alignment); 5850 } 5851 } 5852 5853 SmallString<256> MangledNameBuffer; 5854 StringRef GlobalVariableName; 5855 llvm::GlobalValue::LinkageTypes LT; 5856 5857 // Mangle the string literal if that's how the ABI merges duplicate strings. 5858 // Don't do it if they are writable, since we don't want writes in one TU to 5859 // affect strings in another. 5860 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 5861 !LangOpts.WritableStrings) { 5862 llvm::raw_svector_ostream Out(MangledNameBuffer); 5863 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 5864 LT = llvm::GlobalValue::LinkOnceODRLinkage; 5865 GlobalVariableName = MangledNameBuffer; 5866 } else { 5867 LT = llvm::GlobalValue::PrivateLinkage; 5868 GlobalVariableName = Name; 5869 } 5870 5871 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 5872 5873 CGDebugInfo *DI = getModuleDebugInfo(); 5874 if (DI && getCodeGenOpts().hasReducedDebugInfo()) 5875 DI->AddStringLiteralDebugInfo(GV, S); 5876 5877 if (Entry) 5878 *Entry = GV; 5879 5880 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>"); 5881 5882 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5883 GV->getValueType(), Alignment); 5884 } 5885 5886 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 5887 /// array for the given ObjCEncodeExpr node. 5888 ConstantAddress 5889 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 5890 std::string Str; 5891 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 5892 5893 return GetAddrOfConstantCString(Str); 5894 } 5895 5896 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 5897 /// the literal and a terminating '\0' character. 5898 /// The result has pointer to array type. 5899 ConstantAddress CodeGenModule::GetAddrOfConstantCString( 5900 const std::string &Str, const char *GlobalName) { 5901 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 5902 CharUnits Alignment = 5903 getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 5904 5905 llvm::Constant *C = 5906 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 5907 5908 // Don't share any string literals if strings aren't constant. 5909 llvm::GlobalVariable **Entry = nullptr; 5910 if (!LangOpts.WritableStrings) { 5911 Entry = &ConstantStringMap[C]; 5912 if (auto GV = *Entry) { 5913 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5914 GV->setAlignment(Alignment.getAsAlign()); 5915 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5916 GV->getValueType(), Alignment); 5917 } 5918 } 5919 5920 // Get the default prefix if a name wasn't specified. 5921 if (!GlobalName) 5922 GlobalName = ".str"; 5923 // Create a global variable for this. 5924 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 5925 GlobalName, Alignment); 5926 if (Entry) 5927 *Entry = GV; 5928 5929 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5930 GV->getValueType(), Alignment); 5931 } 5932 5933 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 5934 const MaterializeTemporaryExpr *E, const Expr *Init) { 5935 assert((E->getStorageDuration() == SD_Static || 5936 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 5937 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 5938 5939 // If we're not materializing a subobject of the temporary, keep the 5940 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 5941 QualType MaterializedType = Init->getType(); 5942 if (Init == E->getSubExpr()) 5943 MaterializedType = E->getType(); 5944 5945 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 5946 5947 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr}); 5948 if (!InsertResult.second) { 5949 // We've seen this before: either we already created it or we're in the 5950 // process of doing so. 5951 if (!InsertResult.first->second) { 5952 // We recursively re-entered this function, probably during emission of 5953 // the initializer. Create a placeholder. We'll clean this up in the 5954 // outer call, at the end of this function. 5955 llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType); 5956 InsertResult.first->second = new llvm::GlobalVariable( 5957 getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, 5958 nullptr); 5959 } 5960 return ConstantAddress(InsertResult.first->second, 5961 llvm::cast<llvm::GlobalVariable>( 5962 InsertResult.first->second->stripPointerCasts()) 5963 ->getValueType(), 5964 Align); 5965 } 5966 5967 // FIXME: If an externally-visible declaration extends multiple temporaries, 5968 // we need to give each temporary the same name in every translation unit (and 5969 // we also need to make the temporaries externally-visible). 5970 SmallString<256> Name; 5971 llvm::raw_svector_ostream Out(Name); 5972 getCXXABI().getMangleContext().mangleReferenceTemporary( 5973 VD, E->getManglingNumber(), Out); 5974 5975 APValue *Value = nullptr; 5976 if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) { 5977 // If the initializer of the extending declaration is a constant 5978 // initializer, we should have a cached constant initializer for this 5979 // temporary. Note that this might have a different value from the value 5980 // computed by evaluating the initializer if the surrounding constant 5981 // expression modifies the temporary. 5982 Value = E->getOrCreateValue(false); 5983 } 5984 5985 // Try evaluating it now, it might have a constant initializer. 5986 Expr::EvalResult EvalResult; 5987 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 5988 !EvalResult.hasSideEffects()) 5989 Value = &EvalResult.Val; 5990 5991 LangAS AddrSpace = 5992 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 5993 5994 Optional<ConstantEmitter> emitter; 5995 llvm::Constant *InitialValue = nullptr; 5996 bool Constant = false; 5997 llvm::Type *Type; 5998 if (Value) { 5999 // The temporary has a constant initializer, use it. 6000 emitter.emplace(*this); 6001 InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 6002 MaterializedType); 6003 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 6004 Type = InitialValue->getType(); 6005 } else { 6006 // No initializer, the initialization will be provided when we 6007 // initialize the declaration which performed lifetime extension. 6008 Type = getTypes().ConvertTypeForMem(MaterializedType); 6009 } 6010 6011 // Create a global variable for this lifetime-extended temporary. 6012 llvm::GlobalValue::LinkageTypes Linkage = 6013 getLLVMLinkageVarDefinition(VD, Constant); 6014 if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 6015 const VarDecl *InitVD; 6016 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 6017 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 6018 // Temporaries defined inside a class get linkonce_odr linkage because the 6019 // class can be defined in multiple translation units. 6020 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 6021 } else { 6022 // There is no need for this temporary to have external linkage if the 6023 // VarDecl has external linkage. 6024 Linkage = llvm::GlobalVariable::InternalLinkage; 6025 } 6026 } 6027 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 6028 auto *GV = new llvm::GlobalVariable( 6029 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 6030 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 6031 if (emitter) emitter->finalize(GV); 6032 // Don't assign dllimport or dllexport to local linkage globals. 6033 if (!llvm::GlobalValue::isLocalLinkage(Linkage)) { 6034 setGVProperties(GV, VD); 6035 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass) 6036 // The reference temporary should never be dllexport. 6037 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 6038 } 6039 GV->setAlignment(Align.getAsAlign()); 6040 if (supportsCOMDAT() && GV->isWeakForLinker()) 6041 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 6042 if (VD->getTLSKind()) 6043 setTLSMode(GV, *VD); 6044 llvm::Constant *CV = GV; 6045 if (AddrSpace != LangAS::Default) 6046 CV = getTargetCodeGenInfo().performAddrSpaceCast( 6047 *this, GV, AddrSpace, LangAS::Default, 6048 Type->getPointerTo( 6049 getContext().getTargetAddressSpace(LangAS::Default))); 6050 6051 // Update the map with the new temporary. If we created a placeholder above, 6052 // replace it with the new global now. 6053 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; 6054 if (Entry) { 6055 Entry->replaceAllUsesWith( 6056 llvm::ConstantExpr::getBitCast(CV, Entry->getType())); 6057 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent(); 6058 } 6059 Entry = CV; 6060 6061 return ConstantAddress(CV, Type, Align); 6062 } 6063 6064 /// EmitObjCPropertyImplementations - Emit information for synthesized 6065 /// properties for an implementation. 6066 void CodeGenModule::EmitObjCPropertyImplementations(const 6067 ObjCImplementationDecl *D) { 6068 for (const auto *PID : D->property_impls()) { 6069 // Dynamic is just for type-checking. 6070 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 6071 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 6072 6073 // Determine which methods need to be implemented, some may have 6074 // been overridden. Note that ::isPropertyAccessor is not the method 6075 // we want, that just indicates if the decl came from a 6076 // property. What we want to know is if the method is defined in 6077 // this implementation. 6078 auto *Getter = PID->getGetterMethodDecl(); 6079 if (!Getter || Getter->isSynthesizedAccessorStub()) 6080 CodeGenFunction(*this).GenerateObjCGetter( 6081 const_cast<ObjCImplementationDecl *>(D), PID); 6082 auto *Setter = PID->getSetterMethodDecl(); 6083 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 6084 CodeGenFunction(*this).GenerateObjCSetter( 6085 const_cast<ObjCImplementationDecl *>(D), PID); 6086 } 6087 } 6088 } 6089 6090 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 6091 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 6092 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 6093 ivar; ivar = ivar->getNextIvar()) 6094 if (ivar->getType().isDestructedType()) 6095 return true; 6096 6097 return false; 6098 } 6099 6100 static bool AllTrivialInitializers(CodeGenModule &CGM, 6101 ObjCImplementationDecl *D) { 6102 CodeGenFunction CGF(CGM); 6103 for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 6104 E = D->init_end(); B != E; ++B) { 6105 CXXCtorInitializer *CtorInitExp = *B; 6106 Expr *Init = CtorInitExp->getInit(); 6107 if (!CGF.isTrivialInitializer(Init)) 6108 return false; 6109 } 6110 return true; 6111 } 6112 6113 /// EmitObjCIvarInitializations - Emit information for ivar initialization 6114 /// for an implementation. 6115 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 6116 // We might need a .cxx_destruct even if we don't have any ivar initializers. 6117 if (needsDestructMethod(D)) { 6118 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 6119 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 6120 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( 6121 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 6122 getContext().VoidTy, nullptr, D, 6123 /*isInstance=*/true, /*isVariadic=*/false, 6124 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 6125 /*isImplicitlyDeclared=*/true, 6126 /*isDefined=*/false, ObjCMethodDecl::Required); 6127 D->addInstanceMethod(DTORMethod); 6128 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 6129 D->setHasDestructors(true); 6130 } 6131 6132 // If the implementation doesn't have any ivar initializers, we don't need 6133 // a .cxx_construct. 6134 if (D->getNumIvarInitializers() == 0 || 6135 AllTrivialInitializers(*this, D)) 6136 return; 6137 6138 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 6139 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 6140 // The constructor returns 'self'. 6141 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( 6142 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 6143 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, 6144 /*isVariadic=*/false, 6145 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 6146 /*isImplicitlyDeclared=*/true, 6147 /*isDefined=*/false, ObjCMethodDecl::Required); 6148 D->addInstanceMethod(CTORMethod); 6149 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 6150 D->setHasNonZeroConstructors(true); 6151 } 6152 6153 // EmitLinkageSpec - Emit all declarations in a linkage spec. 6154 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 6155 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 6156 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 6157 ErrorUnsupported(LSD, "linkage spec"); 6158 return; 6159 } 6160 6161 EmitDeclContext(LSD); 6162 } 6163 6164 void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) { 6165 std::unique_ptr<CodeGenFunction> &CurCGF = 6166 GlobalTopLevelStmtBlockInFlight.first; 6167 6168 // We emitted a top-level stmt but after it there is initialization. 6169 // Stop squashing the top-level stmts into a single function. 6170 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) { 6171 CurCGF->FinishFunction(D->getEndLoc()); 6172 CurCGF = nullptr; 6173 } 6174 6175 if (!CurCGF) { 6176 // void __stmts__N(void) 6177 // FIXME: Ask the ABI name mangler to pick a name. 6178 std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size()); 6179 FunctionArgList Args; 6180 QualType RetTy = getContext().VoidTy; 6181 const CGFunctionInfo &FnInfo = 6182 getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args); 6183 llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo); 6184 llvm::Function *Fn = llvm::Function::Create( 6185 FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule()); 6186 6187 CurCGF.reset(new CodeGenFunction(*this)); 6188 GlobalTopLevelStmtBlockInFlight.second = D; 6189 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args, 6190 D->getBeginLoc(), D->getBeginLoc()); 6191 CXXGlobalInits.push_back(Fn); 6192 } 6193 6194 CurCGF->EmitStmt(D->getStmt()); 6195 } 6196 6197 void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 6198 for (auto *I : DC->decls()) { 6199 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 6200 // are themselves considered "top-level", so EmitTopLevelDecl on an 6201 // ObjCImplDecl does not recursively visit them. We need to do that in 6202 // case they're nested inside another construct (LinkageSpecDecl / 6203 // ExportDecl) that does stop them from being considered "top-level". 6204 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 6205 for (auto *M : OID->methods()) 6206 EmitTopLevelDecl(M); 6207 } 6208 6209 EmitTopLevelDecl(I); 6210 } 6211 } 6212 6213 /// EmitTopLevelDecl - Emit code for a single top level declaration. 6214 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 6215 // Ignore dependent declarations. 6216 if (D->isTemplated()) 6217 return; 6218 6219 // Consteval function shouldn't be emitted. 6220 if (auto *FD = dyn_cast<FunctionDecl>(D)) 6221 if (FD->isConsteval()) 6222 return; 6223 6224 switch (D->getKind()) { 6225 case Decl::CXXConversion: 6226 case Decl::CXXMethod: 6227 case Decl::Function: 6228 EmitGlobal(cast<FunctionDecl>(D)); 6229 // Always provide some coverage mapping 6230 // even for the functions that aren't emitted. 6231 AddDeferredUnusedCoverageMapping(D); 6232 break; 6233 6234 case Decl::CXXDeductionGuide: 6235 // Function-like, but does not result in code emission. 6236 break; 6237 6238 case Decl::Var: 6239 case Decl::Decomposition: 6240 case Decl::VarTemplateSpecialization: 6241 EmitGlobal(cast<VarDecl>(D)); 6242 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 6243 for (auto *B : DD->bindings()) 6244 if (auto *HD = B->getHoldingVar()) 6245 EmitGlobal(HD); 6246 break; 6247 6248 // Indirect fields from global anonymous structs and unions can be 6249 // ignored; only the actual variable requires IR gen support. 6250 case Decl::IndirectField: 6251 break; 6252 6253 // C++ Decls 6254 case Decl::Namespace: 6255 EmitDeclContext(cast<NamespaceDecl>(D)); 6256 break; 6257 case Decl::ClassTemplateSpecialization: { 6258 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 6259 if (CGDebugInfo *DI = getModuleDebugInfo()) 6260 if (Spec->getSpecializationKind() == 6261 TSK_ExplicitInstantiationDefinition && 6262 Spec->hasDefinition()) 6263 DI->completeTemplateDefinition(*Spec); 6264 } [[fallthrough]]; 6265 case Decl::CXXRecord: { 6266 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); 6267 if (CGDebugInfo *DI = getModuleDebugInfo()) { 6268 if (CRD->hasDefinition()) 6269 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6270 if (auto *ES = D->getASTContext().getExternalSource()) 6271 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 6272 DI->completeUnusedClass(*CRD); 6273 } 6274 // Emit any static data members, they may be definitions. 6275 for (auto *I : CRD->decls()) 6276 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 6277 EmitTopLevelDecl(I); 6278 break; 6279 } 6280 // No code generation needed. 6281 case Decl::UsingShadow: 6282 case Decl::ClassTemplate: 6283 case Decl::VarTemplate: 6284 case Decl::Concept: 6285 case Decl::VarTemplatePartialSpecialization: 6286 case Decl::FunctionTemplate: 6287 case Decl::TypeAliasTemplate: 6288 case Decl::Block: 6289 case Decl::Empty: 6290 case Decl::Binding: 6291 break; 6292 case Decl::Using: // using X; [C++] 6293 if (CGDebugInfo *DI = getModuleDebugInfo()) 6294 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 6295 break; 6296 case Decl::UsingEnum: // using enum X; [C++] 6297 if (CGDebugInfo *DI = getModuleDebugInfo()) 6298 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D)); 6299 break; 6300 case Decl::NamespaceAlias: 6301 if (CGDebugInfo *DI = getModuleDebugInfo()) 6302 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 6303 break; 6304 case Decl::UsingDirective: // using namespace X; [C++] 6305 if (CGDebugInfo *DI = getModuleDebugInfo()) 6306 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 6307 break; 6308 case Decl::CXXConstructor: 6309 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 6310 break; 6311 case Decl::CXXDestructor: 6312 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 6313 break; 6314 6315 case Decl::StaticAssert: 6316 // Nothing to do. 6317 break; 6318 6319 // Objective-C Decls 6320 6321 // Forward declarations, no (immediate) code generation. 6322 case Decl::ObjCInterface: 6323 case Decl::ObjCCategory: 6324 break; 6325 6326 case Decl::ObjCProtocol: { 6327 auto *Proto = cast<ObjCProtocolDecl>(D); 6328 if (Proto->isThisDeclarationADefinition()) 6329 ObjCRuntime->GenerateProtocol(Proto); 6330 break; 6331 } 6332 6333 case Decl::ObjCCategoryImpl: 6334 // Categories have properties but don't support synthesize so we 6335 // can ignore them here. 6336 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 6337 break; 6338 6339 case Decl::ObjCImplementation: { 6340 auto *OMD = cast<ObjCImplementationDecl>(D); 6341 EmitObjCPropertyImplementations(OMD); 6342 EmitObjCIvarInitializations(OMD); 6343 ObjCRuntime->GenerateClass(OMD); 6344 // Emit global variable debug information. 6345 if (CGDebugInfo *DI = getModuleDebugInfo()) 6346 if (getCodeGenOpts().hasReducedDebugInfo()) 6347 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 6348 OMD->getClassInterface()), OMD->getLocation()); 6349 break; 6350 } 6351 case Decl::ObjCMethod: { 6352 auto *OMD = cast<ObjCMethodDecl>(D); 6353 // If this is not a prototype, emit the body. 6354 if (OMD->getBody()) 6355 CodeGenFunction(*this).GenerateObjCMethod(OMD); 6356 break; 6357 } 6358 case Decl::ObjCCompatibleAlias: 6359 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 6360 break; 6361 6362 case Decl::PragmaComment: { 6363 const auto *PCD = cast<PragmaCommentDecl>(D); 6364 switch (PCD->getCommentKind()) { 6365 case PCK_Unknown: 6366 llvm_unreachable("unexpected pragma comment kind"); 6367 case PCK_Linker: 6368 AppendLinkerOptions(PCD->getArg()); 6369 break; 6370 case PCK_Lib: 6371 AddDependentLib(PCD->getArg()); 6372 break; 6373 case PCK_Compiler: 6374 case PCK_ExeStr: 6375 case PCK_User: 6376 break; // We ignore all of these. 6377 } 6378 break; 6379 } 6380 6381 case Decl::PragmaDetectMismatch: { 6382 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 6383 AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 6384 break; 6385 } 6386 6387 case Decl::LinkageSpec: 6388 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 6389 break; 6390 6391 case Decl::FileScopeAsm: { 6392 // File-scope asm is ignored during device-side CUDA compilation. 6393 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 6394 break; 6395 // File-scope asm is ignored during device-side OpenMP compilation. 6396 if (LangOpts.OpenMPIsDevice) 6397 break; 6398 // File-scope asm is ignored during device-side SYCL compilation. 6399 if (LangOpts.SYCLIsDevice) 6400 break; 6401 auto *AD = cast<FileScopeAsmDecl>(D); 6402 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 6403 break; 6404 } 6405 6406 case Decl::TopLevelStmt: 6407 EmitTopLevelStmt(cast<TopLevelStmtDecl>(D)); 6408 break; 6409 6410 case Decl::Import: { 6411 auto *Import = cast<ImportDecl>(D); 6412 6413 // If we've already imported this module, we're done. 6414 if (!ImportedModules.insert(Import->getImportedModule())) 6415 break; 6416 6417 // Emit debug information for direct imports. 6418 if (!Import->getImportedOwningModule()) { 6419 if (CGDebugInfo *DI = getModuleDebugInfo()) 6420 DI->EmitImportDecl(*Import); 6421 } 6422 6423 // For C++ standard modules we are done - we will call the module 6424 // initializer for imported modules, and that will likewise call those for 6425 // any imports it has. 6426 if (CXX20ModuleInits && Import->getImportedOwningModule() && 6427 !Import->getImportedOwningModule()->isModuleMapModule()) 6428 break; 6429 6430 // For clang C++ module map modules the initializers for sub-modules are 6431 // emitted here. 6432 6433 // Find all of the submodules and emit the module initializers. 6434 llvm::SmallPtrSet<clang::Module *, 16> Visited; 6435 SmallVector<clang::Module *, 16> Stack; 6436 Visited.insert(Import->getImportedModule()); 6437 Stack.push_back(Import->getImportedModule()); 6438 6439 while (!Stack.empty()) { 6440 clang::Module *Mod = Stack.pop_back_val(); 6441 if (!EmittedModuleInitializers.insert(Mod).second) 6442 continue; 6443 6444 for (auto *D : Context.getModuleInitializers(Mod)) 6445 EmitTopLevelDecl(D); 6446 6447 // Visit the submodules of this module. 6448 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 6449 SubEnd = Mod->submodule_end(); 6450 Sub != SubEnd; ++Sub) { 6451 // Skip explicit children; they need to be explicitly imported to emit 6452 // the initializers. 6453 if ((*Sub)->IsExplicit) 6454 continue; 6455 6456 if (Visited.insert(*Sub).second) 6457 Stack.push_back(*Sub); 6458 } 6459 } 6460 break; 6461 } 6462 6463 case Decl::Export: 6464 EmitDeclContext(cast<ExportDecl>(D)); 6465 break; 6466 6467 case Decl::OMPThreadPrivate: 6468 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 6469 break; 6470 6471 case Decl::OMPAllocate: 6472 EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D)); 6473 break; 6474 6475 case Decl::OMPDeclareReduction: 6476 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 6477 break; 6478 6479 case Decl::OMPDeclareMapper: 6480 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 6481 break; 6482 6483 case Decl::OMPRequires: 6484 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 6485 break; 6486 6487 case Decl::Typedef: 6488 case Decl::TypeAlias: // using foo = bar; [C++11] 6489 if (CGDebugInfo *DI = getModuleDebugInfo()) 6490 DI->EmitAndRetainType( 6491 getContext().getTypedefType(cast<TypedefNameDecl>(D))); 6492 break; 6493 6494 case Decl::Record: 6495 if (CGDebugInfo *DI = getModuleDebugInfo()) 6496 if (cast<RecordDecl>(D)->getDefinition()) 6497 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6498 break; 6499 6500 case Decl::Enum: 6501 if (CGDebugInfo *DI = getModuleDebugInfo()) 6502 if (cast<EnumDecl>(D)->getDefinition()) 6503 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); 6504 break; 6505 6506 case Decl::HLSLBuffer: 6507 getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D)); 6508 break; 6509 6510 default: 6511 // Make sure we handled everything we should, every other kind is a 6512 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 6513 // function. Need to recode Decl::Kind to do that easily. 6514 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 6515 break; 6516 } 6517 } 6518 6519 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 6520 // Do we need to generate coverage mapping? 6521 if (!CodeGenOpts.CoverageMapping) 6522 return; 6523 switch (D->getKind()) { 6524 case Decl::CXXConversion: 6525 case Decl::CXXMethod: 6526 case Decl::Function: 6527 case Decl::ObjCMethod: 6528 case Decl::CXXConstructor: 6529 case Decl::CXXDestructor: { 6530 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 6531 break; 6532 SourceManager &SM = getContext().getSourceManager(); 6533 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 6534 break; 6535 auto I = DeferredEmptyCoverageMappingDecls.find(D); 6536 if (I == DeferredEmptyCoverageMappingDecls.end()) 6537 DeferredEmptyCoverageMappingDecls[D] = true; 6538 break; 6539 } 6540 default: 6541 break; 6542 }; 6543 } 6544 6545 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 6546 // Do we need to generate coverage mapping? 6547 if (!CodeGenOpts.CoverageMapping) 6548 return; 6549 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 6550 if (Fn->isTemplateInstantiation()) 6551 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 6552 } 6553 auto I = DeferredEmptyCoverageMappingDecls.find(D); 6554 if (I == DeferredEmptyCoverageMappingDecls.end()) 6555 DeferredEmptyCoverageMappingDecls[D] = false; 6556 else 6557 I->second = false; 6558 } 6559 6560 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 6561 // We call takeVector() here to avoid use-after-free. 6562 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 6563 // we deserialize function bodies to emit coverage info for them, and that 6564 // deserializes more declarations. How should we handle that case? 6565 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 6566 if (!Entry.second) 6567 continue; 6568 const Decl *D = Entry.first; 6569 switch (D->getKind()) { 6570 case Decl::CXXConversion: 6571 case Decl::CXXMethod: 6572 case Decl::Function: 6573 case Decl::ObjCMethod: { 6574 CodeGenPGO PGO(*this); 6575 GlobalDecl GD(cast<FunctionDecl>(D)); 6576 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6577 getFunctionLinkage(GD)); 6578 break; 6579 } 6580 case Decl::CXXConstructor: { 6581 CodeGenPGO PGO(*this); 6582 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 6583 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6584 getFunctionLinkage(GD)); 6585 break; 6586 } 6587 case Decl::CXXDestructor: { 6588 CodeGenPGO PGO(*this); 6589 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 6590 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6591 getFunctionLinkage(GD)); 6592 break; 6593 } 6594 default: 6595 break; 6596 }; 6597 } 6598 } 6599 6600 void CodeGenModule::EmitMainVoidAlias() { 6601 // In order to transition away from "__original_main" gracefully, emit an 6602 // alias for "main" in the no-argument case so that libc can detect when 6603 // new-style no-argument main is in used. 6604 if (llvm::Function *F = getModule().getFunction("main")) { 6605 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && 6606 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) { 6607 auto *GA = llvm::GlobalAlias::create("__main_void", F); 6608 GA->setVisibility(llvm::GlobalValue::HiddenVisibility); 6609 } 6610 } 6611 } 6612 6613 /// Turns the given pointer into a constant. 6614 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 6615 const void *Ptr) { 6616 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 6617 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 6618 return llvm::ConstantInt::get(i64, PtrInt); 6619 } 6620 6621 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 6622 llvm::NamedMDNode *&GlobalMetadata, 6623 GlobalDecl D, 6624 llvm::GlobalValue *Addr) { 6625 if (!GlobalMetadata) 6626 GlobalMetadata = 6627 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 6628 6629 // TODO: should we report variant information for ctors/dtors? 6630 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 6631 llvm::ConstantAsMetadata::get(GetPointerConstant( 6632 CGM.getLLVMContext(), D.getDecl()))}; 6633 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 6634 } 6635 6636 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem, 6637 llvm::GlobalValue *CppFunc) { 6638 // Store the list of ifuncs we need to replace uses in. 6639 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs; 6640 // List of ConstantExprs that we should be able to delete when we're done 6641 // here. 6642 llvm::SmallVector<llvm::ConstantExpr *> CEs; 6643 6644 // It isn't valid to replace the extern-C ifuncs if all we find is itself! 6645 if (Elem == CppFunc) 6646 return false; 6647 6648 // First make sure that all users of this are ifuncs (or ifuncs via a 6649 // bitcast), and collect the list of ifuncs and CEs so we can work on them 6650 // later. 6651 for (llvm::User *User : Elem->users()) { 6652 // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an 6653 // ifunc directly. In any other case, just give up, as we don't know what we 6654 // could break by changing those. 6655 if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) { 6656 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast) 6657 return false; 6658 6659 for (llvm::User *CEUser : ConstExpr->users()) { 6660 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) { 6661 IFuncs.push_back(IFunc); 6662 } else { 6663 return false; 6664 } 6665 } 6666 CEs.push_back(ConstExpr); 6667 } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) { 6668 IFuncs.push_back(IFunc); 6669 } else { 6670 // This user is one we don't know how to handle, so fail redirection. This 6671 // will result in an ifunc retaining a resolver name that will ultimately 6672 // fail to be resolved to a defined function. 6673 return false; 6674 } 6675 } 6676 6677 // Now we know this is a valid case where we can do this alias replacement, we 6678 // need to remove all of the references to Elem (and the bitcasts!) so we can 6679 // delete it. 6680 for (llvm::GlobalIFunc *IFunc : IFuncs) 6681 IFunc->setResolver(nullptr); 6682 for (llvm::ConstantExpr *ConstExpr : CEs) 6683 ConstExpr->destroyConstant(); 6684 6685 // We should now be out of uses for the 'old' version of this function, so we 6686 // can erase it as well. 6687 Elem->eraseFromParent(); 6688 6689 for (llvm::GlobalIFunc *IFunc : IFuncs) { 6690 // The type of the resolver is always just a function-type that returns the 6691 // type of the IFunc, so create that here. If the type of the actual 6692 // resolver doesn't match, it just gets bitcast to the right thing. 6693 auto *ResolverTy = 6694 llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false); 6695 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 6696 CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false); 6697 IFunc->setResolver(Resolver); 6698 } 6699 return true; 6700 } 6701 6702 /// For each function which is declared within an extern "C" region and marked 6703 /// as 'used', but has internal linkage, create an alias from the unmangled 6704 /// name to the mangled name if possible. People expect to be able to refer 6705 /// to such functions with an unmangled name from inline assembly within the 6706 /// same translation unit. 6707 void CodeGenModule::EmitStaticExternCAliases() { 6708 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 6709 return; 6710 for (auto &I : StaticExternCValues) { 6711 IdentifierInfo *Name = I.first; 6712 llvm::GlobalValue *Val = I.second; 6713 6714 // If Val is null, that implies there were multiple declarations that each 6715 // had a claim to the unmangled name. In this case, generation of the alias 6716 // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC. 6717 if (!Val) 6718 break; 6719 6720 llvm::GlobalValue *ExistingElem = 6721 getModule().getNamedValue(Name->getName()); 6722 6723 // If there is either not something already by this name, or we were able to 6724 // replace all uses from IFuncs, create the alias. 6725 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val)) 6726 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 6727 } 6728 } 6729 6730 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 6731 GlobalDecl &Result) const { 6732 auto Res = Manglings.find(MangledName); 6733 if (Res == Manglings.end()) 6734 return false; 6735 Result = Res->getValue(); 6736 return true; 6737 } 6738 6739 /// Emits metadata nodes associating all the global values in the 6740 /// current module with the Decls they came from. This is useful for 6741 /// projects using IR gen as a subroutine. 6742 /// 6743 /// Since there's currently no way to associate an MDNode directly 6744 /// with an llvm::GlobalValue, we create a global named metadata 6745 /// with the name 'clang.global.decl.ptrs'. 6746 void CodeGenModule::EmitDeclMetadata() { 6747 llvm::NamedMDNode *GlobalMetadata = nullptr; 6748 6749 for (auto &I : MangledDeclNames) { 6750 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 6751 // Some mangled names don't necessarily have an associated GlobalValue 6752 // in this module, e.g. if we mangled it for DebugInfo. 6753 if (Addr) 6754 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 6755 } 6756 } 6757 6758 /// Emits metadata nodes for all the local variables in the current 6759 /// function. 6760 void CodeGenFunction::EmitDeclMetadata() { 6761 if (LocalDeclMap.empty()) return; 6762 6763 llvm::LLVMContext &Context = getLLVMContext(); 6764 6765 // Find the unique metadata ID for this name. 6766 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 6767 6768 llvm::NamedMDNode *GlobalMetadata = nullptr; 6769 6770 for (auto &I : LocalDeclMap) { 6771 const Decl *D = I.first; 6772 llvm::Value *Addr = I.second.getPointer(); 6773 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 6774 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 6775 Alloca->setMetadata( 6776 DeclPtrKind, llvm::MDNode::get( 6777 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 6778 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 6779 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 6780 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 6781 } 6782 } 6783 } 6784 6785 void CodeGenModule::EmitVersionIdentMetadata() { 6786 llvm::NamedMDNode *IdentMetadata = 6787 TheModule.getOrInsertNamedMetadata("llvm.ident"); 6788 std::string Version = getClangFullVersion(); 6789 llvm::LLVMContext &Ctx = TheModule.getContext(); 6790 6791 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 6792 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 6793 } 6794 6795 void CodeGenModule::EmitCommandLineMetadata() { 6796 llvm::NamedMDNode *CommandLineMetadata = 6797 TheModule.getOrInsertNamedMetadata("llvm.commandline"); 6798 std::string CommandLine = getCodeGenOpts().RecordCommandLine; 6799 llvm::LLVMContext &Ctx = TheModule.getContext(); 6800 6801 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 6802 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 6803 } 6804 6805 void CodeGenModule::EmitCoverageFile() { 6806 if (getCodeGenOpts().CoverageDataFile.empty() && 6807 getCodeGenOpts().CoverageNotesFile.empty()) 6808 return; 6809 6810 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 6811 if (!CUNode) 6812 return; 6813 6814 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 6815 llvm::LLVMContext &Ctx = TheModule.getContext(); 6816 auto *CoverageDataFile = 6817 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 6818 auto *CoverageNotesFile = 6819 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 6820 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 6821 llvm::MDNode *CU = CUNode->getOperand(i); 6822 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 6823 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 6824 } 6825 } 6826 6827 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 6828 bool ForEH) { 6829 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 6830 // FIXME: should we even be calling this method if RTTI is disabled 6831 // and it's not for EH? 6832 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice || 6833 (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 6834 getTriple().isNVPTX())) 6835 return llvm::Constant::getNullValue(Int8PtrTy); 6836 6837 if (ForEH && Ty->isObjCObjectPointerType() && 6838 LangOpts.ObjCRuntime.isGNUFamily()) 6839 return ObjCRuntime->GetEHType(Ty); 6840 6841 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 6842 } 6843 6844 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 6845 // Do not emit threadprivates in simd-only mode. 6846 if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 6847 return; 6848 for (auto RefExpr : D->varlists()) { 6849 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 6850 bool PerformInit = 6851 VD->getAnyInitializer() && 6852 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 6853 /*ForRef=*/false); 6854 6855 Address Addr(GetAddrOfGlobalVar(VD), 6856 getTypes().ConvertTypeForMem(VD->getType()), 6857 getContext().getDeclAlign(VD)); 6858 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 6859 VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 6860 CXXGlobalInits.push_back(InitFunction); 6861 } 6862 } 6863 6864 llvm::Metadata * 6865 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 6866 StringRef Suffix) { 6867 if (auto *FnType = T->getAs<FunctionProtoType>()) 6868 T = getContext().getFunctionType( 6869 FnType->getReturnType(), FnType->getParamTypes(), 6870 FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 6871 6872 llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 6873 if (InternalId) 6874 return InternalId; 6875 6876 if (isExternallyVisible(T->getLinkage())) { 6877 std::string OutName; 6878 llvm::raw_string_ostream Out(OutName); 6879 getCXXABI().getMangleContext().mangleTypeName(T, Out); 6880 Out << Suffix; 6881 6882 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 6883 } else { 6884 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 6885 llvm::ArrayRef<llvm::Metadata *>()); 6886 } 6887 6888 return InternalId; 6889 } 6890 6891 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 6892 return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 6893 } 6894 6895 llvm::Metadata * 6896 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 6897 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 6898 } 6899 6900 // Generalize pointer types to a void pointer with the qualifiers of the 6901 // originally pointed-to type, e.g. 'const char *' and 'char * const *' 6902 // generalize to 'const void *' while 'char *' and 'const char **' generalize to 6903 // 'void *'. 6904 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 6905 if (!Ty->isPointerType()) 6906 return Ty; 6907 6908 return Ctx.getPointerType( 6909 QualType(Ctx.VoidTy).withCVRQualifiers( 6910 Ty->getPointeeType().getCVRQualifiers())); 6911 } 6912 6913 // Apply type generalization to a FunctionType's return and argument types 6914 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 6915 if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 6916 SmallVector<QualType, 8> GeneralizedParams; 6917 for (auto &Param : FnType->param_types()) 6918 GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 6919 6920 return Ctx.getFunctionType( 6921 GeneralizeType(Ctx, FnType->getReturnType()), 6922 GeneralizedParams, FnType->getExtProtoInfo()); 6923 } 6924 6925 if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 6926 return Ctx.getFunctionNoProtoType( 6927 GeneralizeType(Ctx, FnType->getReturnType())); 6928 6929 llvm_unreachable("Encountered unknown FunctionType"); 6930 } 6931 6932 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 6933 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 6934 GeneralizedMetadataIdMap, ".generalized"); 6935 } 6936 6937 /// Returns whether this module needs the "all-vtables" type identifier. 6938 bool CodeGenModule::NeedAllVtablesTypeId() const { 6939 // Returns true if at least one of vtable-based CFI checkers is enabled and 6940 // is not in the trapping mode. 6941 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 6942 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 6943 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 6944 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 6945 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 6946 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 6947 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 6948 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 6949 } 6950 6951 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 6952 CharUnits Offset, 6953 const CXXRecordDecl *RD) { 6954 llvm::Metadata *MD = 6955 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 6956 VTable->addTypeMetadata(Offset.getQuantity(), MD); 6957 6958 if (CodeGenOpts.SanitizeCfiCrossDso) 6959 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 6960 VTable->addTypeMetadata(Offset.getQuantity(), 6961 llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 6962 6963 if (NeedAllVtablesTypeId()) { 6964 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 6965 VTable->addTypeMetadata(Offset.getQuantity(), MD); 6966 } 6967 } 6968 6969 llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 6970 if (!SanStats) 6971 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 6972 6973 return *SanStats; 6974 } 6975 6976 llvm::Value * 6977 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 6978 CodeGenFunction &CGF) { 6979 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 6980 auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 6981 auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 6982 auto *Call = CGF.EmitRuntimeCall( 6983 CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C}); 6984 return Call; 6985 } 6986 6987 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( 6988 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { 6989 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 6990 /* forPointeeType= */ true); 6991 } 6992 6993 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, 6994 LValueBaseInfo *BaseInfo, 6995 TBAAAccessInfo *TBAAInfo, 6996 bool forPointeeType) { 6997 if (TBAAInfo) 6998 *TBAAInfo = getTBAAAccessInfo(T); 6999 7000 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But 7001 // that doesn't return the information we need to compute BaseInfo. 7002 7003 // Honor alignment typedef attributes even on incomplete types. 7004 // We also honor them straight for C++ class types, even as pointees; 7005 // there's an expressivity gap here. 7006 if (auto TT = T->getAs<TypedefType>()) { 7007 if (auto Align = TT->getDecl()->getMaxAlignment()) { 7008 if (BaseInfo) 7009 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 7010 return getContext().toCharUnitsFromBits(Align); 7011 } 7012 } 7013 7014 bool AlignForArray = T->isArrayType(); 7015 7016 // Analyze the base element type, so we don't get confused by incomplete 7017 // array types. 7018 T = getContext().getBaseElementType(T); 7019 7020 if (T->isIncompleteType()) { 7021 // We could try to replicate the logic from 7022 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the 7023 // type is incomplete, so it's impossible to test. We could try to reuse 7024 // getTypeAlignIfKnown, but that doesn't return the information we need 7025 // to set BaseInfo. So just ignore the possibility that the alignment is 7026 // greater than one. 7027 if (BaseInfo) 7028 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 7029 return CharUnits::One(); 7030 } 7031 7032 if (BaseInfo) 7033 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 7034 7035 CharUnits Alignment; 7036 const CXXRecordDecl *RD; 7037 if (T.getQualifiers().hasUnaligned()) { 7038 Alignment = CharUnits::One(); 7039 } else if (forPointeeType && !AlignForArray && 7040 (RD = T->getAsCXXRecordDecl())) { 7041 // For C++ class pointees, we don't know whether we're pointing at a 7042 // base or a complete object, so we generally need to use the 7043 // non-virtual alignment. 7044 Alignment = getClassPointerAlignment(RD); 7045 } else { 7046 Alignment = getContext().getTypeAlignInChars(T); 7047 } 7048 7049 // Cap to the global maximum type alignment unless the alignment 7050 // was somehow explicit on the type. 7051 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 7052 if (Alignment.getQuantity() > MaxAlign && 7053 !getContext().isAlignmentRequired(T)) 7054 Alignment = CharUnits::fromQuantity(MaxAlign); 7055 } 7056 return Alignment; 7057 } 7058 7059 bool CodeGenModule::stopAutoInit() { 7060 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; 7061 if (StopAfter) { 7062 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is 7063 // used 7064 if (NumAutoVarInit >= StopAfter) { 7065 return true; 7066 } 7067 if (!NumAutoVarInit) { 7068 unsigned DiagID = getDiags().getCustomDiagID( 7069 DiagnosticsEngine::Warning, 7070 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 7071 "number of times ftrivial-auto-var-init=%1 gets applied."); 7072 getDiags().Report(DiagID) 7073 << StopAfter 7074 << (getContext().getLangOpts().getTrivialAutoVarInit() == 7075 LangOptions::TrivialAutoVarInitKind::Zero 7076 ? "zero" 7077 : "pattern"); 7078 } 7079 ++NumAutoVarInit; 7080 } 7081 return false; 7082 } 7083 7084 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS, 7085 const Decl *D) const { 7086 // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers 7087 // postfix beginning with '.' since the symbol name can be demangled. 7088 if (LangOpts.HIP) 7089 OS << (isa<VarDecl>(D) ? ".static." : ".intern."); 7090 else 7091 OS << (isa<VarDecl>(D) ? "__static__" : "__intern__"); 7092 7093 // If the CUID is not specified we try to generate a unique postfix. 7094 if (getLangOpts().CUID.empty()) { 7095 SourceManager &SM = getContext().getSourceManager(); 7096 PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation()); 7097 assert(PLoc.isValid() && "Source location is expected to be valid."); 7098 7099 // Get the hash of the user defined macros. 7100 llvm::MD5 Hash; 7101 llvm::MD5::MD5Result Result; 7102 for (const auto &Arg : PreprocessorOpts.Macros) 7103 Hash.update(Arg.first); 7104 Hash.final(Result); 7105 7106 // Get the UniqueID for the file containing the decl. 7107 llvm::sys::fs::UniqueID ID; 7108 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) { 7109 PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false); 7110 assert(PLoc.isValid() && "Source location is expected to be valid."); 7111 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) 7112 SM.getDiagnostics().Report(diag::err_cannot_open_file) 7113 << PLoc.getFilename() << EC.message(); 7114 } 7115 OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice()) 7116 << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8); 7117 } else { 7118 OS << getContext().getCUIDHash(); 7119 } 7120 } 7121 7122 void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) { 7123 assert(DeferredDeclsToEmit.empty() && 7124 "Should have emitted all decls deferred to emit."); 7125 assert(NewBuilder->DeferredDecls.empty() && 7126 "Newly created module should not have deferred decls"); 7127 NewBuilder->DeferredDecls = std::move(DeferredDecls); 7128 7129 assert(NewBuilder->DeferredVTables.empty() && 7130 "Newly created module should not have deferred vtables"); 7131 NewBuilder->DeferredVTables = std::move(DeferredVTables); 7132 7133 assert(NewBuilder->MangledDeclNames.empty() && 7134 "Newly created module should not have mangled decl names"); 7135 assert(NewBuilder->Manglings.empty() && 7136 "Newly created module should not have manglings"); 7137 NewBuilder->Manglings = std::move(Manglings); 7138 7139 assert(WeakRefReferences.empty() && "Not all WeakRefRefs have been applied"); 7140 NewBuilder->WeakRefReferences = std::move(WeakRefReferences); 7141 7142 NewBuilder->TBAA = std::move(TBAA); 7143 7144 assert(NewBuilder->EmittedDeferredDecls.empty() && 7145 "Still have (unmerged) EmittedDeferredDecls deferred decls"); 7146 7147 NewBuilder->EmittedDeferredDecls = std::move(EmittedDeferredDecls); 7148 7149 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx); 7150 } 7151