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