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