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