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