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