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