1 //===--- CodeGenModule.h - Per-Module state for LLVM CodeGen ----*- C++ -*-===//
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 is the internal per-translation-unit state used for llvm translation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef CLANG_CODEGEN_CODEGENMODULE_H
15 #define CLANG_CODEGEN_CODEGENMODULE_H
16 
17 #include "CGVTables.h"
18 #include "CodeGenTypes.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/GlobalDecl.h"
23 #include "clang/AST/Mangle.h"
24 #include "clang/Basic/ABI.h"
25 #include "clang/Basic/LangOptions.h"
26 #include "clang/Basic/Module.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/Transforms/Utils/SpecialCaseList.h"
35 
36 namespace llvm {
37 class Module;
38 class Constant;
39 class ConstantInt;
40 class Function;
41 class GlobalValue;
42 class DataLayout;
43 class FunctionType;
44 class LLVMContext;
45 class IndexedInstrProfReader;
46 }
47 
48 namespace clang {
49 class TargetCodeGenInfo;
50 class ASTContext;
51 class AtomicType;
52 class FunctionDecl;
53 class IdentifierInfo;
54 class ObjCMethodDecl;
55 class ObjCImplementationDecl;
56 class ObjCCategoryImplDecl;
57 class ObjCProtocolDecl;
58 class ObjCEncodeExpr;
59 class BlockExpr;
60 class CharUnits;
61 class Decl;
62 class Expr;
63 class Stmt;
64 class InitListExpr;
65 class StringLiteral;
66 class NamedDecl;
67 class ValueDecl;
68 class VarDecl;
69 class LangOptions;
70 class CodeGenOptions;
71 class DiagnosticsEngine;
72 class AnnotateAttr;
73 class CXXDestructorDecl;
74 class Module;
75 
76 namespace CodeGen {
77 
78 class CallArgList;
79 class CodeGenFunction;
80 class CodeGenTBAA;
81 class CGCXXABI;
82 class CGDebugInfo;
83 class CGObjCRuntime;
84 class CGOpenCLRuntime;
85 class CGOpenMPRuntime;
86 class CGCUDARuntime;
87 class BlockFieldFlags;
88 class FunctionArgList;
89 
90 struct OrderGlobalInits {
91   unsigned int priority;
92   unsigned int lex_order;
93   OrderGlobalInits(unsigned int p, unsigned int l)
94       : priority(p), lex_order(l) {}
95 
96   bool operator==(const OrderGlobalInits &RHS) const {
97     return priority == RHS.priority && lex_order == RHS.lex_order;
98   }
99 
100   bool operator<(const OrderGlobalInits &RHS) const {
101     return std::tie(priority, lex_order) <
102            std::tie(RHS.priority, RHS.lex_order);
103   }
104 };
105 
106 struct CodeGenTypeCache {
107   /// void
108   llvm::Type *VoidTy;
109 
110   /// i8, i16, i32, and i64
111   llvm::IntegerType *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
112   /// float, double
113   llvm::Type *FloatTy, *DoubleTy;
114 
115   /// int
116   llvm::IntegerType *IntTy;
117 
118   /// intptr_t, size_t, and ptrdiff_t, which we assume are the same size.
119   union {
120     llvm::IntegerType *IntPtrTy;
121     llvm::IntegerType *SizeTy;
122     llvm::IntegerType *PtrDiffTy;
123   };
124 
125   /// void* in address space 0
126   union {
127     llvm::PointerType *VoidPtrTy;
128     llvm::PointerType *Int8PtrTy;
129   };
130 
131   /// void** in address space 0
132   union {
133     llvm::PointerType *VoidPtrPtrTy;
134     llvm::PointerType *Int8PtrPtrTy;
135   };
136 
137   /// The width of a pointer into the generic address space.
138   unsigned char PointerWidthInBits;
139 
140   /// The size and alignment of a pointer into the generic address
141   /// space.
142   union {
143     unsigned char PointerAlignInBytes;
144     unsigned char PointerSizeInBytes;
145     unsigned char SizeSizeInBytes; // sizeof(size_t)
146   };
147 
148   llvm::CallingConv::ID RuntimeCC;
149   llvm::CallingConv::ID getRuntimeCC() const { return RuntimeCC; }
150 };
151 
152 struct RREntrypoints {
153   RREntrypoints() { memset(this, 0, sizeof(*this)); }
154   /// void objc_autoreleasePoolPop(void*);
155   llvm::Constant *objc_autoreleasePoolPop;
156 
157   /// void *objc_autoreleasePoolPush(void);
158   llvm::Constant *objc_autoreleasePoolPush;
159 };
160 
161 struct ARCEntrypoints {
162   ARCEntrypoints() { memset(this, 0, sizeof(*this)); }
163 
164   /// id objc_autorelease(id);
165   llvm::Constant *objc_autorelease;
166 
167   /// id objc_autoreleaseReturnValue(id);
168   llvm::Constant *objc_autoreleaseReturnValue;
169 
170   /// void objc_copyWeak(id *dest, id *src);
171   llvm::Constant *objc_copyWeak;
172 
173   /// void objc_destroyWeak(id*);
174   llvm::Constant *objc_destroyWeak;
175 
176   /// id objc_initWeak(id*, id);
177   llvm::Constant *objc_initWeak;
178 
179   /// id objc_loadWeak(id*);
180   llvm::Constant *objc_loadWeak;
181 
182   /// id objc_loadWeakRetained(id*);
183   llvm::Constant *objc_loadWeakRetained;
184 
185   /// void objc_moveWeak(id *dest, id *src);
186   llvm::Constant *objc_moveWeak;
187 
188   /// id objc_retain(id);
189   llvm::Constant *objc_retain;
190 
191   /// id objc_retainAutorelease(id);
192   llvm::Constant *objc_retainAutorelease;
193 
194   /// id objc_retainAutoreleaseReturnValue(id);
195   llvm::Constant *objc_retainAutoreleaseReturnValue;
196 
197   /// id objc_retainAutoreleasedReturnValue(id);
198   llvm::Constant *objc_retainAutoreleasedReturnValue;
199 
200   /// id objc_retainBlock(id);
201   llvm::Constant *objc_retainBlock;
202 
203   /// void objc_release(id);
204   llvm::Constant *objc_release;
205 
206   /// id objc_storeStrong(id*, id);
207   llvm::Constant *objc_storeStrong;
208 
209   /// id objc_storeWeak(id*, id);
210   llvm::Constant *objc_storeWeak;
211 
212   /// A void(void) inline asm to use to mark that the return value of
213   /// a call will be immediately retain.
214   llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
215 
216   /// void clang.arc.use(...);
217   llvm::Constant *clang_arc_use;
218 };
219 
220 /// This class records statistics on instrumentation based profiling.
221 struct InstrProfStats {
222   InstrProfStats() : Visited(0), Missing(0), Mismatched(0) {}
223   bool isOutOfDate() { return Missing || Mismatched; }
224   uint32_t Visited;
225   uint32_t Missing;
226   uint32_t Mismatched;
227 };
228 
229 /// This class organizes the cross-function state that is used while generating
230 /// LLVM code.
231 class CodeGenModule : public CodeGenTypeCache {
232   CodeGenModule(const CodeGenModule &) LLVM_DELETED_FUNCTION;
233   void operator=(const CodeGenModule &) LLVM_DELETED_FUNCTION;
234 
235   struct Structor {
236     Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
237     Structor(int Priority, llvm::Constant *Initializer,
238              llvm::Constant *AssociatedData)
239         : Priority(Priority), Initializer(Initializer),
240           AssociatedData(AssociatedData) {}
241     int Priority;
242     llvm::Constant *Initializer;
243     llvm::Constant *AssociatedData;
244   };
245 
246   typedef std::vector<Structor> CtorList;
247 
248   ASTContext &Context;
249   const LangOptions &LangOpts;
250   const CodeGenOptions &CodeGenOpts;
251   llvm::Module &TheModule;
252   DiagnosticsEngine &Diags;
253   const llvm::DataLayout &TheDataLayout;
254   const TargetInfo &Target;
255   std::unique_ptr<CGCXXABI> ABI;
256   llvm::LLVMContext &VMContext;
257 
258   CodeGenTBAA *TBAA;
259 
260   mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
261 
262   // This should not be moved earlier, since its initialization depends on some
263   // of the previous reference members being already initialized and also checks
264   // if TheTargetCodeGenInfo is NULL
265   CodeGenTypes Types;
266 
267   /// Holds information about C++ vtables.
268   CodeGenVTables VTables;
269 
270   CGObjCRuntime* ObjCRuntime;
271   CGOpenCLRuntime* OpenCLRuntime;
272   CGOpenMPRuntime* OpenMPRuntime;
273   CGCUDARuntime* CUDARuntime;
274   CGDebugInfo* DebugInfo;
275   ARCEntrypoints *ARCData;
276   llvm::MDNode *NoObjCARCExceptionsMetadata;
277   RREntrypoints *RRData;
278   std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
279   InstrProfStats PGOStats;
280 
281   // A set of references that have only been seen via a weakref so far. This is
282   // used to remove the weak of the reference if we ever see a direct reference
283   // or a definition.
284   llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
285 
286   /// This contains all the decls which have definitions but/ which are deferred
287   /// for emission and therefore should only be output if they are actually
288   /// used. If a decl is in this, then it is known to have not been referenced
289   /// yet.
290   std::map<StringRef, GlobalDecl> DeferredDecls;
291 
292   /// This is a list of deferred decls which we have seen that *are* actually
293   /// referenced. These get code generated when the module is done.
294   struct DeferredGlobal {
295     DeferredGlobal(llvm::GlobalValue *GV, GlobalDecl GD) : GV(GV), GD(GD) {}
296     llvm::AssertingVH<llvm::GlobalValue> GV;
297     GlobalDecl GD;
298   };
299   std::vector<DeferredGlobal> DeferredDeclsToEmit;
300   void addDeferredDeclToEmit(llvm::GlobalValue *GV, GlobalDecl GD) {
301     DeferredDeclsToEmit.push_back(DeferredGlobal(GV, GD));
302   }
303 
304   /// List of alias we have emitted. Used to make sure that what they point to
305   /// is defined once we get to the end of the of the translation unit.
306   std::vector<GlobalDecl> Aliases;
307 
308   typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
309   ReplacementsTy Replacements;
310 
311   /// A queue of (optional) vtables to consider emitting.
312   std::vector<const CXXRecordDecl*> DeferredVTables;
313 
314   /// List of global values which are required to be present in the object file;
315   /// bitcast to i8*. This is used for forcing visibility of symbols which may
316   /// otherwise be optimized out.
317   std::vector<llvm::WeakVH> LLVMUsed;
318   std::vector<llvm::WeakVH> LLVMCompilerUsed;
319 
320   /// Store the list of global constructors and their respective priorities to
321   /// be emitted when the translation unit is complete.
322   CtorList GlobalCtors;
323 
324   /// Store the list of global destructors and their respective priorities to be
325   /// emitted when the translation unit is complete.
326   CtorList GlobalDtors;
327 
328   /// A map of canonical GlobalDecls to their mangled names.
329   llvm::DenseMap<GlobalDecl, StringRef> MangledDeclNames;
330   llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
331 
332   /// Global annotations.
333   std::vector<llvm::Constant*> Annotations;
334 
335   /// Map used to get unique annotation strings.
336   llvm::StringMap<llvm::Constant*> AnnotationStrings;
337 
338   llvm::StringMap<llvm::Constant*> CFConstantStringMap;
339 
340   llvm::StringMap<llvm::GlobalVariable *> Constant1ByteStringMap;
341   llvm::StringMap<llvm::GlobalVariable *> Constant2ByteStringMap;
342   llvm::StringMap<llvm::GlobalVariable *> Constant4ByteStringMap;
343   llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
344   llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
345   llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
346 
347   llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
348   llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
349 
350   /// Map used to get unique type descriptor constants for sanitizers.
351   llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
352 
353   /// Map used to track internal linkage functions declared within
354   /// extern "C" regions.
355   typedef llvm::MapVector<IdentifierInfo *,
356                           llvm::GlobalValue *> StaticExternCMap;
357   StaticExternCMap StaticExternCValues;
358 
359   /// \brief thread_local variables defined or used in this TU.
360   std::vector<std::pair<const VarDecl *, llvm::GlobalVariable *> >
361     CXXThreadLocals;
362 
363   /// \brief thread_local variables with initializers that need to run
364   /// before any thread_local variable in this TU is odr-used.
365   std::vector<llvm::Constant*> CXXThreadLocalInits;
366 
367   /// Global variables with initializers that need to run before main.
368   std::vector<llvm::Constant*> CXXGlobalInits;
369 
370   /// When a C++ decl with an initializer is deferred, null is
371   /// appended to CXXGlobalInits, and the index of that null is placed
372   /// here so that the initializer will be performed in the correct
373   /// order.
374   llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
375 
376   typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
377 
378   struct GlobalInitPriorityCmp {
379     bool operator()(const GlobalInitData &LHS,
380                     const GlobalInitData &RHS) const {
381       return LHS.first.priority < RHS.first.priority;
382     }
383   };
384 
385   /// Global variables with initializers whose order of initialization is set by
386   /// init_priority attribute.
387   SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
388 
389   /// Global destructor functions and arguments that need to run on termination.
390   std::vector<std::pair<llvm::WeakVH,llvm::Constant*> > CXXGlobalDtors;
391 
392   /// \brief The complete set of modules that has been imported.
393   llvm::SetVector<clang::Module *> ImportedModules;
394 
395   /// \brief A vector of metadata strings.
396   SmallVector<llvm::Value *, 16> LinkerOptionsMetadata;
397 
398   /// @name Cache for Objective-C runtime types
399   /// @{
400 
401   /// Cached reference to the class for constant strings. This value has type
402   /// int * but is actually an Obj-C class pointer.
403   llvm::WeakVH CFConstantStringClassRef;
404 
405   /// Cached reference to the class for constant strings. This value has type
406   /// int * but is actually an Obj-C class pointer.
407   llvm::WeakVH ConstantStringClassRef;
408 
409   /// \brief The LLVM type corresponding to NSConstantString.
410   llvm::StructType *NSConstantStringType;
411 
412   /// \brief The type used to describe the state of a fast enumeration in
413   /// Objective-C's for..in loop.
414   QualType ObjCFastEnumerationStateType;
415 
416   /// @}
417 
418   /// Lazily create the Objective-C runtime
419   void createObjCRuntime();
420 
421   void createOpenCLRuntime();
422   void createOpenMPRuntime();
423   void createCUDARuntime();
424 
425   bool isTriviallyRecursive(const FunctionDecl *F);
426   bool shouldEmitFunction(GlobalDecl GD);
427 
428   /// @name Cache for Blocks Runtime Globals
429   /// @{
430 
431   llvm::Constant *NSConcreteGlobalBlock;
432   llvm::Constant *NSConcreteStackBlock;
433 
434   llvm::Constant *BlockObjectAssign;
435   llvm::Constant *BlockObjectDispose;
436 
437   llvm::Type *BlockDescriptorType;
438   llvm::Type *GenericBlockLiteralType;
439 
440   struct {
441     int GlobalUniqueCount;
442   } Block;
443 
444   /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
445   llvm::Constant *LifetimeStartFn;
446 
447   /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
448   llvm::Constant *LifetimeEndFn;
449 
450   GlobalDecl initializedGlobalDecl;
451 
452   std::unique_ptr<llvm::SpecialCaseList> SanitizerBlacklist;
453 
454   const SanitizerOptions &SanOpts;
455 
456   /// @}
457 public:
458   CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
459                 llvm::Module &M, const llvm::DataLayout &TD,
460                 DiagnosticsEngine &Diags);
461 
462   ~CodeGenModule();
463 
464   void clear();
465 
466   /// Finalize LLVM code generation.
467   void Release();
468 
469   /// Return a reference to the configured Objective-C runtime.
470   CGObjCRuntime &getObjCRuntime() {
471     if (!ObjCRuntime) createObjCRuntime();
472     return *ObjCRuntime;
473   }
474 
475   /// Return true iff an Objective-C runtime has been configured.
476   bool hasObjCRuntime() { return !!ObjCRuntime; }
477 
478   /// Return a reference to the configured OpenCL runtime.
479   CGOpenCLRuntime &getOpenCLRuntime() {
480     assert(OpenCLRuntime != nullptr);
481     return *OpenCLRuntime;
482   }
483 
484   /// Return a reference to the configured OpenMP runtime.
485   CGOpenMPRuntime &getOpenMPRuntime() {
486     assert(OpenMPRuntime != nullptr);
487     return *OpenMPRuntime;
488   }
489 
490   /// Return a reference to the configured CUDA runtime.
491   CGCUDARuntime &getCUDARuntime() {
492     assert(CUDARuntime != nullptr);
493     return *CUDARuntime;
494   }
495 
496   ARCEntrypoints &getARCEntrypoints() const {
497     assert(getLangOpts().ObjCAutoRefCount && ARCData != nullptr);
498     return *ARCData;
499   }
500 
501   RREntrypoints &getRREntrypoints() const {
502     assert(RRData != nullptr);
503     return *RRData;
504   }
505 
506   InstrProfStats &getPGOStats() { return PGOStats; }
507   llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
508 
509   llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
510     return StaticLocalDeclMap[D];
511   }
512   void setStaticLocalDeclAddress(const VarDecl *D,
513                                  llvm::Constant *C) {
514     StaticLocalDeclMap[D] = C;
515   }
516 
517   llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
518     return StaticLocalDeclGuardMap[D];
519   }
520   void setStaticLocalDeclGuardAddress(const VarDecl *D,
521                                       llvm::GlobalVariable *C) {
522     StaticLocalDeclGuardMap[D] = C;
523   }
524 
525   bool lookupRepresentativeDecl(StringRef MangledName,
526                                 GlobalDecl &Result) const;
527 
528   llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
529     return AtomicSetterHelperFnMap[Ty];
530   }
531   void setAtomicSetterHelperFnMap(QualType Ty,
532                             llvm::Constant *Fn) {
533     AtomicSetterHelperFnMap[Ty] = Fn;
534   }
535 
536   llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
537     return AtomicGetterHelperFnMap[Ty];
538   }
539   void setAtomicGetterHelperFnMap(QualType Ty,
540                             llvm::Constant *Fn) {
541     AtomicGetterHelperFnMap[Ty] = Fn;
542   }
543 
544   llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
545     return TypeDescriptorMap[Ty];
546   }
547   void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
548     TypeDescriptorMap[Ty] = C;
549   }
550 
551   CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
552 
553   llvm::MDNode *getNoObjCARCExceptionsMetadata() {
554     if (!NoObjCARCExceptionsMetadata)
555       NoObjCARCExceptionsMetadata =
556         llvm::MDNode::get(getLLVMContext(),
557                           SmallVector<llvm::Value*,1>());
558     return NoObjCARCExceptionsMetadata;
559   }
560 
561   ASTContext &getContext() const { return Context; }
562   const LangOptions &getLangOpts() const { return LangOpts; }
563   const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
564   llvm::Module &getModule() const { return TheModule; }
565   DiagnosticsEngine &getDiags() const { return Diags; }
566   const llvm::DataLayout &getDataLayout() const { return TheDataLayout; }
567   const TargetInfo &getTarget() const { return Target; }
568   CGCXXABI &getCXXABI() const { return *ABI; }
569   llvm::LLVMContext &getLLVMContext() { return VMContext; }
570 
571   bool shouldUseTBAA() const { return TBAA != nullptr; }
572 
573   const TargetCodeGenInfo &getTargetCodeGenInfo();
574 
575   CodeGenTypes &getTypes() { return Types; }
576 
577   CodeGenVTables &getVTables() { return VTables; }
578 
579   ItaniumVTableContext &getItaniumVTableContext() {
580     return VTables.getItaniumVTableContext();
581   }
582 
583   MicrosoftVTableContext &getMicrosoftVTableContext() {
584     return VTables.getMicrosoftVTableContext();
585   }
586 
587   llvm::MDNode *getTBAAInfo(QualType QTy);
588   llvm::MDNode *getTBAAInfoForVTablePtr();
589   llvm::MDNode *getTBAAStructInfo(QualType QTy);
590   /// Return the MDNode in the type DAG for the given struct type.
591   llvm::MDNode *getTBAAStructTypeInfo(QualType QTy);
592   /// Return the path-aware tag for given base type, access node and offset.
593   llvm::MDNode *getTBAAStructTagInfo(QualType BaseTy, llvm::MDNode *AccessN,
594                                      uint64_t O);
595 
596   bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
597 
598   bool isPaddedAtomicType(QualType type);
599   bool isPaddedAtomicType(const AtomicType *type);
600 
601   /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
602   /// is the same as the type. For struct-path aware TBAA, the tag
603   /// is different from the type: base type, access type and offset.
604   /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
605   void DecorateInstruction(llvm::Instruction *Inst,
606                            llvm::MDNode *TBAAInfo,
607                            bool ConvertTypeToTag = true);
608 
609   /// Emit the given number of characters as a value of type size_t.
610   llvm::ConstantInt *getSize(CharUnits numChars);
611 
612   /// Set the visibility for the given LLVM GlobalValue.
613   void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
614 
615   /// Set the TLS mode for the given LLVM GlobalVariable for the thread-local
616   /// variable declaration D.
617   void setTLSMode(llvm::GlobalVariable *GV, const VarDecl &D) const;
618 
619   static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
620     switch (V) {
621     case DefaultVisibility:   return llvm::GlobalValue::DefaultVisibility;
622     case HiddenVisibility:    return llvm::GlobalValue::HiddenVisibility;
623     case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
624     }
625     llvm_unreachable("unknown visibility!");
626   }
627 
628   llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
629     if (isa<CXXConstructorDecl>(GD.getDecl()))
630       return GetAddrOfCXXConstructor(cast<CXXConstructorDecl>(GD.getDecl()),
631                                      GD.getCtorType());
632     else if (isa<CXXDestructorDecl>(GD.getDecl()))
633       return GetAddrOfCXXDestructor(cast<CXXDestructorDecl>(GD.getDecl()),
634                                      GD.getDtorType());
635     else if (isa<FunctionDecl>(GD.getDecl()))
636       return GetAddrOfFunction(GD);
637     else
638       return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
639   }
640 
641   /// Will return a global variable of the given type. If a variable with a
642   /// different type already exists then a new  variable with the right type
643   /// will be created and all uses of the old variable will be replaced with a
644   /// bitcast to the new variable.
645   llvm::GlobalVariable *
646   CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
647                                     llvm::GlobalValue::LinkageTypes Linkage);
648 
649   /// Return the address space of the underlying global variable for D, as
650   /// determined by its declaration. Normally this is the same as the address
651   /// space of D's type, but in CUDA, address spaces are associated with
652   /// declarations, not types.
653   unsigned GetGlobalVarAddressSpace(const VarDecl *D, unsigned AddrSpace);
654 
655   /// Return the llvm::Constant for the address of the given global variable.
656   /// If Ty is non-null and if the global doesn't exist, then it will be greated
657   /// with the specified type instead of whatever the normal requested type
658   /// would be.
659   llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
660                                      llvm::Type *Ty = nullptr);
661 
662   /// Return the address of the given function. If Ty is non-null, then this
663   /// function will use the specified type if it has to create it.
664   llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = 0,
665                                     bool ForVTable = false,
666                                     bool DontDefer = false);
667 
668   /// Get the address of the RTTI descriptor for the given type.
669   llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
670 
671   /// Get the address of a uuid descriptor .
672   llvm::Constant *GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
673 
674   /// Get the address of the thunk for the given global decl.
675   llvm::Constant *GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk);
676 
677   /// Get a reference to the target of VD.
678   llvm::Constant *GetWeakRefReference(const ValueDecl *VD);
679 
680   /// Returns the offset from a derived class to  a class. Returns null if the
681   /// offset is 0.
682   llvm::Constant *
683   GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
684                                CastExpr::path_const_iterator PathBegin,
685                                CastExpr::path_const_iterator PathEnd);
686 
687   /// A pair of helper functions for a __block variable.
688   class ByrefHelpers : public llvm::FoldingSetNode {
689   public:
690     llvm::Constant *CopyHelper;
691     llvm::Constant *DisposeHelper;
692 
693     /// The alignment of the field.  This is important because
694     /// different offsets to the field within the byref struct need to
695     /// have different helper functions.
696     CharUnits Alignment;
697 
698     ByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
699     virtual ~ByrefHelpers();
700 
701     void Profile(llvm::FoldingSetNodeID &id) const {
702       id.AddInteger(Alignment.getQuantity());
703       profileImpl(id);
704     }
705     virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
706 
707     virtual bool needsCopy() const { return true; }
708     virtual void emitCopy(CodeGenFunction &CGF,
709                           llvm::Value *dest, llvm::Value *src) = 0;
710 
711     virtual bool needsDispose() const { return true; }
712     virtual void emitDispose(CodeGenFunction &CGF, llvm::Value *field) = 0;
713   };
714 
715   llvm::FoldingSet<ByrefHelpers> ByrefHelpersCache;
716 
717   /// Fetches the global unique block count.
718   int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
719 
720   /// Fetches the type of a generic block descriptor.
721   llvm::Type *getBlockDescriptorType();
722 
723   /// The type of a generic block literal.
724   llvm::Type *getGenericBlockLiteralType();
725 
726   /// \brief Gets or a creats a Microsoft TypeDescriptor.
727   llvm::Constant *getMSTypeDescriptor(QualType Ty);
728   /// \brief Gets or a creats a Microsoft CompleteObjectLocator.
729   llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
730                                                    const VPtrInfo *Info);
731 
732   /// Gets the address of a block which requires no captures.
733   llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
734 
735   /// Return a pointer to a constant CFString object for the given string.
736   llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
737 
738   /// Return a pointer to a constant NSString object for the given string. Or a
739   /// user defined String object as defined via
740   /// -fconstant-string-class=class_name option.
741   llvm::Constant *GetAddrOfConstantString(const StringLiteral *Literal);
742 
743   /// Return a constant array for the given string.
744   llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
745 
746   /// Return a pointer to a constant array for the given string literal.
747   llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *S);
748 
749   /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
750   llvm::Constant *GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
751 
752   /// Returns a pointer to a character array containing the literal and a
753   /// terminating '\0' character. The result has pointer to array type.
754   ///
755   /// \param GlobalName If provided, the name to use for the global (if one is
756   /// created).
757   llvm::Constant *GetAddrOfConstantCString(const std::string &str,
758                                            const char *GlobalName = nullptr,
759                                            unsigned Alignment = 0);
760 
761   /// Returns a pointer to a constant global variable for the given file-scope
762   /// compound literal expression.
763   llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
764 
765   /// \brief Returns a pointer to a global variable representing a temporary
766   /// with static or thread storage duration.
767   llvm::Constant *GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
768                                            const Expr *Inner);
769 
770   /// \brief Retrieve the record type that describes the state of an
771   /// Objective-C fast enumeration loop (for..in).
772   QualType getObjCFastEnumerationStateType();
773 
774   /// Return the address of the constructor of the given type.
775   llvm::GlobalValue *
776   GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor, CXXCtorType ctorType,
777                           const CGFunctionInfo *fnInfo = nullptr,
778                           bool DontDefer = false);
779 
780   /// Return the address of the constructor of the given type.
781   llvm::GlobalValue *
782   GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
783                          CXXDtorType dtorType,
784                          const CGFunctionInfo *fnInfo = nullptr,
785                          llvm::FunctionType *fnType = nullptr,
786                          bool DontDefer = false);
787 
788   /// Given a builtin id for a function like "__builtin_fabsf", return a
789   /// Function* for "fabsf".
790   llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
791                                      unsigned BuiltinID);
792 
793   llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
794 
795   /// Emit code for a single top level declaration.
796   void EmitTopLevelDecl(Decl *D);
797 
798   /// Tell the consumer that this variable has been instantiated.
799   void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
800 
801   /// \brief If the declaration has internal linkage but is inside an
802   /// extern "C" linkage specification, prepare to emit an alias for it
803   /// to the expected name.
804   template<typename SomeDecl>
805   void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
806 
807   /// Add a global to a list to be added to the llvm.used metadata.
808   void addUsedGlobal(llvm::GlobalValue *GV);
809 
810   /// Add a global to a list to be added to the llvm.compiler.used metadata.
811   void addCompilerUsedGlobal(llvm::GlobalValue *GV);
812 
813   /// Add a destructor and object to add to the C++ global destructor function.
814   void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
815     CXXGlobalDtors.push_back(std::make_pair(DtorFn, Object));
816   }
817 
818   /// Create a new runtime function with the specified type and name.
819   llvm::Constant *CreateRuntimeFunction(llvm::FunctionType *Ty,
820                                         StringRef Name,
821                                         llvm::AttributeSet ExtraAttrs =
822                                           llvm::AttributeSet());
823   /// Create a new runtime global variable with the specified type and name.
824   llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
825                                         StringRef Name);
826 
827   ///@name Custom Blocks Runtime Interfaces
828   ///@{
829 
830   llvm::Constant *getNSConcreteGlobalBlock();
831   llvm::Constant *getNSConcreteStackBlock();
832   llvm::Constant *getBlockObjectAssign();
833   llvm::Constant *getBlockObjectDispose();
834 
835   ///@}
836 
837   llvm::Constant *getLLVMLifetimeStartFn();
838   llvm::Constant *getLLVMLifetimeEndFn();
839 
840   // Make sure that this type is translated.
841   void UpdateCompletedType(const TagDecl *TD);
842 
843   llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
844 
845   /// Try to emit the initializer for the given declaration as a constant;
846   /// returns 0 if the expression cannot be emitted as a constant.
847   llvm::Constant *EmitConstantInit(const VarDecl &D,
848                                    CodeGenFunction *CGF = nullptr);
849 
850   /// Try to emit the given expression as a constant; returns 0 if the
851   /// expression cannot be emitted as a constant.
852   llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
853                                    CodeGenFunction *CGF = nullptr);
854 
855   /// Emit the given constant value as a constant, in the type's scalar
856   /// representation.
857   llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestType,
858                                     CodeGenFunction *CGF = nullptr);
859 
860   /// Emit the given constant value as a constant, in the type's memory
861   /// representation.
862   llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
863                                              QualType DestType,
864                                              CodeGenFunction *CGF = nullptr);
865 
866   /// Return the result of value-initializing the given type, i.e. a null
867   /// expression of the given type.  This is usually, but not always, an LLVM
868   /// null constant.
869   llvm::Constant *EmitNullConstant(QualType T);
870 
871   /// Return a null constant appropriate for zero-initializing a base class with
872   /// the given type. This is usually, but not always, an LLVM null constant.
873   llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
874 
875   /// Emit a general error that something can't be done.
876   void Error(SourceLocation loc, StringRef error);
877 
878   /// Print out an error that codegen doesn't support the specified stmt yet.
879   void ErrorUnsupported(const Stmt *S, const char *Type);
880 
881   /// Print out an error that codegen doesn't support the specified decl yet.
882   void ErrorUnsupported(const Decl *D, const char *Type);
883 
884   /// Set the attributes on the LLVM function for the given decl and function
885   /// info. This applies attributes necessary for handling the ABI as well as
886   /// user specified attributes like section.
887   void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F,
888                                      const CGFunctionInfo &FI);
889 
890   /// Set the LLVM function attributes (sext, zext, etc).
891   void SetLLVMFunctionAttributes(const Decl *D,
892                                  const CGFunctionInfo &Info,
893                                  llvm::Function *F);
894 
895   /// Set the LLVM function attributes which only apply to a function
896   /// definintion.
897   void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
898 
899   /// Return true iff the given type uses 'sret' when used as a return type.
900   bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
901 
902   /// Return true iff the given type uses an argument slot when 'sret' is used
903   /// as a return type.
904   bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
905 
906   /// Return true iff the given type uses 'fpret' when used as a return type.
907   bool ReturnTypeUsesFPRet(QualType ResultType);
908 
909   /// Return true iff the given type uses 'fp2ret' when used as a return type.
910   bool ReturnTypeUsesFP2Ret(QualType ResultType);
911 
912   /// Get the LLVM attributes and calling convention to use for a particular
913   /// function type.
914   ///
915   /// \param Info - The function type information.
916   /// \param TargetDecl - The decl these attributes are being constructed
917   /// for. If supplied the attributes applied to this decl may contribute to the
918   /// function attributes and calling convention.
919   /// \param PAL [out] - On return, the attribute list to use.
920   /// \param CallingConv [out] - On return, the LLVM calling convention to use.
921   void ConstructAttributeList(const CGFunctionInfo &Info,
922                               const Decl *TargetDecl,
923                               AttributeListType &PAL,
924                               unsigned &CallingConv,
925                               bool AttrOnCallSite);
926 
927   StringRef getMangledName(GlobalDecl GD);
928   StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
929 
930   void EmitTentativeDefinition(const VarDecl *D);
931 
932   void EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired);
933 
934   /// Emit the RTTI descriptors for the builtin types.
935   void EmitFundamentalRTTIDescriptors();
936 
937   /// \brief Appends Opts to the "Linker Options" metadata value.
938   void AppendLinkerOptions(StringRef Opts);
939 
940   /// \brief Appends a detect mismatch command to the linker options.
941   void AddDetectMismatch(StringRef Name, StringRef Value);
942 
943   /// \brief Appends a dependent lib to the "Linker Options" metadata value.
944   void AddDependentLib(StringRef Lib);
945 
946   llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
947 
948   void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
949     F->setLinkage(getFunctionLinkage(GD));
950   }
951 
952   /// \brief Returns the appropriate linkage for the TypeInfo struct for a type.
953   llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(QualType Ty);
954 
955   /// Return the appropriate linkage for the vtable, VTT, and type information
956   /// of the given class.
957   llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
958 
959   /// Return the store size, in character units, of the given LLVM type.
960   CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
961 
962   /// Returns LLVM linkage for a declarator.
963   llvm::GlobalValue::LinkageTypes
964   getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
965                               bool IsConstantVariable);
966 
967   /// Returns LLVM linkage for a declarator.
968   llvm::GlobalValue::LinkageTypes
969   getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
970 
971   /// Emit all the global annotations.
972   void EmitGlobalAnnotations();
973 
974   /// Emit an annotation string.
975   llvm::Constant *EmitAnnotationString(StringRef Str);
976 
977   /// Emit the annotation's translation unit.
978   llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
979 
980   /// Emit the annotation line number.
981   llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
982 
983   /// Generate the llvm::ConstantStruct which contains the annotation
984   /// information for a given GlobalValue. The annotation struct is
985   /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
986   /// GlobalValue being annotated. The second field is the constant string
987   /// created from the AnnotateAttr's annotation. The third field is a constant
988   /// string containing the name of the translation unit. The fourth field is
989   /// the line number in the file of the annotated value declaration.
990   llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
991                                    const AnnotateAttr *AA,
992                                    SourceLocation L);
993 
994   /// Add global annotations that are set on D, for the global GV. Those
995   /// annotations are emitted during finalization of the LLVM code.
996   void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
997 
998   const llvm::SpecialCaseList &getSanitizerBlacklist() const {
999     return *SanitizerBlacklist;
1000   }
1001 
1002   const SanitizerOptions &getSanOpts() const { return SanOpts; }
1003 
1004   void addDeferredVTable(const CXXRecordDecl *RD) {
1005     DeferredVTables.push_back(RD);
1006   }
1007 
1008   /// Emit code for a singal global function or var decl. Forward declarations
1009   /// are emitted lazily.
1010   void EmitGlobal(GlobalDecl D);
1011 
1012 private:
1013   llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1014 
1015   llvm::Constant *
1016   GetOrCreateLLVMFunction(StringRef MangledName, llvm::Type *Ty, GlobalDecl D,
1017                           bool ForVTable, bool DontDefer = false,
1018                           llvm::AttributeSet ExtraAttrs = llvm::AttributeSet());
1019 
1020   llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1021                                         llvm::PointerType *PTy,
1022                                         const VarDecl *D);
1023 
1024   llvm::StringMapEntry<llvm::GlobalVariable *> *
1025   getConstantStringMapEntry(StringRef Str, int CharByteWidth);
1026 
1027   /// Set attributes which are common to any form of a global definition (alias,
1028   /// Objective-C method, function, global variable).
1029   ///
1030   /// NOTE: This should only be called for definitions.
1031   void SetCommonAttributes(const Decl *D, llvm::GlobalValue *GV);
1032 
1033   void setNonAliasAttributes(const Decl *D, llvm::GlobalObject *GO);
1034 
1035   /// Set attributes for a global definition.
1036   void setFunctionDefinitionAttributes(const FunctionDecl *D,
1037                                        llvm::Function *F);
1038 
1039   /// Set function attributes for a function declaration.
1040   void SetFunctionAttributes(GlobalDecl GD,
1041                              llvm::Function *F,
1042                              bool IsIncompleteFunction);
1043 
1044   void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1045 
1046   void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1047   void EmitGlobalVarDefinition(const VarDecl *D);
1048   void EmitAliasDefinition(GlobalDecl GD);
1049   void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1050   void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1051 
1052   // C++ related functions.
1053 
1054   bool TryEmitDefinitionAsAlias(GlobalDecl Alias, GlobalDecl Target,
1055                                 bool InEveryTU);
1056   bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1057 
1058   void EmitNamespace(const NamespaceDecl *D);
1059   void EmitLinkageSpec(const LinkageSpecDecl *D);
1060   void CompleteDIClassType(const CXXMethodDecl* D);
1061 
1062   /// Emit a single constructor with the given type from a C++ constructor Decl.
1063   void EmitCXXConstructor(const CXXConstructorDecl *D, CXXCtorType Type);
1064 
1065   /// Emit a single destructor with the given type from a C++ destructor Decl.
1066   void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
1067 
1068   /// \brief Emit the function that initializes C++ thread_local variables.
1069   void EmitCXXThreadLocalInitFunc();
1070 
1071   /// Emit the function that initializes C++ globals.
1072   void EmitCXXGlobalInitFunc();
1073 
1074   /// Emit the function that destroys C++ globals.
1075   void EmitCXXGlobalDtorFunc();
1076 
1077   /// Emit the function that initializes the specified global (if PerformInit is
1078   /// true) and registers its destructor.
1079   void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1080                                     llvm::GlobalVariable *Addr,
1081                                     bool PerformInit);
1082 
1083   // FIXME: Hardcoding priority here is gross.
1084   void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1085                      llvm::Constant *AssociatedData = 0);
1086   void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1087 
1088   /// Generates a global array of functions and priorities using the given list
1089   /// and name. This array will have appending linkage and is suitable for use
1090   /// as a LLVM constructor or destructor array.
1091   void EmitCtorList(const CtorList &Fns, const char *GlobalName);
1092 
1093   /// Emit the RTTI descriptors for the given type.
1094   void EmitFundamentalRTTIDescriptor(QualType Type);
1095 
1096   /// Emit any needed decls for which code generation was deferred.
1097   void EmitDeferred();
1098 
1099   /// Call replaceAllUsesWith on all pairs in Replacements.
1100   void applyReplacements();
1101 
1102   void checkAliases();
1103 
1104   /// Emit any vtables which we deferred and still have a use for.
1105   void EmitDeferredVTables();
1106 
1107   /// Emit the llvm.used and llvm.compiler.used metadata.
1108   void emitLLVMUsed();
1109 
1110   /// \brief Emit the link options introduced by imported modules.
1111   void EmitModuleLinkOptions();
1112 
1113   /// \brief Emit aliases for internal-linkage declarations inside "C" language
1114   /// linkage specifications, giving them the "expected" name where possible.
1115   void EmitStaticExternCAliases();
1116 
1117   void EmitDeclMetadata();
1118 
1119   /// \brief Emit the Clang version as llvm.ident metadata.
1120   void EmitVersionIdentMetadata();
1121 
1122   /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1123   /// .gcda files in a way that persists in .bc files.
1124   void EmitCoverageFile();
1125 
1126   /// Emits the initializer for a uuidof string.
1127   llvm::Constant *EmitUuidofInitializer(StringRef uuidstr, QualType IIDType);
1128 
1129   /// Determine if the given decl can be emitted lazily; this is only relevant
1130   /// for definitions. The given decl must be either a function or var decl.
1131   bool MayDeferGeneration(const ValueDecl *D);
1132 
1133   /// Check whether we can use a "simpler", more core exceptions personality
1134   /// function.
1135   void SimplifyPersonality();
1136 };
1137 }  // end namespace CodeGen
1138 }  // end namespace clang
1139 
1140 #endif
1141