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