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