Coverage Report

Created: 2020-11-24 06:42

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