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