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