xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision f067435026123765bcba8094676c813a69d28a88)
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 "CGCUDARuntime.h"
16 #include "CGCXXABI.h"
17 #include "CGCall.h"
18 #include "CGDebugInfo.h"
19 #include "CGObjCRuntime.h"
20 #include "CGOpenCLRuntime.h"
21 #include "CodeGenFunction.h"
22 #include "CodeGenPGO.h"
23 #include "CodeGenTBAA.h"
24 #include "TargetInfo.h"
25 #include "clang/AST/ASTContext.h"
26 #include "clang/AST/CharUnits.h"
27 #include "clang/AST/DeclCXX.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/DeclTemplate.h"
30 #include "clang/AST/Mangle.h"
31 #include "clang/AST/RecordLayout.h"
32 #include "clang/AST/RecursiveASTVisitor.h"
33 #include "clang/Basic/Builtins.h"
34 #include "clang/Basic/CharInfo.h"
35 #include "clang/Basic/Diagnostic.h"
36 #include "clang/Basic/Module.h"
37 #include "clang/Basic/SourceManager.h"
38 #include "clang/Basic/TargetInfo.h"
39 #include "clang/Basic/Version.h"
40 #include "clang/Frontend/CodeGenOptions.h"
41 #include "clang/Sema/SemaDiagnostic.h"
42 #include "llvm/ADT/APSInt.h"
43 #include "llvm/ADT/Triple.h"
44 #include "llvm/IR/CallSite.h"
45 #include "llvm/IR/CallingConv.h"
46 #include "llvm/IR/DataLayout.h"
47 #include "llvm/IR/Intrinsics.h"
48 #include "llvm/IR/LLVMContext.h"
49 #include "llvm/IR/Module.h"
50 #include "llvm/Support/ConvertUTF.h"
51 #include "llvm/Support/ErrorHandling.h"
52 
53 using namespace clang;
54 using namespace CodeGen;
55 
56 static const char AnnotationSection[] = "llvm.metadata";
57 
58 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
59   switch (CGM.getTarget().getCXXABI().getKind()) {
60   case TargetCXXABI::GenericAArch64:
61   case TargetCXXABI::GenericARM:
62   case TargetCXXABI::iOS:
63   case TargetCXXABI::iOS64:
64   case TargetCXXABI::GenericItanium:
65     return CreateItaniumCXXABI(CGM);
66   case TargetCXXABI::Microsoft:
67     return CreateMicrosoftCXXABI(CGM);
68   }
69 
70   llvm_unreachable("invalid C++ ABI kind");
71 }
72 
73 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
74                              llvm::Module &M, const llvm::DataLayout &TD,
75                              DiagnosticsEngine &diags)
76     : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
77       Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
78       ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0),
79       TheTargetCodeGenInfo(0), Types(*this), VTables(*this), ObjCRuntime(0),
80       OpenCLRuntime(0), CUDARuntime(0), DebugInfo(0), ARCData(0),
81       NoObjCARCExceptionsMetadata(0), RRData(0), PGOData(0),
82       CFConstantStringClassRef(0),
83       ConstantStringClassRef(0), NSConstantStringType(0),
84       NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), BlockObjectAssign(0),
85       BlockObjectDispose(0), BlockDescriptorType(0), GenericBlockLiteralType(0),
86       LifetimeStartFn(0), LifetimeEndFn(0),
87       SanitizerBlacklist(
88           llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)),
89       SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled
90                                           : LangOpts.Sanitize) {
91 
92   // Initialize the type cache.
93   llvm::LLVMContext &LLVMContext = M.getContext();
94   VoidTy = llvm::Type::getVoidTy(LLVMContext);
95   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
96   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
97   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
98   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
99   FloatTy = llvm::Type::getFloatTy(LLVMContext);
100   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
101   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
102   PointerAlignInBytes =
103   C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
104   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
105   IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
106   Int8PtrTy = Int8Ty->getPointerTo(0);
107   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
108 
109   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
110 
111   if (LangOpts.ObjC1)
112     createObjCRuntime();
113   if (LangOpts.OpenCL)
114     createOpenCLRuntime();
115   if (LangOpts.CUDA)
116     createCUDARuntime();
117 
118   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
119   if (SanOpts.Thread ||
120       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
121     TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
122                            getCXXABI().getMangleContext());
123 
124   // If debug info or coverage generation is enabled, create the CGDebugInfo
125   // object.
126   if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
127       CodeGenOpts.EmitGcovArcs ||
128       CodeGenOpts.EmitGcovNotes)
129     DebugInfo = new CGDebugInfo(*this);
130 
131   Block.GlobalUniqueCount = 0;
132 
133   if (C.getLangOpts().ObjCAutoRefCount)
134     ARCData = new ARCEntrypoints();
135   RRData = new RREntrypoints();
136 
137   if (!CodeGenOpts.InstrProfileInput.empty())
138     PGOData = new PGOProfileData(*this, CodeGenOpts.InstrProfileInput);
139 }
140 
141 CodeGenModule::~CodeGenModule() {
142   delete ObjCRuntime;
143   delete OpenCLRuntime;
144   delete CUDARuntime;
145   delete TheTargetCodeGenInfo;
146   delete TBAA;
147   delete DebugInfo;
148   delete ARCData;
149   delete RRData;
150 }
151 
152 void CodeGenModule::createObjCRuntime() {
153   // This is just isGNUFamily(), but we want to force implementors of
154   // new ABIs to decide how best to do this.
155   switch (LangOpts.ObjCRuntime.getKind()) {
156   case ObjCRuntime::GNUstep:
157   case ObjCRuntime::GCC:
158   case ObjCRuntime::ObjFW:
159     ObjCRuntime = CreateGNUObjCRuntime(*this);
160     return;
161 
162   case ObjCRuntime::FragileMacOSX:
163   case ObjCRuntime::MacOSX:
164   case ObjCRuntime::iOS:
165     ObjCRuntime = CreateMacObjCRuntime(*this);
166     return;
167   }
168   llvm_unreachable("bad runtime kind");
169 }
170 
171 void CodeGenModule::createOpenCLRuntime() {
172   OpenCLRuntime = new CGOpenCLRuntime(*this);
173 }
174 
175 void CodeGenModule::createCUDARuntime() {
176   CUDARuntime = CreateNVCUDARuntime(*this);
177 }
178 
179 void CodeGenModule::applyReplacements() {
180   for (ReplacementsTy::iterator I = Replacements.begin(),
181                                 E = Replacements.end();
182        I != E; ++I) {
183     StringRef MangledName = I->first();
184     llvm::Constant *Replacement = I->second;
185     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
186     if (!Entry)
187       continue;
188     llvm::Function *OldF = cast<llvm::Function>(Entry);
189     llvm::Function *NewF = dyn_cast<llvm::Function>(Replacement);
190     if (!NewF) {
191       if (llvm::GlobalAlias *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
192         NewF = dyn_cast<llvm::Function>(Alias->getAliasedGlobal());
193       } else {
194         llvm::ConstantExpr *CE = cast<llvm::ConstantExpr>(Replacement);
195         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
196                CE->getOpcode() == llvm::Instruction::GetElementPtr);
197         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
198       }
199     }
200 
201     // Replace old with new, but keep the old order.
202     OldF->replaceAllUsesWith(Replacement);
203     if (NewF) {
204       NewF->removeFromParent();
205       OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
206     }
207     OldF->eraseFromParent();
208   }
209 }
210 
211 void CodeGenModule::checkAliases() {
212   // Check if the constructed aliases are well formed. It is really unfortunate
213   // that we have to do this in CodeGen, but we only construct mangled names
214   // and aliases during codegen.
215   bool Error = false;
216   for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
217          E = Aliases.end(); I != E; ++I) {
218     const GlobalDecl &GD = *I;
219     const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
220     const AliasAttr *AA = D->getAttr<AliasAttr>();
221     StringRef MangledName = getMangledName(GD);
222     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
223     llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
224     llvm::GlobalValue *GV = Alias->getAliasedGlobal();
225     if (!GV) {
226       Error = true;
227       getDiags().Report(AA->getLocation(), diag::err_cyclic_alias);
228     } else if (GV->isDeclaration()) {
229       Error = true;
230       getDiags().Report(AA->getLocation(), diag::err_alias_to_undefined);
231     }
232 
233     // We have to handle alias to weak aliases in here. LLVM itself disallows
234     // this since the object semantics would not match the IL one. For
235     // compatibility with gcc we implement it by just pointing the alias
236     // to its aliasee's aliasee. We also warn, since the user is probably
237     // expecting the link to be weak.
238     llvm::Constant *Aliasee = Alias->getAliasee();
239     llvm::GlobalValue *AliaseeGV;
240     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) {
241       assert((CE->getOpcode() == llvm::Instruction::BitCast ||
242               CE->getOpcode() == llvm::Instruction::AddrSpaceCast) &&
243              "Unsupported aliasee");
244       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
245     } else {
246       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
247     }
248     if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
249       if (GA->mayBeOverridden()) {
250         getDiags().Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
251           << GA->getAliasedGlobal()->getName() << GA->getName();
252         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
253             GA->getAliasee(), Alias->getType());
254         Alias->setAliasee(Aliasee);
255       }
256     }
257   }
258   if (!Error)
259     return;
260 
261   for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
262          E = Aliases.end(); I != E; ++I) {
263     const GlobalDecl &GD = *I;
264     StringRef MangledName = getMangledName(GD);
265     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
266     llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
267     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
268     Alias->eraseFromParent();
269   }
270 }
271 
272 void CodeGenModule::clear() {
273   DeferredDeclsToEmit.clear();
274 }
275 
276 void CodeGenModule::Release() {
277   EmitDeferred();
278   applyReplacements();
279   checkAliases();
280   EmitCXXGlobalInitFunc();
281   EmitCXXGlobalDtorFunc();
282   EmitCXXThreadLocalInitFunc();
283   if (ObjCRuntime)
284     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
285       AddGlobalCtor(ObjCInitFunction);
286   EmitCtorList(GlobalCtors, "llvm.global_ctors");
287   EmitCtorList(GlobalDtors, "llvm.global_dtors");
288   EmitGlobalAnnotations();
289   EmitStaticExternCAliases();
290   emitLLVMUsed();
291 
292   if (CodeGenOpts.Autolink &&
293       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
294     EmitModuleLinkOptions();
295   }
296   if (CodeGenOpts.DwarfVersion)
297     // We actually want the latest version when there are conflicts.
298     // We can change from Warning to Latest if such mode is supported.
299     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
300                               CodeGenOpts.DwarfVersion);
301   if (DebugInfo)
302     // We support a single version in the linked module: error out when
303     // modules do not have the same version. We are going to implement dropping
304     // debug info when the version number is not up-to-date. Once that is
305     // done, the bitcode linker is not going to see modules with different
306     // version numbers.
307     getModule().addModuleFlag(llvm::Module::Error, "Debug Info Version",
308                               llvm::DEBUG_METADATA_VERSION);
309 
310   SimplifyPersonality();
311 
312   if (getCodeGenOpts().EmitDeclMetadata)
313     EmitDeclMetadata();
314 
315   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
316     EmitCoverageFile();
317 
318   if (DebugInfo)
319     DebugInfo->finalize();
320 
321   EmitVersionIdentMetadata();
322 }
323 
324 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
325   // Make sure that this type is translated.
326   Types.UpdateCompletedType(TD);
327 }
328 
329 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
330   if (!TBAA)
331     return 0;
332   return TBAA->getTBAAInfo(QTy);
333 }
334 
335 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
336   if (!TBAA)
337     return 0;
338   return TBAA->getTBAAInfoForVTablePtr();
339 }
340 
341 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
342   if (!TBAA)
343     return 0;
344   return TBAA->getTBAAStructInfo(QTy);
345 }
346 
347 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
348   if (!TBAA)
349     return 0;
350   return TBAA->getTBAAStructTypeInfo(QTy);
351 }
352 
353 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
354                                                   llvm::MDNode *AccessN,
355                                                   uint64_t O) {
356   if (!TBAA)
357     return 0;
358   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
359 }
360 
361 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
362 /// and struct-path aware TBAA, the tag has the same format:
363 /// base type, access type and offset.
364 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
365 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
366                                         llvm::MDNode *TBAAInfo,
367                                         bool ConvertTypeToTag) {
368   if (ConvertTypeToTag && TBAA)
369     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
370                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
371   else
372     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
373 }
374 
375 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
376   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
377   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
378 }
379 
380 /// ErrorUnsupported - Print out an error that codegen doesn't support the
381 /// specified stmt yet.
382 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
383   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
384                                                "cannot compile this %0 yet");
385   std::string Msg = Type;
386   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
387     << Msg << S->getSourceRange();
388 }
389 
390 /// ErrorUnsupported - Print out an error that codegen doesn't support the
391 /// specified decl yet.
392 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
393   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
394                                                "cannot compile this %0 yet");
395   std::string Msg = Type;
396   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
397 }
398 
399 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
400   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
401 }
402 
403 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
404                                         const NamedDecl *D) const {
405   // Internal definitions always have default visibility.
406   if (GV->hasLocalLinkage()) {
407     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
408     return;
409   }
410 
411   // Set visibility for definitions.
412   LinkageInfo LV = D->getLinkageAndVisibility();
413   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
414     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
415 }
416 
417 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
418   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
419       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
420       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
421       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
422       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
423 }
424 
425 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
426     CodeGenOptions::TLSModel M) {
427   switch (M) {
428   case CodeGenOptions::GeneralDynamicTLSModel:
429     return llvm::GlobalVariable::GeneralDynamicTLSModel;
430   case CodeGenOptions::LocalDynamicTLSModel:
431     return llvm::GlobalVariable::LocalDynamicTLSModel;
432   case CodeGenOptions::InitialExecTLSModel:
433     return llvm::GlobalVariable::InitialExecTLSModel;
434   case CodeGenOptions::LocalExecTLSModel:
435     return llvm::GlobalVariable::LocalExecTLSModel;
436   }
437   llvm_unreachable("Invalid TLS model!");
438 }
439 
440 void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
441                                const VarDecl &D) const {
442   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
443 
444   llvm::GlobalVariable::ThreadLocalMode TLM;
445   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
446 
447   // Override the TLS model if it is explicitly specified.
448   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
449     TLM = GetLLVMTLSModel(Attr->getModel());
450   }
451 
452   GV->setThreadLocalMode(TLM);
453 }
454 
455 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
456   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
457 
458   StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
459   if (!Str.empty())
460     return Str;
461 
462   if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
463     IdentifierInfo *II = ND->getIdentifier();
464     assert(II && "Attempt to mangle unnamed decl.");
465 
466     Str = II->getName();
467     return Str;
468   }
469 
470   SmallString<256> Buffer;
471   llvm::raw_svector_ostream Out(Buffer);
472   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
473     getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
474   else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
475     getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
476   else
477     getCXXABI().getMangleContext().mangleName(ND, Out);
478 
479   // Allocate space for the mangled name.
480   Out.flush();
481   size_t Length = Buffer.size();
482   char *Name = MangledNamesAllocator.Allocate<char>(Length);
483   std::copy(Buffer.begin(), Buffer.end(), Name);
484 
485   Str = StringRef(Name, Length);
486 
487   return Str;
488 }
489 
490 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
491                                         const BlockDecl *BD) {
492   MangleContext &MangleCtx = getCXXABI().getMangleContext();
493   const Decl *D = GD.getDecl();
494   llvm::raw_svector_ostream Out(Buffer.getBuffer());
495   if (D == 0)
496     MangleCtx.mangleGlobalBlock(BD,
497       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
498   else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
499     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
500   else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
501     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
502   else
503     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
504 }
505 
506 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
507   return getModule().getNamedValue(Name);
508 }
509 
510 /// AddGlobalCtor - Add a function to the list that will be called before
511 /// main() runs.
512 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
513   // FIXME: Type coercion of void()* types.
514   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
515 }
516 
517 /// AddGlobalDtor - Add a function to the list that will be called
518 /// when the module is unloaded.
519 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
520   // FIXME: Type coercion of void()* types.
521   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
522 }
523 
524 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
525   // Ctor function type is void()*.
526   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
527   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
528 
529   // Get the type of a ctor entry, { i32, void ()* }.
530   llvm::StructType *CtorStructTy =
531     llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
532 
533   // Construct the constructor and destructor arrays.
534   SmallVector<llvm::Constant*, 8> Ctors;
535   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
536     llvm::Constant *S[] = {
537       llvm::ConstantInt::get(Int32Ty, I->second, false),
538       llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
539     };
540     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
541   }
542 
543   if (!Ctors.empty()) {
544     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
545     new llvm::GlobalVariable(TheModule, AT, false,
546                              llvm::GlobalValue::AppendingLinkage,
547                              llvm::ConstantArray::get(AT, Ctors),
548                              GlobalName);
549   }
550 }
551 
552 llvm::GlobalValue::LinkageTypes
553 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
554   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
555 
556   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
557 
558   if (Linkage == GVA_Internal)
559     return llvm::Function::InternalLinkage;
560 
561   if (D->hasAttr<DLLExportAttr>())
562     return llvm::Function::ExternalLinkage;
563 
564   if (D->hasAttr<WeakAttr>())
565     return llvm::Function::WeakAnyLinkage;
566 
567   // In C99 mode, 'inline' functions are guaranteed to have a strong
568   // definition somewhere else, so we can use available_externally linkage.
569   if (Linkage == GVA_C99Inline)
570     return llvm::Function::AvailableExternallyLinkage;
571 
572   // Note that Apple's kernel linker doesn't support symbol
573   // coalescing, so we need to avoid linkonce and weak linkages there.
574   // Normally, this means we just map to internal, but for explicit
575   // instantiations we'll map to external.
576 
577   // In C++, the compiler has to emit a definition in every translation unit
578   // that references the function.  We should use linkonce_odr because
579   // a) if all references in this translation unit are optimized away, we
580   // don't need to codegen it.  b) if the function persists, it needs to be
581   // merged with other definitions. c) C++ has the ODR, so we know the
582   // definition is dependable.
583   if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
584     return !Context.getLangOpts().AppleKext
585              ? llvm::Function::LinkOnceODRLinkage
586              : llvm::Function::InternalLinkage;
587 
588   // An explicit instantiation of a template has weak linkage, since
589   // explicit instantiations can occur in multiple translation units
590   // and must all be equivalent. However, we are not allowed to
591   // throw away these explicit instantiations.
592   if (Linkage == GVA_ExplicitTemplateInstantiation)
593     return !Context.getLangOpts().AppleKext
594              ? llvm::Function::WeakODRLinkage
595              : llvm::Function::ExternalLinkage;
596 
597   // Destructor variants in the Microsoft C++ ABI are always linkonce_odr thunks
598   // emitted on an as-needed basis.
599   if (isa<CXXDestructorDecl>(D) &&
600       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
601                                          GD.getDtorType()))
602     return llvm::Function::LinkOnceODRLinkage;
603 
604   // Otherwise, we have strong external linkage.
605   assert(Linkage == GVA_StrongExternal);
606   return llvm::Function::ExternalLinkage;
607 }
608 
609 
610 /// SetFunctionDefinitionAttributes - Set attributes for a global.
611 ///
612 /// FIXME: This is currently only done for aliases and functions, but not for
613 /// variables (these details are set in EmitGlobalVarDefinition for variables).
614 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
615                                                     llvm::GlobalValue *GV) {
616   SetCommonAttributes(D, GV);
617 }
618 
619 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
620                                               const CGFunctionInfo &Info,
621                                               llvm::Function *F) {
622   unsigned CallingConv;
623   AttributeListType AttributeList;
624   ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
625   F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
626   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
627 }
628 
629 /// Determines whether the language options require us to model
630 /// unwind exceptions.  We treat -fexceptions as mandating this
631 /// except under the fragile ObjC ABI with only ObjC exceptions
632 /// enabled.  This means, for example, that C with -fexceptions
633 /// enables this.
634 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
635   // If exceptions are completely disabled, obviously this is false.
636   if (!LangOpts.Exceptions) return false;
637 
638   // If C++ exceptions are enabled, this is true.
639   if (LangOpts.CXXExceptions) return true;
640 
641   // If ObjC exceptions are enabled, this depends on the ABI.
642   if (LangOpts.ObjCExceptions) {
643     return LangOpts.ObjCRuntime.hasUnwindExceptions();
644   }
645 
646   return true;
647 }
648 
649 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
650                                                            llvm::Function *F) {
651   llvm::AttrBuilder B;
652 
653   if (CodeGenOpts.UnwindTables)
654     B.addAttribute(llvm::Attribute::UWTable);
655 
656   if (!hasUnwindExceptions(LangOpts))
657     B.addAttribute(llvm::Attribute::NoUnwind);
658 
659   if (D->hasAttr<NakedAttr>()) {
660     // Naked implies noinline: we should not be inlining such functions.
661     B.addAttribute(llvm::Attribute::Naked);
662     B.addAttribute(llvm::Attribute::NoInline);
663   } else if (D->hasAttr<OptimizeNoneAttr>()) {
664     // OptimizeNone implies noinline; we should not be inlining such functions.
665     B.addAttribute(llvm::Attribute::OptimizeNone);
666     B.addAttribute(llvm::Attribute::NoInline);
667   } else if (D->hasAttr<NoDuplicateAttr>()) {
668     B.addAttribute(llvm::Attribute::NoDuplicate);
669   } else if (D->hasAttr<NoInlineAttr>()) {
670     B.addAttribute(llvm::Attribute::NoInline);
671   } else if (D->hasAttr<AlwaysInlineAttr>() &&
672              !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
673                                               llvm::Attribute::NoInline)) {
674     // (noinline wins over always_inline, and we can't specify both in IR)
675     B.addAttribute(llvm::Attribute::AlwaysInline);
676   }
677 
678   if (D->hasAttr<ColdAttr>()) {
679     B.addAttribute(llvm::Attribute::OptimizeForSize);
680     B.addAttribute(llvm::Attribute::Cold);
681   }
682 
683   if (D->hasAttr<MinSizeAttr>())
684     B.addAttribute(llvm::Attribute::MinSize);
685 
686   if (D->hasAttr<OptimizeNoneAttr>()) {
687     // OptimizeNone wins over OptimizeForSize and MinSize.
688     B.removeAttribute(llvm::Attribute::OptimizeForSize);
689     B.removeAttribute(llvm::Attribute::MinSize);
690   }
691 
692   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
693     B.addAttribute(llvm::Attribute::StackProtect);
694   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
695     B.addAttribute(llvm::Attribute::StackProtectStrong);
696   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
697     B.addAttribute(llvm::Attribute::StackProtectReq);
698 
699   // Add sanitizer attributes if function is not blacklisted.
700   if (!SanitizerBlacklist->isIn(*F)) {
701     // When AddressSanitizer is enabled, set SanitizeAddress attribute
702     // unless __attribute__((no_sanitize_address)) is used.
703     if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
704       B.addAttribute(llvm::Attribute::SanitizeAddress);
705     // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
706     if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
707       B.addAttribute(llvm::Attribute::SanitizeThread);
708     }
709     // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
710     if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
711       B.addAttribute(llvm::Attribute::SanitizeMemory);
712   }
713 
714   F->addAttributes(llvm::AttributeSet::FunctionIndex,
715                    llvm::AttributeSet::get(
716                        F->getContext(), llvm::AttributeSet::FunctionIndex, B));
717 
718   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
719     F->setUnnamedAddr(true);
720   else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
721     if (MD->isVirtual())
722       F->setUnnamedAddr(true);
723 
724   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
725   if (alignment)
726     F->setAlignment(alignment);
727 
728   // C++ ABI requires 2-byte alignment for member functions.
729   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
730     F->setAlignment(2);
731 }
732 
733 void CodeGenModule::SetCommonAttributes(const Decl *D,
734                                         llvm::GlobalValue *GV) {
735   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
736     setGlobalVisibility(GV, ND);
737   else
738     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
739 
740   if (D->hasAttr<UsedAttr>())
741     addUsedGlobal(GV);
742 
743   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
744     GV->setSection(SA->getName());
745 
746   // Alias cannot have attributes. Filter them here.
747   if (!isa<llvm::GlobalAlias>(GV))
748     getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
749 }
750 
751 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
752                                                   llvm::Function *F,
753                                                   const CGFunctionInfo &FI) {
754   SetLLVMFunctionAttributes(D, FI, F);
755   SetLLVMFunctionAttributesForDefinition(D, F);
756 
757   F->setLinkage(llvm::Function::InternalLinkage);
758 
759   SetCommonAttributes(D, F);
760 }
761 
762 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
763                                           llvm::Function *F,
764                                           bool IsIncompleteFunction) {
765   if (unsigned IID = F->getIntrinsicID()) {
766     // If this is an intrinsic function, set the function's attributes
767     // to the intrinsic's attributes.
768     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
769                                                     (llvm::Intrinsic::ID)IID));
770     return;
771   }
772 
773   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
774 
775   if (!IsIncompleteFunction)
776     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
777 
778   if (getCXXABI().HasThisReturn(GD)) {
779     assert(!F->arg_empty() &&
780            F->arg_begin()->getType()
781              ->canLosslesslyBitCastTo(F->getReturnType()) &&
782            "unexpected this return");
783     F->addAttribute(1, llvm::Attribute::Returned);
784   }
785 
786   // Only a few attributes are set on declarations; these may later be
787   // overridden by a definition.
788 
789   if (FD->hasAttr<DLLImportAttr>()) {
790     F->setLinkage(llvm::Function::ExternalLinkage);
791     F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
792   } else if (FD->hasAttr<WeakAttr>() ||
793              FD->isWeakImported()) {
794     // "extern_weak" is overloaded in LLVM; we probably should have
795     // separate linkage types for this.
796     F->setLinkage(llvm::Function::ExternalWeakLinkage);
797   } else {
798     F->setLinkage(llvm::Function::ExternalLinkage);
799     if (FD->hasAttr<DLLExportAttr>())
800       F->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
801 
802     LinkageInfo LV = FD->getLinkageAndVisibility();
803     if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) {
804       F->setVisibility(GetLLVMVisibility(LV.getVisibility()));
805     }
806   }
807 
808   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
809     F->setSection(SA->getName());
810 
811   // A replaceable global allocation function does not act like a builtin by
812   // default, only if it is invoked by a new-expression or delete-expression.
813   if (FD->isReplaceableGlobalAllocationFunction())
814     F->addAttribute(llvm::AttributeSet::FunctionIndex,
815                     llvm::Attribute::NoBuiltin);
816 }
817 
818 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
819   assert(!GV->isDeclaration() &&
820          "Only globals with definition can force usage.");
821   LLVMUsed.push_back(GV);
822 }
823 
824 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
825   assert(!GV->isDeclaration() &&
826          "Only globals with definition can force usage.");
827   LLVMCompilerUsed.push_back(GV);
828 }
829 
830 static void emitUsed(CodeGenModule &CGM, StringRef Name,
831                      std::vector<llvm::WeakVH> &List) {
832   // Don't create llvm.used if there is no need.
833   if (List.empty())
834     return;
835 
836   // Convert List to what ConstantArray needs.
837   SmallVector<llvm::Constant*, 8> UsedArray;
838   UsedArray.resize(List.size());
839   for (unsigned i = 0, e = List.size(); i != e; ++i) {
840     UsedArray[i] =
841      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]),
842                                     CGM.Int8PtrTy);
843   }
844 
845   if (UsedArray.empty())
846     return;
847   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
848 
849   llvm::GlobalVariable *GV =
850     new llvm::GlobalVariable(CGM.getModule(), ATy, false,
851                              llvm::GlobalValue::AppendingLinkage,
852                              llvm::ConstantArray::get(ATy, UsedArray),
853                              Name);
854 
855   GV->setSection("llvm.metadata");
856 }
857 
858 void CodeGenModule::emitLLVMUsed() {
859   emitUsed(*this, "llvm.used", LLVMUsed);
860   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
861 }
862 
863 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
864   llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
865   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
866 }
867 
868 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
869   llvm::SmallString<32> Opt;
870   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
871   llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
872   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
873 }
874 
875 void CodeGenModule::AddDependentLib(StringRef Lib) {
876   llvm::SmallString<24> Opt;
877   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
878   llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
879   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
880 }
881 
882 /// \brief Add link options implied by the given module, including modules
883 /// it depends on, using a postorder walk.
884 static void addLinkOptionsPostorder(CodeGenModule &CGM,
885                                     Module *Mod,
886                                     SmallVectorImpl<llvm::Value *> &Metadata,
887                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
888   // Import this module's parent.
889   if (Mod->Parent && Visited.insert(Mod->Parent)) {
890     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
891   }
892 
893   // Import this module's dependencies.
894   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
895     if (Visited.insert(Mod->Imports[I-1]))
896       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
897   }
898 
899   // Add linker options to link against the libraries/frameworks
900   // described by this module.
901   llvm::LLVMContext &Context = CGM.getLLVMContext();
902   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
903     // Link against a framework.  Frameworks are currently Darwin only, so we
904     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
905     if (Mod->LinkLibraries[I-1].IsFramework) {
906       llvm::Value *Args[2] = {
907         llvm::MDString::get(Context, "-framework"),
908         llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
909       };
910 
911       Metadata.push_back(llvm::MDNode::get(Context, Args));
912       continue;
913     }
914 
915     // Link against a library.
916     llvm::SmallString<24> Opt;
917     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
918       Mod->LinkLibraries[I-1].Library, Opt);
919     llvm::Value *OptString = llvm::MDString::get(Context, Opt);
920     Metadata.push_back(llvm::MDNode::get(Context, OptString));
921   }
922 }
923 
924 void CodeGenModule::EmitModuleLinkOptions() {
925   // Collect the set of all of the modules we want to visit to emit link
926   // options, which is essentially the imported modules and all of their
927   // non-explicit child modules.
928   llvm::SetVector<clang::Module *> LinkModules;
929   llvm::SmallPtrSet<clang::Module *, 16> Visited;
930   SmallVector<clang::Module *, 16> Stack;
931 
932   // Seed the stack with imported modules.
933   for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
934                                                MEnd = ImportedModules.end();
935        M != MEnd; ++M) {
936     if (Visited.insert(*M))
937       Stack.push_back(*M);
938   }
939 
940   // Find all of the modules to import, making a little effort to prune
941   // non-leaf modules.
942   while (!Stack.empty()) {
943     clang::Module *Mod = Stack.pop_back_val();
944 
945     bool AnyChildren = false;
946 
947     // Visit the submodules of this module.
948     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
949                                         SubEnd = Mod->submodule_end();
950          Sub != SubEnd; ++Sub) {
951       // Skip explicit children; they need to be explicitly imported to be
952       // linked against.
953       if ((*Sub)->IsExplicit)
954         continue;
955 
956       if (Visited.insert(*Sub)) {
957         Stack.push_back(*Sub);
958         AnyChildren = true;
959       }
960     }
961 
962     // We didn't find any children, so add this module to the list of
963     // modules to link against.
964     if (!AnyChildren) {
965       LinkModules.insert(Mod);
966     }
967   }
968 
969   // Add link options for all of the imported modules in reverse topological
970   // order.  We don't do anything to try to order import link flags with respect
971   // to linker options inserted by things like #pragma comment().
972   SmallVector<llvm::Value *, 16> MetadataArgs;
973   Visited.clear();
974   for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
975                                                MEnd = LinkModules.end();
976        M != MEnd; ++M) {
977     if (Visited.insert(*M))
978       addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
979   }
980   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
981   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
982 
983   // Add the linker options metadata flag.
984   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
985                             llvm::MDNode::get(getLLVMContext(),
986                                               LinkerOptionsMetadata));
987 }
988 
989 void CodeGenModule::EmitDeferred() {
990   // Emit code for any potentially referenced deferred decls.  Since a
991   // previously unused static decl may become used during the generation of code
992   // for a static function, iterate until no changes are made.
993 
994   while (true) {
995     if (!DeferredVTables.empty()) {
996       EmitDeferredVTables();
997 
998       // Emitting a v-table doesn't directly cause more v-tables to
999       // become deferred, although it can cause functions to be
1000       // emitted that then need those v-tables.
1001       assert(DeferredVTables.empty());
1002     }
1003 
1004     // Stop if we're out of both deferred v-tables and deferred declarations.
1005     if (DeferredDeclsToEmit.empty()) break;
1006 
1007     DeferredGlobal &G = DeferredDeclsToEmit.back();
1008     GlobalDecl D = G.GD;
1009     llvm::GlobalValue *GV = G.GV;
1010     DeferredDeclsToEmit.pop_back();
1011 
1012     assert(GV == GetGlobalValue(getMangledName(D)));
1013     // Check to see if we've already emitted this.  This is necessary
1014     // for a couple of reasons: first, decls can end up in the
1015     // deferred-decls queue multiple times, and second, decls can end
1016     // up with definitions in unusual ways (e.g. by an extern inline
1017     // function acquiring a strong function redefinition).  Just
1018     // ignore these cases.
1019     if(!GV->isDeclaration())
1020       continue;
1021 
1022     // Otherwise, emit the definition and move on to the next one.
1023     EmitGlobalDefinition(D, GV);
1024   }
1025 }
1026 
1027 void CodeGenModule::EmitGlobalAnnotations() {
1028   if (Annotations.empty())
1029     return;
1030 
1031   // Create a new global variable for the ConstantStruct in the Module.
1032   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1033     Annotations[0]->getType(), Annotations.size()), Annotations);
1034   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
1035     Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
1036     "llvm.global.annotations");
1037   gv->setSection(AnnotationSection);
1038 }
1039 
1040 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1041   llvm::Constant *&AStr = AnnotationStrings[Str];
1042   if (AStr)
1043     return AStr;
1044 
1045   // Not found yet, create a new global.
1046   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1047   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
1048     true, llvm::GlobalValue::PrivateLinkage, s, ".str");
1049   gv->setSection(AnnotationSection);
1050   gv->setUnnamedAddr(true);
1051   AStr = gv;
1052   return gv;
1053 }
1054 
1055 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1056   SourceManager &SM = getContext().getSourceManager();
1057   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1058   if (PLoc.isValid())
1059     return EmitAnnotationString(PLoc.getFilename());
1060   return EmitAnnotationString(SM.getBufferName(Loc));
1061 }
1062 
1063 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1064   SourceManager &SM = getContext().getSourceManager();
1065   PresumedLoc PLoc = SM.getPresumedLoc(L);
1066   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1067     SM.getExpansionLineNumber(L);
1068   return llvm::ConstantInt::get(Int32Ty, LineNo);
1069 }
1070 
1071 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1072                                                 const AnnotateAttr *AA,
1073                                                 SourceLocation L) {
1074   // Get the globals for file name, annotation, and the line number.
1075   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1076                  *UnitGV = EmitAnnotationUnit(L),
1077                  *LineNoCst = EmitAnnotationLineNo(L);
1078 
1079   // Create the ConstantStruct for the global annotation.
1080   llvm::Constant *Fields[4] = {
1081     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1082     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1083     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1084     LineNoCst
1085   };
1086   return llvm::ConstantStruct::getAnon(Fields);
1087 }
1088 
1089 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1090                                          llvm::GlobalValue *GV) {
1091   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1092   // Get the struct elements for these annotations.
1093   for (const auto *I : D->specific_attrs<AnnotateAttr>())
1094     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1095 }
1096 
1097 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
1098   // Never defer when EmitAllDecls is specified.
1099   if (LangOpts.EmitAllDecls)
1100     return false;
1101 
1102   return !getContext().DeclMustBeEmitted(Global);
1103 }
1104 
1105 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1106     const CXXUuidofExpr* E) {
1107   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1108   // well-formed.
1109   StringRef Uuid = E->getUuidAsStringRef(Context);
1110   std::string Name = "_GUID_" + Uuid.lower();
1111   std::replace(Name.begin(), Name.end(), '-', '_');
1112 
1113   // Look for an existing global.
1114   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1115     return GV;
1116 
1117   llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
1118   assert(Init && "failed to initialize as constant");
1119 
1120   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1121       getModule(), Init->getType(),
1122       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1123   return GV;
1124 }
1125 
1126 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1127   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1128   assert(AA && "No alias?");
1129 
1130   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1131 
1132   // See if there is already something with the target's name in the module.
1133   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1134   if (Entry) {
1135     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1136     return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1137   }
1138 
1139   llvm::Constant *Aliasee;
1140   if (isa<llvm::FunctionType>(DeclTy))
1141     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1142                                       GlobalDecl(cast<FunctionDecl>(VD)),
1143                                       /*ForVTable=*/false);
1144   else
1145     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1146                                     llvm::PointerType::getUnqual(DeclTy), 0);
1147 
1148   llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
1149   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1150   WeakRefReferences.insert(F);
1151 
1152   return Aliasee;
1153 }
1154 
1155 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1156   const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
1157 
1158   // Weak references don't produce any output by themselves.
1159   if (Global->hasAttr<WeakRefAttr>())
1160     return;
1161 
1162   // If this is an alias definition (which otherwise looks like a declaration)
1163   // emit it now.
1164   if (Global->hasAttr<AliasAttr>())
1165     return EmitAliasDefinition(GD);
1166 
1167   // If this is CUDA, be selective about which declarations we emit.
1168   if (LangOpts.CUDA) {
1169     if (CodeGenOpts.CUDAIsDevice) {
1170       if (!Global->hasAttr<CUDADeviceAttr>() &&
1171           !Global->hasAttr<CUDAGlobalAttr>() &&
1172           !Global->hasAttr<CUDAConstantAttr>() &&
1173           !Global->hasAttr<CUDASharedAttr>())
1174         return;
1175     } else {
1176       if (!Global->hasAttr<CUDAHostAttr>() && (
1177             Global->hasAttr<CUDADeviceAttr>() ||
1178             Global->hasAttr<CUDAConstantAttr>() ||
1179             Global->hasAttr<CUDASharedAttr>()))
1180         return;
1181     }
1182   }
1183 
1184   // Ignore declarations, they will be emitted on their first use.
1185   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
1186     // Forward declarations are emitted lazily on first use.
1187     if (!FD->doesThisDeclarationHaveABody()) {
1188       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1189         return;
1190 
1191       StringRef MangledName = getMangledName(GD);
1192 
1193       // Compute the function info and LLVM type.
1194       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1195       llvm::Type *Ty = getTypes().GetFunctionType(FI);
1196 
1197       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1198                               /*DontDefer=*/false);
1199       return;
1200     }
1201   } else {
1202     const VarDecl *VD = cast<VarDecl>(Global);
1203     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1204 
1205     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
1206       return;
1207   }
1208 
1209   // Defer code generation when possible if this is a static definition, inline
1210   // function etc.  These we only want to emit if they are used.
1211   if (!MayDeferGeneration(Global)) {
1212     // Emit the definition if it can't be deferred.
1213     EmitGlobalDefinition(GD);
1214     return;
1215   }
1216 
1217   // If we're deferring emission of a C++ variable with an
1218   // initializer, remember the order in which it appeared in the file.
1219   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1220       cast<VarDecl>(Global)->hasInit()) {
1221     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1222     CXXGlobalInits.push_back(0);
1223   }
1224 
1225   // If the value has already been used, add it directly to the
1226   // DeferredDeclsToEmit list.
1227   StringRef MangledName = getMangledName(GD);
1228   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName))
1229     addDeferredDeclToEmit(GV, GD);
1230   else {
1231     // Otherwise, remember that we saw a deferred decl with this name.  The
1232     // first use of the mangled name will cause it to move into
1233     // DeferredDeclsToEmit.
1234     DeferredDecls[MangledName] = GD;
1235   }
1236 }
1237 
1238 namespace {
1239   struct FunctionIsDirectlyRecursive :
1240     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1241     const StringRef Name;
1242     const Builtin::Context &BI;
1243     bool Result;
1244     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1245       Name(N), BI(C), Result(false) {
1246     }
1247     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1248 
1249     bool TraverseCallExpr(CallExpr *E) {
1250       const FunctionDecl *FD = E->getDirectCallee();
1251       if (!FD)
1252         return true;
1253       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1254       if (Attr && Name == Attr->getLabel()) {
1255         Result = true;
1256         return false;
1257       }
1258       unsigned BuiltinID = FD->getBuiltinID();
1259       if (!BuiltinID)
1260         return true;
1261       StringRef BuiltinName = BI.GetName(BuiltinID);
1262       if (BuiltinName.startswith("__builtin_") &&
1263           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1264         Result = true;
1265         return false;
1266       }
1267       return true;
1268     }
1269   };
1270 }
1271 
1272 // isTriviallyRecursive - Check if this function calls another
1273 // decl that, because of the asm attribute or the other decl being a builtin,
1274 // ends up pointing to itself.
1275 bool
1276 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1277   StringRef Name;
1278   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1279     // asm labels are a special kind of mangling we have to support.
1280     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1281     if (!Attr)
1282       return false;
1283     Name = Attr->getLabel();
1284   } else {
1285     Name = FD->getName();
1286   }
1287 
1288   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1289   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1290   return Walker.Result;
1291 }
1292 
1293 bool
1294 CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1295   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1296     return true;
1297   const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl());
1298   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1299     return false;
1300   // PR9614. Avoid cases where the source code is lying to us. An available
1301   // externally function should have an equivalent function somewhere else,
1302   // but a function that calls itself is clearly not equivalent to the real
1303   // implementation.
1304   // This happens in glibc's btowc and in some configure checks.
1305   return !isTriviallyRecursive(F);
1306 }
1307 
1308 /// If the type for the method's class was generated by
1309 /// CGDebugInfo::createContextChain(), the cache contains only a
1310 /// limited DIType without any declarations. Since EmitFunctionStart()
1311 /// needs to find the canonical declaration for each method, we need
1312 /// to construct the complete type prior to emitting the method.
1313 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1314   if (!D->isInstance())
1315     return;
1316 
1317   if (CGDebugInfo *DI = getModuleDebugInfo())
1318     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1319       const PointerType *ThisPtr =
1320         cast<PointerType>(D->getThisType(getContext()));
1321       DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1322     }
1323 }
1324 
1325 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1326   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1327 
1328   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1329                                  Context.getSourceManager(),
1330                                  "Generating code for declaration");
1331 
1332   if (isa<FunctionDecl>(D)) {
1333     // At -O0, don't generate IR for functions with available_externally
1334     // linkage.
1335     if (!shouldEmitFunction(GD))
1336       return;
1337 
1338     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1339       CompleteDIClassType(Method);
1340       // Make sure to emit the definition(s) before we emit the thunks.
1341       // This is necessary for the generation of certain thunks.
1342       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1343         EmitCXXConstructor(CD, GD.getCtorType());
1344       else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1345         EmitCXXDestructor(DD, GD.getDtorType());
1346       else
1347         EmitGlobalFunctionDefinition(GD, GV);
1348 
1349       if (Method->isVirtual())
1350         getVTables().EmitThunks(GD);
1351 
1352       return;
1353     }
1354 
1355     return EmitGlobalFunctionDefinition(GD, GV);
1356   }
1357 
1358   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1359     return EmitGlobalVarDefinition(VD);
1360 
1361   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1362 }
1363 
1364 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1365 /// module, create and return an llvm Function with the specified type. If there
1366 /// is something in the module with the specified name, return it potentially
1367 /// bitcasted to the right type.
1368 ///
1369 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1370 /// to set the attributes on the function when it is first created.
1371 llvm::Constant *
1372 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1373                                        llvm::Type *Ty,
1374                                        GlobalDecl GD, bool ForVTable,
1375                                        bool DontDefer,
1376                                        llvm::AttributeSet ExtraAttrs) {
1377   const Decl *D = GD.getDecl();
1378 
1379   // Lookup the entry, lazily creating it if necessary.
1380   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1381   if (Entry) {
1382     if (WeakRefReferences.erase(Entry)) {
1383       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1384       if (FD && !FD->hasAttr<WeakAttr>())
1385         Entry->setLinkage(llvm::Function::ExternalLinkage);
1386     }
1387 
1388     if (Entry->getType()->getElementType() == Ty)
1389       return Entry;
1390 
1391     // Make sure the result is of the correct type.
1392     return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1393   }
1394 
1395   // This function doesn't have a complete type (for example, the return
1396   // type is an incomplete struct). Use a fake type instead, and make
1397   // sure not to try to set attributes.
1398   bool IsIncompleteFunction = false;
1399 
1400   llvm::FunctionType *FTy;
1401   if (isa<llvm::FunctionType>(Ty)) {
1402     FTy = cast<llvm::FunctionType>(Ty);
1403   } else {
1404     FTy = llvm::FunctionType::get(VoidTy, false);
1405     IsIncompleteFunction = true;
1406   }
1407 
1408   llvm::Function *F = llvm::Function::Create(FTy,
1409                                              llvm::Function::ExternalLinkage,
1410                                              MangledName, &getModule());
1411   assert(F->getName() == MangledName && "name was uniqued!");
1412   if (D)
1413     SetFunctionAttributes(GD, F, IsIncompleteFunction);
1414   if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1415     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1416     F->addAttributes(llvm::AttributeSet::FunctionIndex,
1417                      llvm::AttributeSet::get(VMContext,
1418                                              llvm::AttributeSet::FunctionIndex,
1419                                              B));
1420   }
1421 
1422   if (!DontDefer) {
1423     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1424     // each other bottoming out with the base dtor.  Therefore we emit non-base
1425     // dtors on usage, even if there is no dtor definition in the TU.
1426     if (D && isa<CXXDestructorDecl>(D) &&
1427         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1428                                            GD.getDtorType()))
1429       addDeferredDeclToEmit(F, GD);
1430 
1431     // This is the first use or definition of a mangled name.  If there is a
1432     // deferred decl with this name, remember that we need to emit it at the end
1433     // of the file.
1434     llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1435     if (DDI != DeferredDecls.end()) {
1436       // Move the potentially referenced deferred decl to the
1437       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1438       // don't need it anymore).
1439       addDeferredDeclToEmit(F, DDI->second);
1440       DeferredDecls.erase(DDI);
1441 
1442       // Otherwise, if this is a sized deallocation function, emit a weak
1443       // definition
1444       // for it at the end of the translation unit.
1445     } else if (D && cast<FunctionDecl>(D)
1446                         ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
1447       addDeferredDeclToEmit(F, GD);
1448 
1449       // Otherwise, there are cases we have to worry about where we're
1450       // using a declaration for which we must emit a definition but where
1451       // we might not find a top-level definition:
1452       //   - member functions defined inline in their classes
1453       //   - friend functions defined inline in some class
1454       //   - special member functions with implicit definitions
1455       // If we ever change our AST traversal to walk into class methods,
1456       // this will be unnecessary.
1457       //
1458       // We also don't emit a definition for a function if it's going to be an
1459       // entry
1460       // in a vtable, unless it's already marked as used.
1461     } else if (getLangOpts().CPlusPlus && D) {
1462       // Look for a declaration that's lexically in a record.
1463       const FunctionDecl *FD = cast<FunctionDecl>(D);
1464       FD = FD->getMostRecentDecl();
1465       do {
1466         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1467           if (FD->isImplicit() && !ForVTable) {
1468             assert(FD->isUsed() &&
1469                    "Sema didn't mark implicit function as used!");
1470             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1471             break;
1472           } else if (FD->doesThisDeclarationHaveABody()) {
1473             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1474             break;
1475           }
1476         }
1477         FD = FD->getPreviousDecl();
1478       } while (FD);
1479     }
1480   }
1481 
1482   // Make sure the result is of the requested type.
1483   if (!IsIncompleteFunction) {
1484     assert(F->getType()->getElementType() == Ty);
1485     return F;
1486   }
1487 
1488   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1489   return llvm::ConstantExpr::getBitCast(F, PTy);
1490 }
1491 
1492 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1493 /// non-null, then this function will use the specified type if it has to
1494 /// create it (this occurs when we see a definition of the function).
1495 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1496                                                  llvm::Type *Ty,
1497                                                  bool ForVTable,
1498                                                  bool DontDefer) {
1499   // If there was no specific requested type, just convert it now.
1500   if (!Ty)
1501     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1502 
1503   StringRef MangledName = getMangledName(GD);
1504   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
1505 }
1506 
1507 /// CreateRuntimeFunction - Create a new runtime function with the specified
1508 /// type and name.
1509 llvm::Constant *
1510 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1511                                      StringRef Name,
1512                                      llvm::AttributeSet ExtraAttrs) {
1513   llvm::Constant *C =
1514       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1515                               /*DontDefer=*/false, ExtraAttrs);
1516   if (llvm::Function *F = dyn_cast<llvm::Function>(C))
1517     if (F->empty())
1518       F->setCallingConv(getRuntimeCC());
1519   return C;
1520 }
1521 
1522 /// isTypeConstant - Determine whether an object of this type can be emitted
1523 /// as a constant.
1524 ///
1525 /// If ExcludeCtor is true, the duration when the object's constructor runs
1526 /// will not be considered. The caller will need to verify that the object is
1527 /// not written to during its construction.
1528 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1529   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1530     return false;
1531 
1532   if (Context.getLangOpts().CPlusPlus) {
1533     if (const CXXRecordDecl *Record
1534           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1535       return ExcludeCtor && !Record->hasMutableFields() &&
1536              Record->hasTrivialDestructor();
1537   }
1538 
1539   return true;
1540 }
1541 
1542 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1543 /// create and return an llvm GlobalVariable with the specified type.  If there
1544 /// is something in the module with the specified name, return it potentially
1545 /// bitcasted to the right type.
1546 ///
1547 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1548 /// to set the attributes on the global when it is first created.
1549 llvm::Constant *
1550 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1551                                      llvm::PointerType *Ty,
1552                                      const VarDecl *D,
1553                                      bool UnnamedAddr) {
1554   // Lookup the entry, lazily creating it if necessary.
1555   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1556   if (Entry) {
1557     if (WeakRefReferences.erase(Entry)) {
1558       if (D && !D->hasAttr<WeakAttr>())
1559         Entry->setLinkage(llvm::Function::ExternalLinkage);
1560     }
1561 
1562     if (UnnamedAddr)
1563       Entry->setUnnamedAddr(true);
1564 
1565     if (Entry->getType() == Ty)
1566       return Entry;
1567 
1568     // Make sure the result is of the correct type.
1569     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1570       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1571 
1572     return llvm::ConstantExpr::getBitCast(Entry, Ty);
1573   }
1574 
1575   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1576   llvm::GlobalVariable *GV =
1577     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1578                              llvm::GlobalValue::ExternalLinkage,
1579                              0, MangledName, 0,
1580                              llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1581 
1582   // This is the first use or definition of a mangled name.  If there is a
1583   // deferred decl with this name, remember that we need to emit it at the end
1584   // of the file.
1585   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1586   if (DDI != DeferredDecls.end()) {
1587     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1588     // list, and remove it from DeferredDecls (since we don't need it anymore).
1589     addDeferredDeclToEmit(GV, DDI->second);
1590     DeferredDecls.erase(DDI);
1591   }
1592 
1593   // Handle things which are present even on external declarations.
1594   if (D) {
1595     // FIXME: This code is overly simple and should be merged with other global
1596     // handling.
1597     GV->setConstant(isTypeConstant(D->getType(), false));
1598 
1599     // Set linkage and visibility in case we never see a definition.
1600     LinkageInfo LV = D->getLinkageAndVisibility();
1601     if (LV.getLinkage() != ExternalLinkage) {
1602       // Don't set internal linkage on declarations.
1603     } else {
1604       if (D->hasAttr<DLLImportAttr>()) {
1605         GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1606         GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1607       } else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1608         GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1609 
1610       // Set visibility on a declaration only if it's explicit.
1611       if (LV.isVisibilityExplicit())
1612         GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1613     }
1614 
1615     if (D->getTLSKind()) {
1616       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1617         CXXThreadLocals.push_back(std::make_pair(D, GV));
1618       setTLSMode(GV, *D);
1619     }
1620 
1621     // If required by the ABI, treat declarations of static data members with
1622     // inline initializers as definitions.
1623     if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1624         D->isStaticDataMember() && D->hasInit() &&
1625         !D->isThisDeclarationADefinition())
1626       EmitGlobalVarDefinition(D);
1627   }
1628 
1629   if (AddrSpace != Ty->getAddressSpace())
1630     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1631 
1632   if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
1633       D->getLanguageLinkage() == CLanguageLinkage &&
1634       D->getType().isConstant(Context) &&
1635       isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
1636     GV->setSection(".cp.rodata");
1637 
1638   return GV;
1639 }
1640 
1641 
1642 llvm::GlobalVariable *
1643 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1644                                       llvm::Type *Ty,
1645                                       llvm::GlobalValue::LinkageTypes Linkage) {
1646   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1647   llvm::GlobalVariable *OldGV = 0;
1648 
1649 
1650   if (GV) {
1651     // Check if the variable has the right type.
1652     if (GV->getType()->getElementType() == Ty)
1653       return GV;
1654 
1655     // Because C++ name mangling, the only way we can end up with an already
1656     // existing global with the same name is if it has been declared extern "C".
1657     assert(GV->isDeclaration() && "Declaration has wrong type!");
1658     OldGV = GV;
1659   }
1660 
1661   // Create a new variable.
1662   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1663                                 Linkage, 0, Name);
1664 
1665   if (OldGV) {
1666     // Replace occurrences of the old variable if needed.
1667     GV->takeName(OldGV);
1668 
1669     if (!OldGV->use_empty()) {
1670       llvm::Constant *NewPtrForOldDecl =
1671       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1672       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1673     }
1674 
1675     OldGV->eraseFromParent();
1676   }
1677 
1678   return GV;
1679 }
1680 
1681 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1682 /// given global variable.  If Ty is non-null and if the global doesn't exist,
1683 /// then it will be created with the specified type instead of whatever the
1684 /// normal requested type would be.
1685 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1686                                                   llvm::Type *Ty) {
1687   assert(D->hasGlobalStorage() && "Not a global variable");
1688   QualType ASTTy = D->getType();
1689   if (Ty == 0)
1690     Ty = getTypes().ConvertTypeForMem(ASTTy);
1691 
1692   llvm::PointerType *PTy =
1693     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1694 
1695   StringRef MangledName = getMangledName(D);
1696   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1697 }
1698 
1699 /// CreateRuntimeVariable - Create a new runtime global variable with the
1700 /// specified type and name.
1701 llvm::Constant *
1702 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1703                                      StringRef Name) {
1704   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1705                                true);
1706 }
1707 
1708 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1709   assert(!D->getInit() && "Cannot emit definite definitions here!");
1710 
1711   if (MayDeferGeneration(D)) {
1712     // If we have not seen a reference to this variable yet, place it
1713     // into the deferred declarations table to be emitted if needed
1714     // later.
1715     StringRef MangledName = getMangledName(D);
1716     if (!GetGlobalValue(MangledName)) {
1717       DeferredDecls[MangledName] = D;
1718       return;
1719     }
1720   }
1721 
1722   // The tentative definition is the only definition.
1723   EmitGlobalVarDefinition(D);
1724 }
1725 
1726 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1727     return Context.toCharUnitsFromBits(
1728       TheDataLayout.getTypeStoreSizeInBits(Ty));
1729 }
1730 
1731 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1732                                                  unsigned AddrSpace) {
1733   if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1734     if (D->hasAttr<CUDAConstantAttr>())
1735       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1736     else if (D->hasAttr<CUDASharedAttr>())
1737       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1738     else
1739       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1740   }
1741 
1742   return AddrSpace;
1743 }
1744 
1745 template<typename SomeDecl>
1746 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1747                                                llvm::GlobalValue *GV) {
1748   if (!getLangOpts().CPlusPlus)
1749     return;
1750 
1751   // Must have 'used' attribute, or else inline assembly can't rely on
1752   // the name existing.
1753   if (!D->template hasAttr<UsedAttr>())
1754     return;
1755 
1756   // Must have internal linkage and an ordinary name.
1757   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
1758     return;
1759 
1760   // Must be in an extern "C" context. Entities declared directly within
1761   // a record are not extern "C" even if the record is in such a context.
1762   const SomeDecl *First = D->getFirstDecl();
1763   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
1764     return;
1765 
1766   // OK, this is an internal linkage entity inside an extern "C" linkage
1767   // specification. Make a note of that so we can give it the "expected"
1768   // mangled name if nothing else is using that name.
1769   std::pair<StaticExternCMap::iterator, bool> R =
1770       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
1771 
1772   // If we have multiple internal linkage entities with the same name
1773   // in extern "C" regions, none of them gets that name.
1774   if (!R.second)
1775     R.first->second = 0;
1776 }
1777 
1778 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1779   llvm::Constant *Init = 0;
1780   QualType ASTTy = D->getType();
1781   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1782   bool NeedsGlobalCtor = false;
1783   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1784 
1785   const VarDecl *InitDecl;
1786   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1787 
1788   if (!InitExpr) {
1789     // This is a tentative definition; tentative definitions are
1790     // implicitly initialized with { 0 }.
1791     //
1792     // Note that tentative definitions are only emitted at the end of
1793     // a translation unit, so they should never have incomplete
1794     // type. In addition, EmitTentativeDefinition makes sure that we
1795     // never attempt to emit a tentative definition if a real one
1796     // exists. A use may still exists, however, so we still may need
1797     // to do a RAUW.
1798     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1799     Init = EmitNullConstant(D->getType());
1800   } else {
1801     initializedGlobalDecl = GlobalDecl(D);
1802     Init = EmitConstantInit(*InitDecl);
1803 
1804     if (!Init) {
1805       QualType T = InitExpr->getType();
1806       if (D->getType()->isReferenceType())
1807         T = D->getType();
1808 
1809       if (getLangOpts().CPlusPlus) {
1810         Init = EmitNullConstant(T);
1811         NeedsGlobalCtor = true;
1812       } else {
1813         ErrorUnsupported(D, "static initializer");
1814         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1815       }
1816     } else {
1817       // We don't need an initializer, so remove the entry for the delayed
1818       // initializer position (just in case this entry was delayed) if we
1819       // also don't need to register a destructor.
1820       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1821         DelayedCXXInitPosition.erase(D);
1822     }
1823   }
1824 
1825   llvm::Type* InitType = Init->getType();
1826   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1827 
1828   // Strip off a bitcast if we got one back.
1829   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1830     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1831            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
1832            // All zero index gep.
1833            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1834     Entry = CE->getOperand(0);
1835   }
1836 
1837   // Entry is now either a Function or GlobalVariable.
1838   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1839 
1840   // We have a definition after a declaration with the wrong type.
1841   // We must make a new GlobalVariable* and update everything that used OldGV
1842   // (a declaration or tentative definition) with the new GlobalVariable*
1843   // (which will be a definition).
1844   //
1845   // This happens if there is a prototype for a global (e.g.
1846   // "extern int x[];") and then a definition of a different type (e.g.
1847   // "int x[10];"). This also happens when an initializer has a different type
1848   // from the type of the global (this happens with unions).
1849   if (GV == 0 ||
1850       GV->getType()->getElementType() != InitType ||
1851       GV->getType()->getAddressSpace() !=
1852        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
1853 
1854     // Move the old entry aside so that we'll create a new one.
1855     Entry->setName(StringRef());
1856 
1857     // Make a new global with the correct type, this is now guaranteed to work.
1858     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1859 
1860     // Replace all uses of the old global with the new global
1861     llvm::Constant *NewPtrForOldDecl =
1862         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1863     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1864 
1865     // Erase the old global, since it is no longer used.
1866     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1867   }
1868 
1869   MaybeHandleStaticInExternC(D, GV);
1870 
1871   if (D->hasAttr<AnnotateAttr>())
1872     AddGlobalAnnotations(D, GV);
1873 
1874   GV->setInitializer(Init);
1875 
1876   // If it is safe to mark the global 'constant', do so now.
1877   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1878                   isTypeConstant(D->getType(), true));
1879 
1880   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1881 
1882   // Set the llvm linkage type as appropriate.
1883   llvm::GlobalValue::LinkageTypes Linkage =
1884     GetLLVMLinkageVarDefinition(D, GV->isConstant());
1885   GV->setLinkage(Linkage);
1886   if (D->hasAttr<DLLImportAttr>())
1887     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1888   else if (D->hasAttr<DLLExportAttr>())
1889     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1890 
1891   // If required by the ABI, give definitions of static data members with inline
1892   // initializers linkonce_odr linkage.
1893   if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1894       D->isStaticDataMember() && InitExpr &&
1895       !InitDecl->isThisDeclarationADefinition())
1896     GV->setLinkage(llvm::GlobalVariable::LinkOnceODRLinkage);
1897 
1898   if (Linkage == llvm::GlobalVariable::CommonLinkage)
1899     // common vars aren't constant even if declared const.
1900     GV->setConstant(false);
1901 
1902   SetCommonAttributes(D, GV);
1903 
1904   // Emit the initializer function if necessary.
1905   if (NeedsGlobalCtor || NeedsGlobalDtor)
1906     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1907 
1908   // If we are compiling with ASan, add metadata indicating dynamically
1909   // initialized globals.
1910   if (SanOpts.Address && NeedsGlobalCtor) {
1911     llvm::Module &M = getModule();
1912 
1913     llvm::NamedMDNode *DynamicInitializers =
1914         M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1915     llvm::Value *GlobalToAdd[] = { GV };
1916     llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1917     DynamicInitializers->addOperand(ThisGlobal);
1918   }
1919 
1920   // Emit global variable debug information.
1921   if (CGDebugInfo *DI = getModuleDebugInfo())
1922     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1923       DI->EmitGlobalVariable(GV, D);
1924 }
1925 
1926 llvm::GlobalValue::LinkageTypes
1927 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, bool isConstant) {
1928   GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1929   if (Linkage == GVA_Internal)
1930     return llvm::Function::InternalLinkage;
1931   else if (D->hasAttr<DLLImportAttr>())
1932     return llvm::Function::ExternalLinkage;
1933   else if (D->hasAttr<DLLExportAttr>())
1934     return llvm::Function::ExternalLinkage;
1935   else if (D->hasAttr<SelectAnyAttr>()) {
1936     // selectany symbols are externally visible, so use weak instead of
1937     // linkonce.  MSVC optimizes away references to const selectany globals, so
1938     // all definitions should be the same and ODR linkage should be used.
1939     // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
1940     return llvm::GlobalVariable::WeakODRLinkage;
1941   } else if (D->hasAttr<WeakAttr>()) {
1942     if (isConstant)
1943       return llvm::GlobalVariable::WeakODRLinkage;
1944     else
1945       return llvm::GlobalVariable::WeakAnyLinkage;
1946   } else if (Linkage == GVA_TemplateInstantiation ||
1947              Linkage == GVA_ExplicitTemplateInstantiation)
1948     return llvm::GlobalVariable::WeakODRLinkage;
1949   else if (!getLangOpts().CPlusPlus &&
1950            ((!CodeGenOpts.NoCommon && !D->hasAttr<NoCommonAttr>()) ||
1951              D->hasAttr<CommonAttr>()) &&
1952            !D->hasExternalStorage() && !D->getInit() &&
1953            !D->hasAttr<SectionAttr>() && !D->getTLSKind() &&
1954            !D->hasAttr<WeakImportAttr>()) {
1955     // Thread local vars aren't considered common linkage.
1956     return llvm::GlobalVariable::CommonLinkage;
1957   } else if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
1958              getTarget().getTriple().isMacOSX())
1959     // On Darwin, the backing variable for a C++11 thread_local variable always
1960     // has internal linkage; all accesses should just be calls to the
1961     // Itanium-specified entry point, which has the normal linkage of the
1962     // variable.
1963     return llvm::GlobalValue::InternalLinkage;
1964   return llvm::GlobalVariable::ExternalLinkage;
1965 }
1966 
1967 /// Replace the uses of a function that was declared with a non-proto type.
1968 /// We want to silently drop extra arguments from call sites
1969 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1970                                           llvm::Function *newFn) {
1971   // Fast path.
1972   if (old->use_empty()) return;
1973 
1974   llvm::Type *newRetTy = newFn->getReturnType();
1975   SmallVector<llvm::Value*, 4> newArgs;
1976 
1977   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1978          ui != ue; ) {
1979     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1980     llvm::User *user = use->getUser();
1981 
1982     // Recognize and replace uses of bitcasts.  Most calls to
1983     // unprototyped functions will use bitcasts.
1984     if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1985       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1986         replaceUsesOfNonProtoConstant(bitcast, newFn);
1987       continue;
1988     }
1989 
1990     // Recognize calls to the function.
1991     llvm::CallSite callSite(user);
1992     if (!callSite) continue;
1993     if (!callSite.isCallee(&*use)) continue;
1994 
1995     // If the return types don't match exactly, then we can't
1996     // transform this call unless it's dead.
1997     if (callSite->getType() != newRetTy && !callSite->use_empty())
1998       continue;
1999 
2000     // Get the call site's attribute list.
2001     SmallVector<llvm::AttributeSet, 8> newAttrs;
2002     llvm::AttributeSet oldAttrs = callSite.getAttributes();
2003 
2004     // Collect any return attributes from the call.
2005     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2006       newAttrs.push_back(
2007         llvm::AttributeSet::get(newFn->getContext(),
2008                                 oldAttrs.getRetAttributes()));
2009 
2010     // If the function was passed too few arguments, don't transform.
2011     unsigned newNumArgs = newFn->arg_size();
2012     if (callSite.arg_size() < newNumArgs) continue;
2013 
2014     // If extra arguments were passed, we silently drop them.
2015     // If any of the types mismatch, we don't transform.
2016     unsigned argNo = 0;
2017     bool dontTransform = false;
2018     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2019            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2020       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2021         dontTransform = true;
2022         break;
2023       }
2024 
2025       // Add any parameter attributes.
2026       if (oldAttrs.hasAttributes(argNo + 1))
2027         newAttrs.
2028           push_back(llvm::
2029                     AttributeSet::get(newFn->getContext(),
2030                                       oldAttrs.getParamAttributes(argNo + 1)));
2031     }
2032     if (dontTransform)
2033       continue;
2034 
2035     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2036       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2037                                                  oldAttrs.getFnAttributes()));
2038 
2039     // Okay, we can transform this.  Create the new call instruction and copy
2040     // over the required information.
2041     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2042 
2043     llvm::CallSite newCall;
2044     if (callSite.isCall()) {
2045       newCall = llvm::CallInst::Create(newFn, newArgs, "",
2046                                        callSite.getInstruction());
2047     } else {
2048       llvm::InvokeInst *oldInvoke =
2049         cast<llvm::InvokeInst>(callSite.getInstruction());
2050       newCall = llvm::InvokeInst::Create(newFn,
2051                                          oldInvoke->getNormalDest(),
2052                                          oldInvoke->getUnwindDest(),
2053                                          newArgs, "",
2054                                          callSite.getInstruction());
2055     }
2056     newArgs.clear(); // for the next iteration
2057 
2058     if (!newCall->getType()->isVoidTy())
2059       newCall->takeName(callSite.getInstruction());
2060     newCall.setAttributes(
2061                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2062     newCall.setCallingConv(callSite.getCallingConv());
2063 
2064     // Finally, remove the old call, replacing any uses with the new one.
2065     if (!callSite->use_empty())
2066       callSite->replaceAllUsesWith(newCall.getInstruction());
2067 
2068     // Copy debug location attached to CI.
2069     if (!callSite->getDebugLoc().isUnknown())
2070       newCall->setDebugLoc(callSite->getDebugLoc());
2071     callSite->eraseFromParent();
2072   }
2073 }
2074 
2075 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2076 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2077 /// existing call uses of the old function in the module, this adjusts them to
2078 /// call the new function directly.
2079 ///
2080 /// This is not just a cleanup: the always_inline pass requires direct calls to
2081 /// functions to be able to inline them.  If there is a bitcast in the way, it
2082 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2083 /// run at -O0.
2084 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2085                                                       llvm::Function *NewFn) {
2086   // If we're redefining a global as a function, don't transform it.
2087   if (!isa<llvm::Function>(Old)) return;
2088 
2089   replaceUsesOfNonProtoConstant(Old, NewFn);
2090 }
2091 
2092 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2093   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2094   // If we have a definition, this might be a deferred decl. If the
2095   // instantiation is explicit, make sure we emit it at the end.
2096   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2097     GetAddrOfGlobalVar(VD);
2098 
2099   EmitTopLevelDecl(VD);
2100 }
2101 
2102 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2103                                                  llvm::GlobalValue *GV) {
2104   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
2105 
2106   // Compute the function info and LLVM type.
2107   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2108   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2109 
2110   // Get or create the prototype for the function.
2111   llvm::Constant *Entry =
2112       GV ? GV
2113          : GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
2114 
2115   // Strip off a bitcast if we got one back.
2116   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2117     assert(CE->getOpcode() == llvm::Instruction::BitCast);
2118     Entry = CE->getOperand(0);
2119   }
2120 
2121   if (!cast<llvm::GlobalValue>(Entry)->isDeclaration()) {
2122     getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
2123     return;
2124   }
2125 
2126   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
2127     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
2128 
2129     // If the types mismatch then we have to rewrite the definition.
2130     assert(OldFn->isDeclaration() &&
2131            "Shouldn't replace non-declaration");
2132 
2133     // F is the Function* for the one with the wrong type, we must make a new
2134     // Function* and update everything that used F (a declaration) with the new
2135     // Function* (which will be a definition).
2136     //
2137     // This happens if there is a prototype for a function
2138     // (e.g. "int f()") and then a definition of a different type
2139     // (e.g. "int f(int x)").  Move the old function aside so that it
2140     // doesn't interfere with GetAddrOfFunction.
2141     OldFn->setName(StringRef());
2142     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2143 
2144     // This might be an implementation of a function without a
2145     // prototype, in which case, try to do special replacement of
2146     // calls which match the new prototype.  The really key thing here
2147     // is that we also potentially drop arguments from the call site
2148     // so as to make a direct call, which makes the inliner happier
2149     // and suppresses a number of optimizer warnings (!) about
2150     // dropping arguments.
2151     if (!OldFn->use_empty()) {
2152       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
2153       OldFn->removeDeadConstantUsers();
2154     }
2155 
2156     // Replace uses of F with the Function we will endow with a body.
2157     if (!Entry->use_empty()) {
2158       llvm::Constant *NewPtrForOldDecl =
2159         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
2160       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2161     }
2162 
2163     // Ok, delete the old function now, which is dead.
2164     OldFn->eraseFromParent();
2165 
2166     Entry = NewFn;
2167   }
2168 
2169   // We need to set linkage and visibility on the function before
2170   // generating code for it because various parts of IR generation
2171   // want to propagate this information down (e.g. to local static
2172   // declarations).
2173   llvm::Function *Fn = cast<llvm::Function>(Entry);
2174   setFunctionLinkage(GD, Fn);
2175 
2176   // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
2177   setGlobalVisibility(Fn, D);
2178 
2179   MaybeHandleStaticInExternC(D, Fn);
2180 
2181   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2182 
2183   SetFunctionDefinitionAttributes(D, Fn);
2184   SetLLVMFunctionAttributesForDefinition(D, Fn);
2185 
2186   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2187     AddGlobalCtor(Fn, CA->getPriority());
2188   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2189     AddGlobalDtor(Fn, DA->getPriority());
2190   if (D->hasAttr<AnnotateAttr>())
2191     AddGlobalAnnotations(D, Fn);
2192 
2193   llvm::Function *PGOInit = CodeGenPGO::emitInitialization(*this);
2194   if (PGOInit)
2195     AddGlobalCtor(PGOInit, 0);
2196 }
2197 
2198 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2199   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
2200   const AliasAttr *AA = D->getAttr<AliasAttr>();
2201   assert(AA && "Not an alias?");
2202 
2203   StringRef MangledName = getMangledName(GD);
2204 
2205   // If there is a definition in the module, then it wins over the alias.
2206   // This is dubious, but allow it to be safe.  Just ignore the alias.
2207   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2208   if (Entry && !Entry->isDeclaration())
2209     return;
2210 
2211   Aliases.push_back(GD);
2212 
2213   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2214 
2215   // Create a reference to the named value.  This ensures that it is emitted
2216   // if a deferred decl.
2217   llvm::Constant *Aliasee;
2218   if (isa<llvm::FunctionType>(DeclTy))
2219     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2220                                       /*ForVTable=*/false);
2221   else
2222     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2223                                     llvm::PointerType::getUnqual(DeclTy), 0);
2224 
2225   // Create the new alias itself, but don't set a name yet.
2226   llvm::GlobalValue *GA =
2227     new llvm::GlobalAlias(Aliasee->getType(),
2228                           llvm::Function::ExternalLinkage,
2229                           "", Aliasee, &getModule());
2230 
2231   if (Entry) {
2232     assert(Entry->isDeclaration());
2233 
2234     // If there is a declaration in the module, then we had an extern followed
2235     // by the alias, as in:
2236     //   extern int test6();
2237     //   ...
2238     //   int test6() __attribute__((alias("test7")));
2239     //
2240     // Remove it and replace uses of it with the alias.
2241     GA->takeName(Entry);
2242 
2243     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2244                                                           Entry->getType()));
2245     Entry->eraseFromParent();
2246   } else {
2247     GA->setName(MangledName);
2248   }
2249 
2250   // Set attributes which are particular to an alias; this is a
2251   // specialization of the attributes which may be set on a global
2252   // variable/function.
2253   if (D->hasAttr<DLLExportAttr>()) {
2254     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2255       // The dllexport attribute is ignored for undefined symbols.
2256       if (FD->hasBody())
2257         GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2258     } else {
2259       GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2260     }
2261   } else if (D->hasAttr<WeakAttr>() ||
2262              D->hasAttr<WeakRefAttr>() ||
2263              D->isWeakImported()) {
2264     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2265   }
2266 
2267   SetCommonAttributes(D, GA);
2268 }
2269 
2270 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2271                                             ArrayRef<llvm::Type*> Tys) {
2272   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2273                                          Tys);
2274 }
2275 
2276 static llvm::StringMapEntry<llvm::Constant*> &
2277 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2278                          const StringLiteral *Literal,
2279                          bool TargetIsLSB,
2280                          bool &IsUTF16,
2281                          unsigned &StringLength) {
2282   StringRef String = Literal->getString();
2283   unsigned NumBytes = String.size();
2284 
2285   // Check for simple case.
2286   if (!Literal->containsNonAsciiOrNull()) {
2287     StringLength = NumBytes;
2288     return Map.GetOrCreateValue(String);
2289   }
2290 
2291   // Otherwise, convert the UTF8 literals into a string of shorts.
2292   IsUTF16 = true;
2293 
2294   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2295   const UTF8 *FromPtr = (const UTF8 *)String.data();
2296   UTF16 *ToPtr = &ToBuf[0];
2297 
2298   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2299                            &ToPtr, ToPtr + NumBytes,
2300                            strictConversion);
2301 
2302   // ConvertUTF8toUTF16 returns the length in ToPtr.
2303   StringLength = ToPtr - &ToBuf[0];
2304 
2305   // Add an explicit null.
2306   *ToPtr = 0;
2307   return Map.
2308     GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2309                                (StringLength + 1) * 2));
2310 }
2311 
2312 static llvm::StringMapEntry<llvm::Constant*> &
2313 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2314                        const StringLiteral *Literal,
2315                        unsigned &StringLength) {
2316   StringRef String = Literal->getString();
2317   StringLength = String.size();
2318   return Map.GetOrCreateValue(String);
2319 }
2320 
2321 llvm::Constant *
2322 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2323   unsigned StringLength = 0;
2324   bool isUTF16 = false;
2325   llvm::StringMapEntry<llvm::Constant*> &Entry =
2326     GetConstantCFStringEntry(CFConstantStringMap, Literal,
2327                              getDataLayout().isLittleEndian(),
2328                              isUTF16, StringLength);
2329 
2330   if (llvm::Constant *C = Entry.getValue())
2331     return C;
2332 
2333   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2334   llvm::Constant *Zeros[] = { Zero, Zero };
2335   llvm::Value *V;
2336 
2337   // If we don't already have it, get __CFConstantStringClassReference.
2338   if (!CFConstantStringClassRef) {
2339     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2340     Ty = llvm::ArrayType::get(Ty, 0);
2341     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2342                                            "__CFConstantStringClassReference");
2343     // Decay array -> ptr
2344     V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2345     CFConstantStringClassRef = V;
2346   }
2347   else
2348     V = CFConstantStringClassRef;
2349 
2350   QualType CFTy = getContext().getCFConstantStringType();
2351 
2352   llvm::StructType *STy =
2353     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2354 
2355   llvm::Constant *Fields[4];
2356 
2357   // Class pointer.
2358   Fields[0] = cast<llvm::ConstantExpr>(V);
2359 
2360   // Flags.
2361   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2362   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2363     llvm::ConstantInt::get(Ty, 0x07C8);
2364 
2365   // String pointer.
2366   llvm::Constant *C = 0;
2367   if (isUTF16) {
2368     ArrayRef<uint16_t> Arr =
2369       llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2370                                      const_cast<char *>(Entry.getKey().data())),
2371                                    Entry.getKey().size() / 2);
2372     C = llvm::ConstantDataArray::get(VMContext, Arr);
2373   } else {
2374     C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2375   }
2376 
2377   // Note: -fwritable-strings doesn't make the backing store strings of
2378   // CFStrings writable. (See <rdar://problem/10657500>)
2379   llvm::GlobalVariable *GV =
2380       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2381                                llvm::GlobalValue::PrivateLinkage, C, ".str");
2382   GV->setUnnamedAddr(true);
2383   // Don't enforce the target's minimum global alignment, since the only use
2384   // of the string is via this class initializer.
2385   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2386   // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2387   // that changes the section it ends in, which surprises ld64.
2388   if (isUTF16) {
2389     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2390     GV->setAlignment(Align.getQuantity());
2391     GV->setSection("__TEXT,__ustring");
2392   } else {
2393     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2394     GV->setAlignment(Align.getQuantity());
2395     GV->setSection("__TEXT,__cstring,cstring_literals");
2396   }
2397 
2398   // String.
2399   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2400 
2401   if (isUTF16)
2402     // Cast the UTF16 string to the correct type.
2403     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2404 
2405   // String length.
2406   Ty = getTypes().ConvertType(getContext().LongTy);
2407   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2408 
2409   // The struct.
2410   C = llvm::ConstantStruct::get(STy, Fields);
2411   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2412                                 llvm::GlobalVariable::PrivateLinkage, C,
2413                                 "_unnamed_cfstring_");
2414   GV->setSection("__DATA,__cfstring");
2415   Entry.setValue(GV);
2416 
2417   return GV;
2418 }
2419 
2420 llvm::Constant *
2421 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2422   unsigned StringLength = 0;
2423   llvm::StringMapEntry<llvm::Constant*> &Entry =
2424     GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2425 
2426   if (llvm::Constant *C = Entry.getValue())
2427     return C;
2428 
2429   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2430   llvm::Constant *Zeros[] = { Zero, Zero };
2431   llvm::Value *V;
2432   // If we don't already have it, get _NSConstantStringClassReference.
2433   if (!ConstantStringClassRef) {
2434     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2435     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2436     llvm::Constant *GV;
2437     if (LangOpts.ObjCRuntime.isNonFragile()) {
2438       std::string str =
2439         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2440                             : "OBJC_CLASS_$_" + StringClass;
2441       GV = getObjCRuntime().GetClassGlobal(str);
2442       // Make sure the result is of the correct type.
2443       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2444       V = llvm::ConstantExpr::getBitCast(GV, PTy);
2445       ConstantStringClassRef = V;
2446     } else {
2447       std::string str =
2448         StringClass.empty() ? "_NSConstantStringClassReference"
2449                             : "_" + StringClass + "ClassReference";
2450       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2451       GV = CreateRuntimeVariable(PTy, str);
2452       // Decay array -> ptr
2453       V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2454       ConstantStringClassRef = V;
2455     }
2456   }
2457   else
2458     V = ConstantStringClassRef;
2459 
2460   if (!NSConstantStringType) {
2461     // Construct the type for a constant NSString.
2462     RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
2463     D->startDefinition();
2464 
2465     QualType FieldTypes[3];
2466 
2467     // const int *isa;
2468     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2469     // const char *str;
2470     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2471     // unsigned int length;
2472     FieldTypes[2] = Context.UnsignedIntTy;
2473 
2474     // Create fields
2475     for (unsigned i = 0; i < 3; ++i) {
2476       FieldDecl *Field = FieldDecl::Create(Context, D,
2477                                            SourceLocation(),
2478                                            SourceLocation(), 0,
2479                                            FieldTypes[i], /*TInfo=*/0,
2480                                            /*BitWidth=*/0,
2481                                            /*Mutable=*/false,
2482                                            ICIS_NoInit);
2483       Field->setAccess(AS_public);
2484       D->addDecl(Field);
2485     }
2486 
2487     D->completeDefinition();
2488     QualType NSTy = Context.getTagDeclType(D);
2489     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2490   }
2491 
2492   llvm::Constant *Fields[3];
2493 
2494   // Class pointer.
2495   Fields[0] = cast<llvm::ConstantExpr>(V);
2496 
2497   // String pointer.
2498   llvm::Constant *C =
2499     llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2500 
2501   llvm::GlobalValue::LinkageTypes Linkage;
2502   bool isConstant;
2503   Linkage = llvm::GlobalValue::PrivateLinkage;
2504   isConstant = !LangOpts.WritableStrings;
2505 
2506   llvm::GlobalVariable *GV =
2507   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2508                            ".str");
2509   GV->setUnnamedAddr(true);
2510   // Don't enforce the target's minimum global alignment, since the only use
2511   // of the string is via this class initializer.
2512   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2513   GV->setAlignment(Align.getQuantity());
2514   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2515 
2516   // String length.
2517   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2518   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2519 
2520   // The struct.
2521   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2522   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2523                                 llvm::GlobalVariable::PrivateLinkage, C,
2524                                 "_unnamed_nsstring_");
2525   const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2526   const char *NSStringNonFragileABISection =
2527       "__DATA,__objc_stringobj,regular,no_dead_strip";
2528   // FIXME. Fix section.
2529   GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2530                      ? NSStringNonFragileABISection
2531                      : NSStringSection);
2532   Entry.setValue(GV);
2533 
2534   return GV;
2535 }
2536 
2537 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2538   if (ObjCFastEnumerationStateType.isNull()) {
2539     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
2540     D->startDefinition();
2541 
2542     QualType FieldTypes[] = {
2543       Context.UnsignedLongTy,
2544       Context.getPointerType(Context.getObjCIdType()),
2545       Context.getPointerType(Context.UnsignedLongTy),
2546       Context.getConstantArrayType(Context.UnsignedLongTy,
2547                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2548     };
2549 
2550     for (size_t i = 0; i < 4; ++i) {
2551       FieldDecl *Field = FieldDecl::Create(Context,
2552                                            D,
2553                                            SourceLocation(),
2554                                            SourceLocation(), 0,
2555                                            FieldTypes[i], /*TInfo=*/0,
2556                                            /*BitWidth=*/0,
2557                                            /*Mutable=*/false,
2558                                            ICIS_NoInit);
2559       Field->setAccess(AS_public);
2560       D->addDecl(Field);
2561     }
2562 
2563     D->completeDefinition();
2564     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2565   }
2566 
2567   return ObjCFastEnumerationStateType;
2568 }
2569 
2570 llvm::Constant *
2571 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2572   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2573 
2574   // Don't emit it as the address of the string, emit the string data itself
2575   // as an inline array.
2576   if (E->getCharByteWidth() == 1) {
2577     SmallString<64> Str(E->getString());
2578 
2579     // Resize the string to the right size, which is indicated by its type.
2580     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2581     Str.resize(CAT->getSize().getZExtValue());
2582     return llvm::ConstantDataArray::getString(VMContext, Str, false);
2583   }
2584 
2585   llvm::ArrayType *AType =
2586     cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2587   llvm::Type *ElemTy = AType->getElementType();
2588   unsigned NumElements = AType->getNumElements();
2589 
2590   // Wide strings have either 2-byte or 4-byte elements.
2591   if (ElemTy->getPrimitiveSizeInBits() == 16) {
2592     SmallVector<uint16_t, 32> Elements;
2593     Elements.reserve(NumElements);
2594 
2595     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2596       Elements.push_back(E->getCodeUnit(i));
2597     Elements.resize(NumElements);
2598     return llvm::ConstantDataArray::get(VMContext, Elements);
2599   }
2600 
2601   assert(ElemTy->getPrimitiveSizeInBits() == 32);
2602   SmallVector<uint32_t, 32> Elements;
2603   Elements.reserve(NumElements);
2604 
2605   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2606     Elements.push_back(E->getCodeUnit(i));
2607   Elements.resize(NumElements);
2608   return llvm::ConstantDataArray::get(VMContext, Elements);
2609 }
2610 
2611 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2612 /// constant array for the given string literal.
2613 llvm::Constant *
2614 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2615   CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
2616 
2617   llvm::StringMapEntry<llvm::GlobalVariable *> *Entry = nullptr;
2618   llvm::GlobalVariable *GV = nullptr;
2619   if (!LangOpts.WritableStrings) {
2620     llvm::StringMap<llvm::GlobalVariable *> *ConstantStringMap = nullptr;
2621     switch (S->getCharByteWidth()) {
2622     case 1:
2623       ConstantStringMap = &Constant1ByteStringMap;
2624       break;
2625     case 2:
2626       ConstantStringMap = &Constant2ByteStringMap;
2627       break;
2628     case 4:
2629       ConstantStringMap = &Constant4ByteStringMap;
2630       break;
2631     default:
2632       llvm_unreachable("unhandled byte width!");
2633     }
2634     Entry = &ConstantStringMap->GetOrCreateValue(S->getBytes());
2635     GV = Entry->getValue();
2636   }
2637 
2638   if (!GV) {
2639     SmallString<256> MangledNameBuffer;
2640     StringRef GlobalVariableName;
2641     llvm::GlobalValue::LinkageTypes LT;
2642 
2643     // Mangle the string literal if the ABI allows for it.  However, we cannot
2644     // do this if  we are compiling with ASan or -fwritable-strings because they
2645     // rely on strings having normal linkage.
2646     if (!LangOpts.WritableStrings && !SanOpts.Address &&
2647         getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
2648       llvm::raw_svector_ostream Out(MangledNameBuffer);
2649       getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
2650       Out.flush();
2651 
2652       LT = llvm::GlobalValue::LinkOnceODRLinkage;
2653       GlobalVariableName = MangledNameBuffer;
2654     } else {
2655       LT = llvm::GlobalValue::PrivateLinkage;;
2656       GlobalVariableName = ".str";
2657     }
2658 
2659     // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
2660     unsigned AddrSpace = 0;
2661     if (getLangOpts().OpenCL)
2662       AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
2663 
2664     llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2665     GV = new llvm::GlobalVariable(
2666         getModule(), C->getType(), !LangOpts.WritableStrings, LT, C,
2667         GlobalVariableName, /*InsertBefore=*/nullptr,
2668         llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2669     GV->setUnnamedAddr(true);
2670     if (Entry)
2671       Entry->setValue(GV);
2672   }
2673 
2674   if (Align.getQuantity() > GV->getAlignment())
2675     GV->setAlignment(Align.getQuantity());
2676 
2677   return GV;
2678 }
2679 
2680 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2681 /// array for the given ObjCEncodeExpr node.
2682 llvm::Constant *
2683 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2684   std::string Str;
2685   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2686 
2687   return GetAddrOfConstantCString(Str);
2688 }
2689 
2690 
2691 /// GenerateWritableString -- Creates storage for a string literal.
2692 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2693                                              bool constant,
2694                                              CodeGenModule &CGM,
2695                                              const char *GlobalName,
2696                                              unsigned Alignment) {
2697   // Create Constant for this string literal. Don't add a '\0'.
2698   llvm::Constant *C =
2699       llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2700 
2701   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
2702   unsigned AddrSpace = 0;
2703   if (CGM.getLangOpts().OpenCL)
2704     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2705 
2706   // Create a global variable for this string
2707   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
2708       CGM.getModule(), C->getType(), constant,
2709       llvm::GlobalValue::PrivateLinkage, C, GlobalName, 0,
2710       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2711   GV->setAlignment(Alignment);
2712   GV->setUnnamedAddr(true);
2713   return GV;
2714 }
2715 
2716 /// GetAddrOfConstantString - Returns a pointer to a character array
2717 /// containing the literal. This contents are exactly that of the
2718 /// given string, i.e. it will not be null terminated automatically;
2719 /// see GetAddrOfConstantCString. Note that whether the result is
2720 /// actually a pointer to an LLVM constant depends on
2721 /// Feature.WriteableStrings.
2722 ///
2723 /// The result has pointer to array type.
2724 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2725                                                        const char *GlobalName,
2726                                                        unsigned Alignment) {
2727   // Get the default prefix if a name wasn't specified.
2728   if (!GlobalName)
2729     GlobalName = ".str";
2730 
2731   if (Alignment == 0)
2732     Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
2733       .getQuantity();
2734 
2735   // Don't share any string literals if strings aren't constant.
2736   if (LangOpts.WritableStrings)
2737     return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2738 
2739   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2740     Constant1ByteStringMap.GetOrCreateValue(Str);
2741 
2742   if (llvm::GlobalVariable *GV = Entry.getValue()) {
2743     if (Alignment > GV->getAlignment()) {
2744       GV->setAlignment(Alignment);
2745     }
2746     return GV;
2747   }
2748 
2749   // Create a global variable for this.
2750   llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2751                                                    Alignment);
2752   Entry.setValue(GV);
2753   return GV;
2754 }
2755 
2756 /// GetAddrOfConstantCString - Returns a pointer to a character
2757 /// array containing the literal and a terminating '\0'
2758 /// character. The result has pointer to array type.
2759 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2760                                                         const char *GlobalName,
2761                                                         unsigned Alignment) {
2762   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2763   return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2764 }
2765 
2766 llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
2767     const MaterializeTemporaryExpr *E, const Expr *Init) {
2768   assert((E->getStorageDuration() == SD_Static ||
2769           E->getStorageDuration() == SD_Thread) && "not a global temporary");
2770   const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl());
2771 
2772   // If we're not materializing a subobject of the temporary, keep the
2773   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
2774   QualType MaterializedType = Init->getType();
2775   if (Init == E->GetTemporaryExpr())
2776     MaterializedType = E->getType();
2777 
2778   llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
2779   if (Slot)
2780     return Slot;
2781 
2782   // FIXME: If an externally-visible declaration extends multiple temporaries,
2783   // we need to give each temporary the same name in every translation unit (and
2784   // we also need to make the temporaries externally-visible).
2785   SmallString<256> Name;
2786   llvm::raw_svector_ostream Out(Name);
2787   getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
2788   Out.flush();
2789 
2790   APValue *Value = 0;
2791   if (E->getStorageDuration() == SD_Static) {
2792     // We might have a cached constant initializer for this temporary. Note
2793     // that this might have a different value from the value computed by
2794     // evaluating the initializer if the surrounding constant expression
2795     // modifies the temporary.
2796     Value = getContext().getMaterializedTemporaryValue(E, false);
2797     if (Value && Value->isUninit())
2798       Value = 0;
2799   }
2800 
2801   // Try evaluating it now, it might have a constant initializer.
2802   Expr::EvalResult EvalResult;
2803   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
2804       !EvalResult.hasSideEffects())
2805     Value = &EvalResult.Val;
2806 
2807   llvm::Constant *InitialValue = 0;
2808   bool Constant = false;
2809   llvm::Type *Type;
2810   if (Value) {
2811     // The temporary has a constant initializer, use it.
2812     InitialValue = EmitConstantValue(*Value, MaterializedType, 0);
2813     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
2814     Type = InitialValue->getType();
2815   } else {
2816     // No initializer, the initialization will be provided when we
2817     // initialize the declaration which performed lifetime extension.
2818     Type = getTypes().ConvertTypeForMem(MaterializedType);
2819   }
2820 
2821   // Create a global variable for this lifetime-extended temporary.
2822   llvm::GlobalVariable *GV =
2823     new llvm::GlobalVariable(getModule(), Type, Constant,
2824                              llvm::GlobalValue::PrivateLinkage,
2825                              InitialValue, Name.c_str());
2826   GV->setAlignment(
2827       getContext().getTypeAlignInChars(MaterializedType).getQuantity());
2828   if (VD->getTLSKind())
2829     setTLSMode(GV, *VD);
2830   Slot = GV;
2831   return GV;
2832 }
2833 
2834 /// EmitObjCPropertyImplementations - Emit information for synthesized
2835 /// properties for an implementation.
2836 void CodeGenModule::EmitObjCPropertyImplementations(const
2837                                                     ObjCImplementationDecl *D) {
2838   for (const auto *PID : D->property_impls()) {
2839     // Dynamic is just for type-checking.
2840     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2841       ObjCPropertyDecl *PD = PID->getPropertyDecl();
2842 
2843       // Determine which methods need to be implemented, some may have
2844       // been overridden. Note that ::isPropertyAccessor is not the method
2845       // we want, that just indicates if the decl came from a
2846       // property. What we want to know is if the method is defined in
2847       // this implementation.
2848       if (!D->getInstanceMethod(PD->getGetterName()))
2849         CodeGenFunction(*this).GenerateObjCGetter(
2850                                  const_cast<ObjCImplementationDecl *>(D), PID);
2851       if (!PD->isReadOnly() &&
2852           !D->getInstanceMethod(PD->getSetterName()))
2853         CodeGenFunction(*this).GenerateObjCSetter(
2854                                  const_cast<ObjCImplementationDecl *>(D), PID);
2855     }
2856   }
2857 }
2858 
2859 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2860   const ObjCInterfaceDecl *iface = impl->getClassInterface();
2861   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2862        ivar; ivar = ivar->getNextIvar())
2863     if (ivar->getType().isDestructedType())
2864       return true;
2865 
2866   return false;
2867 }
2868 
2869 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2870 /// for an implementation.
2871 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2872   // We might need a .cxx_destruct even if we don't have any ivar initializers.
2873   if (needsDestructMethod(D)) {
2874     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2875     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2876     ObjCMethodDecl *DTORMethod =
2877       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2878                              cxxSelector, getContext().VoidTy, 0, D,
2879                              /*isInstance=*/true, /*isVariadic=*/false,
2880                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
2881                              /*isDefined=*/false, ObjCMethodDecl::Required);
2882     D->addInstanceMethod(DTORMethod);
2883     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2884     D->setHasDestructors(true);
2885   }
2886 
2887   // If the implementation doesn't have any ivar initializers, we don't need
2888   // a .cxx_construct.
2889   if (D->getNumIvarInitializers() == 0)
2890     return;
2891 
2892   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2893   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2894   // The constructor returns 'self'.
2895   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2896                                                 D->getLocation(),
2897                                                 D->getLocation(),
2898                                                 cxxSelector,
2899                                                 getContext().getObjCIdType(), 0,
2900                                                 D, /*isInstance=*/true,
2901                                                 /*isVariadic=*/false,
2902                                                 /*isPropertyAccessor=*/true,
2903                                                 /*isImplicitlyDeclared=*/true,
2904                                                 /*isDefined=*/false,
2905                                                 ObjCMethodDecl::Required);
2906   D->addInstanceMethod(CTORMethod);
2907   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2908   D->setHasNonZeroConstructors(true);
2909 }
2910 
2911 /// EmitNamespace - Emit all declarations in a namespace.
2912 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2913   for (auto *I : ND->decls()) {
2914     if (const auto *VD = dyn_cast<VarDecl>(I))
2915       if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2916           VD->getTemplateSpecializationKind() != TSK_Undeclared)
2917         continue;
2918     EmitTopLevelDecl(I);
2919   }
2920 }
2921 
2922 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2923 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2924   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2925       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2926     ErrorUnsupported(LSD, "linkage spec");
2927     return;
2928   }
2929 
2930   for (auto *I : LSD->decls()) {
2931     // Meta-data for ObjC class includes references to implemented methods.
2932     // Generate class's method definitions first.
2933     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
2934       for (auto *M : OID->methods())
2935         EmitTopLevelDecl(M);
2936     }
2937     EmitTopLevelDecl(I);
2938   }
2939 }
2940 
2941 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2942 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2943   // Ignore dependent declarations.
2944   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2945     return;
2946 
2947   switch (D->getKind()) {
2948   case Decl::CXXConversion:
2949   case Decl::CXXMethod:
2950   case Decl::Function:
2951     // Skip function templates
2952     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2953         cast<FunctionDecl>(D)->isLateTemplateParsed())
2954       return;
2955 
2956     EmitGlobal(cast<FunctionDecl>(D));
2957     break;
2958 
2959   case Decl::Var:
2960     // Skip variable templates
2961     if (cast<VarDecl>(D)->getDescribedVarTemplate())
2962       return;
2963   case Decl::VarTemplateSpecialization:
2964     EmitGlobal(cast<VarDecl>(D));
2965     break;
2966 
2967   // Indirect fields from global anonymous structs and unions can be
2968   // ignored; only the actual variable requires IR gen support.
2969   case Decl::IndirectField:
2970     break;
2971 
2972   // C++ Decls
2973   case Decl::Namespace:
2974     EmitNamespace(cast<NamespaceDecl>(D));
2975     break;
2976     // No code generation needed.
2977   case Decl::UsingShadow:
2978   case Decl::ClassTemplate:
2979   case Decl::VarTemplate:
2980   case Decl::VarTemplatePartialSpecialization:
2981   case Decl::FunctionTemplate:
2982   case Decl::TypeAliasTemplate:
2983   case Decl::Block:
2984   case Decl::Empty:
2985     break;
2986   case Decl::Using:          // using X; [C++]
2987     if (CGDebugInfo *DI = getModuleDebugInfo())
2988         DI->EmitUsingDecl(cast<UsingDecl>(*D));
2989     return;
2990   case Decl::NamespaceAlias:
2991     if (CGDebugInfo *DI = getModuleDebugInfo())
2992         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
2993     return;
2994   case Decl::UsingDirective: // using namespace X; [C++]
2995     if (CGDebugInfo *DI = getModuleDebugInfo())
2996       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
2997     return;
2998   case Decl::CXXConstructor:
2999     // Skip function templates
3000     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3001         cast<FunctionDecl>(D)->isLateTemplateParsed())
3002       return;
3003 
3004     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3005     break;
3006   case Decl::CXXDestructor:
3007     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3008       return;
3009     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3010     break;
3011 
3012   case Decl::StaticAssert:
3013     // Nothing to do.
3014     break;
3015 
3016   // Objective-C Decls
3017 
3018   // Forward declarations, no (immediate) code generation.
3019   case Decl::ObjCInterface:
3020   case Decl::ObjCCategory:
3021     break;
3022 
3023   case Decl::ObjCProtocol: {
3024     ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
3025     if (Proto->isThisDeclarationADefinition())
3026       ObjCRuntime->GenerateProtocol(Proto);
3027     break;
3028   }
3029 
3030   case Decl::ObjCCategoryImpl:
3031     // Categories have properties but don't support synthesize so we
3032     // can ignore them here.
3033     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3034     break;
3035 
3036   case Decl::ObjCImplementation: {
3037     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
3038     EmitObjCPropertyImplementations(OMD);
3039     EmitObjCIvarInitializations(OMD);
3040     ObjCRuntime->GenerateClass(OMD);
3041     // Emit global variable debug information.
3042     if (CGDebugInfo *DI = getModuleDebugInfo())
3043       if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3044         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3045             OMD->getClassInterface()), OMD->getLocation());
3046     break;
3047   }
3048   case Decl::ObjCMethod: {
3049     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
3050     // If this is not a prototype, emit the body.
3051     if (OMD->getBody())
3052       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3053     break;
3054   }
3055   case Decl::ObjCCompatibleAlias:
3056     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3057     break;
3058 
3059   case Decl::LinkageSpec:
3060     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3061     break;
3062 
3063   case Decl::FileScopeAsm: {
3064     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
3065     StringRef AsmString = AD->getAsmString()->getString();
3066 
3067     const std::string &S = getModule().getModuleInlineAsm();
3068     if (S.empty())
3069       getModule().setModuleInlineAsm(AsmString);
3070     else if (S.end()[-1] == '\n')
3071       getModule().setModuleInlineAsm(S + AsmString.str());
3072     else
3073       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
3074     break;
3075   }
3076 
3077   case Decl::Import: {
3078     ImportDecl *Import = cast<ImportDecl>(D);
3079 
3080     // Ignore import declarations that come from imported modules.
3081     if (clang::Module *Owner = Import->getOwningModule()) {
3082       if (getLangOpts().CurrentModule.empty() ||
3083           Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3084         break;
3085     }
3086 
3087     ImportedModules.insert(Import->getImportedModule());
3088     break;
3089   }
3090 
3091   case Decl::ClassTemplateSpecialization: {
3092     const ClassTemplateSpecializationDecl *Spec =
3093         cast<ClassTemplateSpecializationDecl>(D);
3094     if (DebugInfo &&
3095         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition)
3096       DebugInfo->completeTemplateDefinition(*Spec);
3097   }
3098 
3099   default:
3100     // Make sure we handled everything we should, every other kind is a
3101     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3102     // function. Need to recode Decl::Kind to do that easily.
3103     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3104   }
3105 }
3106 
3107 /// Turns the given pointer into a constant.
3108 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3109                                           const void *Ptr) {
3110   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3111   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3112   return llvm::ConstantInt::get(i64, PtrInt);
3113 }
3114 
3115 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3116                                    llvm::NamedMDNode *&GlobalMetadata,
3117                                    GlobalDecl D,
3118                                    llvm::GlobalValue *Addr) {
3119   if (!GlobalMetadata)
3120     GlobalMetadata =
3121       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3122 
3123   // TODO: should we report variant information for ctors/dtors?
3124   llvm::Value *Ops[] = {
3125     Addr,
3126     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
3127   };
3128   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3129 }
3130 
3131 /// For each function which is declared within an extern "C" region and marked
3132 /// as 'used', but has internal linkage, create an alias from the unmangled
3133 /// name to the mangled name if possible. People expect to be able to refer
3134 /// to such functions with an unmangled name from inline assembly within the
3135 /// same translation unit.
3136 void CodeGenModule::EmitStaticExternCAliases() {
3137   for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3138                                   E = StaticExternCValues.end();
3139        I != E; ++I) {
3140     IdentifierInfo *Name = I->first;
3141     llvm::GlobalValue *Val = I->second;
3142     if (Val && !getModule().getNamedValue(Name->getName()))
3143       addUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
3144                                           Name->getName(), Val, &getModule()));
3145   }
3146 }
3147 
3148 /// Emits metadata nodes associating all the global values in the
3149 /// current module with the Decls they came from.  This is useful for
3150 /// projects using IR gen as a subroutine.
3151 ///
3152 /// Since there's currently no way to associate an MDNode directly
3153 /// with an llvm::GlobalValue, we create a global named metadata
3154 /// with the name 'clang.global.decl.ptrs'.
3155 void CodeGenModule::EmitDeclMetadata() {
3156   llvm::NamedMDNode *GlobalMetadata = 0;
3157 
3158   // StaticLocalDeclMap
3159   for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
3160          I = MangledDeclNames.begin(), E = MangledDeclNames.end();
3161        I != E; ++I) {
3162     llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
3163     EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
3164   }
3165 }
3166 
3167 /// Emits metadata nodes for all the local variables in the current
3168 /// function.
3169 void CodeGenFunction::EmitDeclMetadata() {
3170   if (LocalDeclMap.empty()) return;
3171 
3172   llvm::LLVMContext &Context = getLLVMContext();
3173 
3174   // Find the unique metadata ID for this name.
3175   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3176 
3177   llvm::NamedMDNode *GlobalMetadata = 0;
3178 
3179   for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3180          I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3181     const Decl *D = I->first;
3182     llvm::Value *Addr = I->second;
3183 
3184     if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3185       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3186       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
3187     } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3188       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3189       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3190     }
3191   }
3192 }
3193 
3194 void CodeGenModule::EmitVersionIdentMetadata() {
3195   llvm::NamedMDNode *IdentMetadata =
3196     TheModule.getOrInsertNamedMetadata("llvm.ident");
3197   std::string Version = getClangFullVersion();
3198   llvm::LLVMContext &Ctx = TheModule.getContext();
3199 
3200   llvm::Value *IdentNode[] = {
3201     llvm::MDString::get(Ctx, Version)
3202   };
3203   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3204 }
3205 
3206 void CodeGenModule::EmitCoverageFile() {
3207   if (!getCodeGenOpts().CoverageFile.empty()) {
3208     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3209       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3210       llvm::LLVMContext &Ctx = TheModule.getContext();
3211       llvm::MDString *CoverageFile =
3212           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3213       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3214         llvm::MDNode *CU = CUNode->getOperand(i);
3215         llvm::Value *node[] = { CoverageFile, CU };
3216         llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3217         GCov->addOperand(N);
3218       }
3219     }
3220   }
3221 }
3222 
3223 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3224                                                      QualType GuidType) {
3225   // Sema has checked that all uuid strings are of the form
3226   // "12345678-1234-1234-1234-1234567890ab".
3227   assert(Uuid.size() == 36);
3228   for (unsigned i = 0; i < 36; ++i) {
3229     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3230     else                                         assert(isHexDigit(Uuid[i]));
3231   }
3232 
3233   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3234 
3235   llvm::Constant *Field3[8];
3236   for (unsigned Idx = 0; Idx < 8; ++Idx)
3237     Field3[Idx] = llvm::ConstantInt::get(
3238         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3239 
3240   llvm::Constant *Fields[4] = {
3241     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
3242     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
3243     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3244     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3245   };
3246 
3247   return llvm::ConstantStruct::getAnon(Fields);
3248 }
3249