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