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