Coverage Report

Created: 2020-02-25 14:32

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