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