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