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