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