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