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