Coverage Report

Created: 2019-07-24 05:18

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