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