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