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