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