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