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