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