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