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