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