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