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