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