]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.h
Merge OpenSSL 1.1.1d.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CodeGenModule.h
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 LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
15 #define LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H
16
17 #include "CGVTables.h"
18 #include "CodeGenTypeCache.h"
19 #include "CodeGenTypes.h"
20 #include "SanitizerMetadata.h"
21 #include "clang/AST/Attr.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclOpenMP.h"
25 #include "clang/AST/GlobalDecl.h"
26 #include "clang/AST/Mangle.h"
27 #include "clang/Basic/ABI.h"
28 #include "clang/Basic/LangOptions.h"
29 #include "clang/Basic/Module.h"
30 #include "clang/Basic/SanitizerBlacklist.h"
31 #include "clang/Basic/XRayLists.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SetVector.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/StringMap.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/ValueHandle.h"
38 #include "llvm/Transforms/Utils/SanitizerStats.h"
39
40 namespace llvm {
41 class Module;
42 class Constant;
43 class ConstantInt;
44 class Function;
45 class GlobalValue;
46 class DataLayout;
47 class FunctionType;
48 class LLVMContext;
49 class IndexedInstrProfReader;
50 }
51
52 namespace clang {
53 class ASTContext;
54 class AtomicType;
55 class FunctionDecl;
56 class IdentifierInfo;
57 class ObjCMethodDecl;
58 class ObjCImplementationDecl;
59 class ObjCCategoryImplDecl;
60 class ObjCProtocolDecl;
61 class ObjCEncodeExpr;
62 class BlockExpr;
63 class CharUnits;
64 class Decl;
65 class Expr;
66 class Stmt;
67 class InitListExpr;
68 class StringLiteral;
69 class NamedDecl;
70 class ValueDecl;
71 class VarDecl;
72 class LangOptions;
73 class CodeGenOptions;
74 class HeaderSearchOptions;
75 class PreprocessorOptions;
76 class DiagnosticsEngine;
77 class AnnotateAttr;
78 class CXXDestructorDecl;
79 class Module;
80 class CoverageSourceInfo;
81
82 namespace CodeGen {
83
84 class CallArgList;
85 class CodeGenFunction;
86 class CodeGenTBAA;
87 class CGCXXABI;
88 class CGDebugInfo;
89 class CGObjCRuntime;
90 class CGOpenCLRuntime;
91 class CGOpenMPRuntime;
92 class CGCUDARuntime;
93 class BlockFieldFlags;
94 class FunctionArgList;
95 class CoverageMappingModuleGen;
96 class TargetCodeGenInfo;
97
98 enum ForDefinition_t : bool {
99   NotForDefinition = false,
100   ForDefinition = true
101 };
102
103 struct OrderGlobalInits {
104   unsigned int priority;
105   unsigned int lex_order;
106   OrderGlobalInits(unsigned int p, unsigned int l)
107       : priority(p), lex_order(l) {}
108
109   bool operator==(const OrderGlobalInits &RHS) const {
110     return priority == RHS.priority && lex_order == RHS.lex_order;
111   }
112
113   bool operator<(const OrderGlobalInits &RHS) const {
114     return std::tie(priority, lex_order) <
115            std::tie(RHS.priority, RHS.lex_order);
116   }
117 };
118
119 struct ObjCEntrypoints {
120   ObjCEntrypoints() { memset(this, 0, sizeof(*this)); }
121
122   /// void objc_alloc(id);
123   llvm::Constant *objc_alloc;
124
125   /// void objc_allocWithZone(id);
126   llvm::Constant *objc_allocWithZone;
127
128   /// void objc_autoreleasePoolPop(void*);
129   llvm::Constant *objc_autoreleasePoolPop;
130
131   /// void objc_autoreleasePoolPop(void*);
132   /// Note this method is used when we are using exception handling
133   llvm::Constant *objc_autoreleasePoolPopInvoke;
134
135   /// void *objc_autoreleasePoolPush(void);
136   llvm::Constant *objc_autoreleasePoolPush;
137
138   /// id objc_autorelease(id);
139   llvm::Constant *objc_autorelease;
140
141   /// id objc_autorelease(id);
142   /// Note this is the runtime method not the intrinsic.
143   llvm::Constant *objc_autoreleaseRuntimeFunction;
144
145   /// id objc_autoreleaseReturnValue(id);
146   llvm::Constant *objc_autoreleaseReturnValue;
147
148   /// void objc_copyWeak(id *dest, id *src);
149   llvm::Constant *objc_copyWeak;
150
151   /// void objc_destroyWeak(id*);
152   llvm::Constant *objc_destroyWeak;
153
154   /// id objc_initWeak(id*, id);
155   llvm::Constant *objc_initWeak;
156
157   /// id objc_loadWeak(id*);
158   llvm::Constant *objc_loadWeak;
159
160   /// id objc_loadWeakRetained(id*);
161   llvm::Constant *objc_loadWeakRetained;
162
163   /// void objc_moveWeak(id *dest, id *src);
164   llvm::Constant *objc_moveWeak;
165
166   /// id objc_retain(id);
167   llvm::Constant *objc_retain;
168
169   /// id objc_retain(id);
170   /// Note this is the runtime method not the intrinsic.
171   llvm::Constant *objc_retainRuntimeFunction;
172
173   /// id objc_retainAutorelease(id);
174   llvm::Constant *objc_retainAutorelease;
175
176   /// id objc_retainAutoreleaseReturnValue(id);
177   llvm::Constant *objc_retainAutoreleaseReturnValue;
178
179   /// id objc_retainAutoreleasedReturnValue(id);
180   llvm::Constant *objc_retainAutoreleasedReturnValue;
181
182   /// id objc_retainBlock(id);
183   llvm::Constant *objc_retainBlock;
184
185   /// void objc_release(id);
186   llvm::Constant *objc_release;
187
188   /// void objc_release(id);
189   /// Note this is the runtime method not the intrinsic.
190   llvm::Constant *objc_releaseRuntimeFunction;
191
192   /// void objc_storeStrong(id*, id);
193   llvm::Constant *objc_storeStrong;
194
195   /// id objc_storeWeak(id*, id);
196   llvm::Constant *objc_storeWeak;
197
198   /// id objc_unsafeClaimAutoreleasedReturnValue(id);
199   llvm::Constant *objc_unsafeClaimAutoreleasedReturnValue;
200
201   /// A void(void) inline asm to use to mark that the return value of
202   /// a call will be immediately retain.
203   llvm::InlineAsm *retainAutoreleasedReturnValueMarker;
204
205   /// void clang.arc.use(...);
206   llvm::Constant *clang_arc_use;
207 };
208
209 /// This class records statistics on instrumentation based profiling.
210 class InstrProfStats {
211   uint32_t VisitedInMainFile;
212   uint32_t MissingInMainFile;
213   uint32_t Visited;
214   uint32_t Missing;
215   uint32_t Mismatched;
216
217 public:
218   InstrProfStats()
219       : VisitedInMainFile(0), MissingInMainFile(0), Visited(0), Missing(0),
220         Mismatched(0) {}
221   /// Record that we've visited a function and whether or not that function was
222   /// in the main source file.
223   void addVisited(bool MainFile) {
224     if (MainFile)
225       ++VisitedInMainFile;
226     ++Visited;
227   }
228   /// Record that a function we've visited has no profile data.
229   void addMissing(bool MainFile) {
230     if (MainFile)
231       ++MissingInMainFile;
232     ++Missing;
233   }
234   /// Record that a function we've visited has mismatched profile data.
235   void addMismatched(bool MainFile) { ++Mismatched; }
236   /// Whether or not the stats we've gathered indicate any potential problems.
237   bool hasDiagnostics() { return Missing || Mismatched; }
238   /// Report potential problems we've found to \c Diags.
239   void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile);
240 };
241
242 /// A pair of helper functions for a __block variable.
243 class BlockByrefHelpers : public llvm::FoldingSetNode {
244   // MSVC requires this type to be complete in order to process this
245   // header.
246 public:
247   llvm::Constant *CopyHelper;
248   llvm::Constant *DisposeHelper;
249
250   /// The alignment of the field.  This is important because
251   /// different offsets to the field within the byref struct need to
252   /// have different helper functions.
253   CharUnits Alignment;
254
255   BlockByrefHelpers(CharUnits alignment) : Alignment(alignment) {}
256   BlockByrefHelpers(const BlockByrefHelpers &) = default;
257   virtual ~BlockByrefHelpers();
258
259   void Profile(llvm::FoldingSetNodeID &id) const {
260     id.AddInteger(Alignment.getQuantity());
261     profileImpl(id);
262   }
263   virtual void profileImpl(llvm::FoldingSetNodeID &id) const = 0;
264
265   virtual bool needsCopy() const { return true; }
266   virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src) = 0;
267
268   virtual bool needsDispose() const { return true; }
269   virtual void emitDispose(CodeGenFunction &CGF, Address field) = 0;
270 };
271
272 /// This class organizes the cross-function state that is used while generating
273 /// LLVM code.
274 class CodeGenModule : public CodeGenTypeCache {
275   CodeGenModule(const CodeGenModule &) = delete;
276   void operator=(const CodeGenModule &) = delete;
277
278 public:
279   struct Structor {
280     Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
281     Structor(int Priority, llvm::Constant *Initializer,
282              llvm::Constant *AssociatedData)
283         : Priority(Priority), Initializer(Initializer),
284           AssociatedData(AssociatedData) {}
285     int Priority;
286     llvm::Constant *Initializer;
287     llvm::Constant *AssociatedData;
288   };
289
290   typedef std::vector<Structor> CtorList;
291
292 private:
293   ASTContext &Context;
294   const LangOptions &LangOpts;
295   const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
296   const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
297   const CodeGenOptions &CodeGenOpts;
298   llvm::Module &TheModule;
299   DiagnosticsEngine &Diags;
300   const TargetInfo &Target;
301   std::unique_ptr<CGCXXABI> ABI;
302   llvm::LLVMContext &VMContext;
303
304   std::unique_ptr<CodeGenTBAA> TBAA;
305
306   mutable std::unique_ptr<TargetCodeGenInfo> TheTargetCodeGenInfo;
307
308   // This should not be moved earlier, since its initialization depends on some
309   // of the previous reference members being already initialized and also checks
310   // if TheTargetCodeGenInfo is NULL
311   CodeGenTypes Types;
312
313   /// Holds information about C++ vtables.
314   CodeGenVTables VTables;
315
316   std::unique_ptr<CGObjCRuntime> ObjCRuntime;
317   std::unique_ptr<CGOpenCLRuntime> OpenCLRuntime;
318   std::unique_ptr<CGOpenMPRuntime> OpenMPRuntime;
319   std::unique_ptr<CGCUDARuntime> CUDARuntime;
320   std::unique_ptr<CGDebugInfo> DebugInfo;
321   std::unique_ptr<ObjCEntrypoints> ObjCData;
322   llvm::MDNode *NoObjCARCExceptionsMetadata = nullptr;
323   std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader;
324   InstrProfStats PGOStats;
325   std::unique_ptr<llvm::SanitizerStatReport> SanStats;
326
327   // A set of references that have only been seen via a weakref so far. This is
328   // used to remove the weak of the reference if we ever see a direct reference
329   // or a definition.
330   llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
331
332   /// This contains all the decls which have definitions but/ which are deferred
333   /// for emission and therefore should only be output if they are actually
334   /// used. If a decl is in this, then it is known to have not been referenced
335   /// yet.
336   std::map<StringRef, GlobalDecl> DeferredDecls;
337
338   /// This is a list of deferred decls which we have seen that *are* actually
339   /// referenced. These get code generated when the module is done.
340   std::vector<GlobalDecl> DeferredDeclsToEmit;
341   void addDeferredDeclToEmit(GlobalDecl GD) {
342     DeferredDeclsToEmit.emplace_back(GD);
343   }
344
345   /// List of alias we have emitted. Used to make sure that what they point to
346   /// is defined once we get to the end of the of the translation unit.
347   std::vector<GlobalDecl> Aliases;
348
349   /// List of multiversion functions that have to be emitted.  Used to make sure
350   /// we properly emit the iFunc.
351   std::vector<GlobalDecl> MultiVersionFuncs;
352
353   typedef llvm::StringMap<llvm::TrackingVH<llvm::Constant> > ReplacementsTy;
354   ReplacementsTy Replacements;
355
356   /// List of global values to be replaced with something else. Used when we
357   /// want to replace a GlobalValue but can't identify it by its mangled name
358   /// anymore (because the name is already taken).
359   llvm::SmallVector<std::pair<llvm::GlobalValue *, llvm::Constant *>, 8>
360     GlobalValReplacements;
361
362   /// Set of global decls for which we already diagnosed mangled name conflict.
363   /// Required to not issue a warning (on a mangling conflict) multiple times
364   /// for the same decl.
365   llvm::DenseSet<GlobalDecl> DiagnosedConflictingDefinitions;
366
367   /// A queue of (optional) vtables to consider emitting.
368   std::vector<const CXXRecordDecl*> DeferredVTables;
369
370   /// A queue of (optional) vtables that may be emitted opportunistically.
371   std::vector<const CXXRecordDecl *> OpportunisticVTables;
372
373   /// List of global values which are required to be present in the object file;
374   /// bitcast to i8*. This is used for forcing visibility of symbols which may
375   /// otherwise be optimized out.
376   std::vector<llvm::WeakTrackingVH> LLVMUsed;
377   std::vector<llvm::WeakTrackingVH> LLVMCompilerUsed;
378
379   /// Store the list of global constructors and their respective priorities to
380   /// be emitted when the translation unit is complete.
381   CtorList GlobalCtors;
382
383   /// Store the list of global destructors and their respective priorities to be
384   /// emitted when the translation unit is complete.
385   CtorList GlobalDtors;
386
387   /// An ordered map of canonical GlobalDecls to their mangled names.
388   llvm::MapVector<GlobalDecl, StringRef> MangledDeclNames;
389   llvm::StringMap<GlobalDecl, llvm::BumpPtrAllocator> Manglings;
390
391   // An ordered map of canonical GlobalDecls paired with the cpu-index for
392   // cpu-specific name manglings.
393   llvm::MapVector<std::pair<GlobalDecl, unsigned>, StringRef>
394       CPUSpecificMangledDeclNames;
395   llvm::StringMap<std::pair<GlobalDecl, unsigned>, llvm::BumpPtrAllocator>
396       CPUSpecificManglings;
397
398   /// Global annotations.
399   std::vector<llvm::Constant*> Annotations;
400
401   /// Map used to get unique annotation strings.
402   llvm::StringMap<llvm::Constant*> AnnotationStrings;
403
404   llvm::StringMap<llvm::GlobalVariable *> CFConstantStringMap;
405
406   llvm::DenseMap<llvm::Constant *, llvm::GlobalVariable *> ConstantStringMap;
407   llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
408   llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardMap;
409   llvm::DenseMap<const Expr*, llvm::Constant *> MaterializedGlobalTemporaryMap;
410
411   llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
412   llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
413
414   /// Map used to get unique type descriptor constants for sanitizers.
415   llvm::DenseMap<QualType, llvm::Constant *> TypeDescriptorMap;
416
417   /// Map used to track internal linkage functions declared within
418   /// extern "C" regions.
419   typedef llvm::MapVector<IdentifierInfo *,
420                           llvm::GlobalValue *> StaticExternCMap;
421   StaticExternCMap StaticExternCValues;
422
423   /// thread_local variables defined or used in this TU.
424   std::vector<const VarDecl *> CXXThreadLocals;
425
426   /// thread_local variables with initializers that need to run
427   /// before any thread_local variable in this TU is odr-used.
428   std::vector<llvm::Function *> CXXThreadLocalInits;
429   std::vector<const VarDecl *> CXXThreadLocalInitVars;
430
431   /// Global variables with initializers that need to run before main.
432   std::vector<llvm::Function *> CXXGlobalInits;
433
434   /// When a C++ decl with an initializer is deferred, null is
435   /// appended to CXXGlobalInits, and the index of that null is placed
436   /// here so that the initializer will be performed in the correct
437   /// order. Once the decl is emitted, the index is replaced with ~0U to ensure
438   /// that we don't re-emit the initializer.
439   llvm::DenseMap<const Decl*, unsigned> DelayedCXXInitPosition;
440
441   typedef std::pair<OrderGlobalInits, llvm::Function*> GlobalInitData;
442
443   struct GlobalInitPriorityCmp {
444     bool operator()(const GlobalInitData &LHS,
445                     const GlobalInitData &RHS) const {
446       return LHS.first.priority < RHS.first.priority;
447     }
448   };
449
450   /// Global variables with initializers whose order of initialization is set by
451   /// init_priority attribute.
452   SmallVector<GlobalInitData, 8> PrioritizedCXXGlobalInits;
453
454   /// Global destructor functions and arguments that need to run on termination.
455   std::vector<std::pair<llvm::WeakTrackingVH, llvm::Constant *>> CXXGlobalDtors;
456
457   /// The complete set of modules that has been imported.
458   llvm::SetVector<clang::Module *> ImportedModules;
459
460   /// The set of modules for which the module initializers
461   /// have been emitted.
462   llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
463
464   /// A vector of metadata strings.
465   SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata;
466
467   /// @name Cache for Objective-C runtime types
468   /// @{
469
470   /// Cached reference to the class for constant strings. This value has type
471   /// int * but is actually an Obj-C class pointer.
472   llvm::WeakTrackingVH CFConstantStringClassRef;
473
474   /// The type used to describe the state of a fast enumeration in
475   /// Objective-C's for..in loop.
476   QualType ObjCFastEnumerationStateType;
477
478   /// @}
479
480   /// Lazily create the Objective-C runtime
481   void createObjCRuntime();
482
483   void createOpenCLRuntime();
484   void createOpenMPRuntime();
485   void createCUDARuntime();
486
487   bool isTriviallyRecursive(const FunctionDecl *F);
488   bool shouldEmitFunction(GlobalDecl GD);
489   bool shouldOpportunisticallyEmitVTables();
490   /// Map used to be sure we don't emit the same CompoundLiteral twice.
491   llvm::DenseMap<const CompoundLiteralExpr *, llvm::GlobalVariable *>
492       EmittedCompoundLiterals;
493
494   /// Map of the global blocks we've emitted, so that we don't have to re-emit
495   /// them if the constexpr evaluator gets aggressive.
496   llvm::DenseMap<const BlockExpr *, llvm::Constant *> EmittedGlobalBlocks;
497
498   /// @name Cache for Blocks Runtime Globals
499   /// @{
500
501   llvm::Constant *NSConcreteGlobalBlock = nullptr;
502   llvm::Constant *NSConcreteStackBlock = nullptr;
503
504   llvm::Constant *BlockObjectAssign = nullptr;
505   llvm::Constant *BlockObjectDispose = nullptr;
506
507   llvm::Type *BlockDescriptorType = nullptr;
508   llvm::Type *GenericBlockLiteralType = nullptr;
509
510   struct {
511     int GlobalUniqueCount;
512   } Block;
513
514   /// void @llvm.lifetime.start(i64 %size, i8* nocapture <ptr>)
515   llvm::Constant *LifetimeStartFn = nullptr;
516
517   /// void @llvm.lifetime.end(i64 %size, i8* nocapture <ptr>)
518   llvm::Constant *LifetimeEndFn = nullptr;
519
520   GlobalDecl initializedGlobalDecl;
521
522   std::unique_ptr<SanitizerMetadata> SanitizerMD;
523
524   /// @}
525
526   llvm::MapVector<const Decl *, bool> DeferredEmptyCoverageMappingDecls;
527
528   std::unique_ptr<CoverageMappingModuleGen> CoverageMapping;
529
530   /// Mapping from canonical types to their metadata identifiers. We need to
531   /// maintain this mapping because identifiers may be formed from distinct
532   /// MDNodes.
533   typedef llvm::DenseMap<QualType, llvm::Metadata *> MetadataTypeMap;
534   MetadataTypeMap MetadataIdMap;
535   MetadataTypeMap VirtualMetadataIdMap;
536   MetadataTypeMap GeneralizedMetadataIdMap;
537
538 public:
539   CodeGenModule(ASTContext &C, const HeaderSearchOptions &headersearchopts,
540                 const PreprocessorOptions &ppopts,
541                 const CodeGenOptions &CodeGenOpts, llvm::Module &M,
542                 DiagnosticsEngine &Diags,
543                 CoverageSourceInfo *CoverageInfo = nullptr);
544
545   ~CodeGenModule();
546
547   void clear();
548
549   /// Finalize LLVM code generation.
550   void Release();
551
552   /// Return true if we should emit location information for expressions.
553   bool getExpressionLocationsEnabled() const;
554
555   /// Return a reference to the configured Objective-C runtime.
556   CGObjCRuntime &getObjCRuntime() {
557     if (!ObjCRuntime) createObjCRuntime();
558     return *ObjCRuntime;
559   }
560
561   /// Return true iff an Objective-C runtime has been configured.
562   bool hasObjCRuntime() { return !!ObjCRuntime; }
563
564   /// Return a reference to the configured OpenCL runtime.
565   CGOpenCLRuntime &getOpenCLRuntime() {
566     assert(OpenCLRuntime != nullptr);
567     return *OpenCLRuntime;
568   }
569
570   /// Return a reference to the configured OpenMP runtime.
571   CGOpenMPRuntime &getOpenMPRuntime() {
572     assert(OpenMPRuntime != nullptr);
573     return *OpenMPRuntime;
574   }
575
576   /// Return a reference to the configured CUDA runtime.
577   CGCUDARuntime &getCUDARuntime() {
578     assert(CUDARuntime != nullptr);
579     return *CUDARuntime;
580   }
581
582   ObjCEntrypoints &getObjCEntrypoints() const {
583     assert(ObjCData != nullptr);
584     return *ObjCData;
585   }
586
587   // Version checking function, used to implement ObjC's @available:
588   // i32 @__isOSVersionAtLeast(i32, i32, i32)
589   llvm::Constant *IsOSVersionAtLeastFn = nullptr;
590
591   InstrProfStats &getPGOStats() { return PGOStats; }
592   llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
593
594   CoverageMappingModuleGen *getCoverageMapping() const {
595     return CoverageMapping.get();
596   }
597
598   llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
599     return StaticLocalDeclMap[D];
600   }
601   void setStaticLocalDeclAddress(const VarDecl *D,
602                                  llvm::Constant *C) {
603     StaticLocalDeclMap[D] = C;
604   }
605
606   llvm::Constant *
607   getOrCreateStaticVarDecl(const VarDecl &D,
608                            llvm::GlobalValue::LinkageTypes Linkage);
609
610   llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
611     return StaticLocalDeclGuardMap[D];
612   }
613   void setStaticLocalDeclGuardAddress(const VarDecl *D,
614                                       llvm::GlobalVariable *C) {
615     StaticLocalDeclGuardMap[D] = C;
616   }
617
618   bool lookupRepresentativeDecl(StringRef MangledName,
619                                 GlobalDecl &Result) const;
620
621   llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
622     return AtomicSetterHelperFnMap[Ty];
623   }
624   void setAtomicSetterHelperFnMap(QualType Ty,
625                             llvm::Constant *Fn) {
626     AtomicSetterHelperFnMap[Ty] = Fn;
627   }
628
629   llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
630     return AtomicGetterHelperFnMap[Ty];
631   }
632   void setAtomicGetterHelperFnMap(QualType Ty,
633                             llvm::Constant *Fn) {
634     AtomicGetterHelperFnMap[Ty] = Fn;
635   }
636
637   llvm::Constant *getTypeDescriptorFromMap(QualType Ty) {
638     return TypeDescriptorMap[Ty];
639   }
640   void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C) {
641     TypeDescriptorMap[Ty] = C;
642   }
643
644   CGDebugInfo *getModuleDebugInfo() { return DebugInfo.get(); }
645
646   llvm::MDNode *getNoObjCARCExceptionsMetadata() {
647     if (!NoObjCARCExceptionsMetadata)
648       NoObjCARCExceptionsMetadata = llvm::MDNode::get(getLLVMContext(), None);
649     return NoObjCARCExceptionsMetadata;
650   }
651
652   ASTContext &getContext() const { return Context; }
653   const LangOptions &getLangOpts() const { return LangOpts; }
654   const HeaderSearchOptions &getHeaderSearchOpts()
655     const { return HeaderSearchOpts; }
656   const PreprocessorOptions &getPreprocessorOpts()
657     const { return PreprocessorOpts; }
658   const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
659   llvm::Module &getModule() const { return TheModule; }
660   DiagnosticsEngine &getDiags() const { return Diags; }
661   const llvm::DataLayout &getDataLayout() const {
662     return TheModule.getDataLayout();
663   }
664   const TargetInfo &getTarget() const { return Target; }
665   const llvm::Triple &getTriple() const { return Target.getTriple(); }
666   bool supportsCOMDAT() const;
667   void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO);
668
669   CGCXXABI &getCXXABI() const { return *ABI; }
670   llvm::LLVMContext &getLLVMContext() { return VMContext; }
671
672   bool shouldUseTBAA() const { return TBAA != nullptr; }
673
674   const TargetCodeGenInfo &getTargetCodeGenInfo();
675
676   CodeGenTypes &getTypes() { return Types; }
677
678   CodeGenVTables &getVTables() { return VTables; }
679
680   ItaniumVTableContext &getItaniumVTableContext() {
681     return VTables.getItaniumVTableContext();
682   }
683
684   MicrosoftVTableContext &getMicrosoftVTableContext() {
685     return VTables.getMicrosoftVTableContext();
686   }
687
688   CtorList &getGlobalCtors() { return GlobalCtors; }
689   CtorList &getGlobalDtors() { return GlobalDtors; }
690
691   /// getTBAATypeInfo - Get metadata used to describe accesses to objects of
692   /// the given type.
693   llvm::MDNode *getTBAATypeInfo(QualType QTy);
694
695   /// getTBAAAccessInfo - Get TBAA information that describes an access to
696   /// an object of the given type.
697   TBAAAccessInfo getTBAAAccessInfo(QualType AccessType);
698
699   /// getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an
700   /// access to a virtual table pointer.
701   TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType);
702
703   llvm::MDNode *getTBAAStructInfo(QualType QTy);
704
705   /// getTBAABaseTypeInfo - Get metadata that describes the given base access
706   /// type. Return null if the type is not suitable for use in TBAA access tags.
707   llvm::MDNode *getTBAABaseTypeInfo(QualType QTy);
708
709   /// getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
710   llvm::MDNode *getTBAAAccessTagInfo(TBAAAccessInfo Info);
711
712   /// mergeTBAAInfoForCast - Get merged TBAA information for the purposes of
713   /// type casts.
714   TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
715                                       TBAAAccessInfo TargetInfo);
716
717   /// mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the
718   /// purposes of conditional operator.
719   TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
720                                                      TBAAAccessInfo InfoB);
721
722   /// mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the
723   /// purposes of memory transfer calls.
724   TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
725                                                 TBAAAccessInfo SrcInfo);
726
727   /// getTBAAInfoForSubobject - Get TBAA information for an access with a given
728   /// base lvalue.
729   TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType) {
730     if (Base.getTBAAInfo().isMayAlias())
731       return TBAAAccessInfo::getMayAliasInfo();
732     return getTBAAAccessInfo(AccessType);
733   }
734
735   bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
736
737   bool isPaddedAtomicType(QualType type);
738   bool isPaddedAtomicType(const AtomicType *type);
739
740   /// DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
741   void DecorateInstructionWithTBAA(llvm::Instruction *Inst,
742                                    TBAAAccessInfo TBAAInfo);
743
744   /// Adds !invariant.barrier !tag to instruction
745   void DecorateInstructionWithInvariantGroup(llvm::Instruction *I,
746                                              const CXXRecordDecl *RD);
747
748   /// Emit the given number of characters as a value of type size_t.
749   llvm::ConstantInt *getSize(CharUnits numChars);
750
751   /// Set the visibility for the given LLVM GlobalValue.
752   void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const;
753
754   void setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
755                                    const NamedDecl *D) const;
756
757   void setDSOLocal(llvm::GlobalValue *GV) const;
758
759   void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const;
760   void setDLLImportDLLExport(llvm::GlobalValue *GV, const NamedDecl *D) const;
761   /// Set visibility, dllimport/dllexport and dso_local.
762   /// This must be called after dllimport/dllexport is set.
763   void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const;
764   void setGVProperties(llvm::GlobalValue *GV, const NamedDecl *D) const;
765
766   /// Set the TLS mode for the given LLVM GlobalValue for the thread-local
767   /// variable declaration D.
768   void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const;
769
770   static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
771     switch (V) {
772     case DefaultVisibility:   return llvm::GlobalValue::DefaultVisibility;
773     case HiddenVisibility:    return llvm::GlobalValue::HiddenVisibility;
774     case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
775     }
776     llvm_unreachable("unknown visibility!");
777   }
778
779   llvm::Constant *GetAddrOfGlobal(GlobalDecl GD,
780                                   ForDefinition_t IsForDefinition
781                                     = NotForDefinition);
782
783   /// Will return a global variable of the given type. If a variable with a
784   /// different type already exists then a new  variable with the right type
785   /// will be created and all uses of the old variable will be replaced with a
786   /// bitcast to the new variable.
787   llvm::GlobalVariable *
788   CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty,
789                                     llvm::GlobalValue::LinkageTypes Linkage,
790                                     unsigned Alignment);
791
792   llvm::Function *
793   CreateGlobalInitOrDestructFunction(llvm::FunctionType *ty, const Twine &name,
794                                      const CGFunctionInfo &FI,
795                                      SourceLocation Loc = SourceLocation(),
796                                      bool TLS = false);
797
798   /// Return the AST address space of the underlying global variable for D, as
799   /// determined by its declaration. Normally this is the same as the address
800   /// space of D's type, but in CUDA, address spaces are associated with
801   /// declarations, not types. If D is nullptr, return the default address
802   /// space for global variable.
803   ///
804   /// For languages without explicit address spaces, if D has default address
805   /// space, target-specific global or constant address space may be returned.
806   LangAS GetGlobalVarAddressSpace(const VarDecl *D);
807
808   /// Return the llvm::Constant for the address of the given global variable.
809   /// If Ty is non-null and if the global doesn't exist, then it will be created
810   /// with the specified type instead of whatever the normal requested type
811   /// would be. If IsForDefinition is true, it is guaranteed that an actual
812   /// global with type Ty will be returned, not conversion of a variable with
813   /// the same mangled name but some other type.
814   llvm::Constant *GetAddrOfGlobalVar(const VarDecl *D,
815                                      llvm::Type *Ty = nullptr,
816                                      ForDefinition_t IsForDefinition
817                                        = NotForDefinition);
818
819   /// Return the AST address space of string literal, which is used to emit
820   /// the string literal as global variable in LLVM IR.
821   /// Note: This is not necessarily the address space of the string literal
822   /// in AST. For address space agnostic language, e.g. C++, string literal
823   /// in AST is always in default address space.
824   LangAS getStringLiteralAddressSpace() const;
825
826   /// Return the address of the given function. If Ty is non-null, then this
827   /// function will use the specified type if it has to create it.
828   llvm::Constant *GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty = nullptr,
829                                     bool ForVTable = false,
830                                     bool DontDefer = false,
831                                     ForDefinition_t IsForDefinition
832                                       = NotForDefinition);
833
834   /// Get the address of the RTTI descriptor for the given type.
835   llvm::Constant *GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH = false);
836
837   /// Get the address of a uuid descriptor .
838   ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr* E);
839
840   /// Get the address of the thunk for the given global decl.
841   llvm::Constant *GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
842                                  GlobalDecl GD);
843
844   /// Get a reference to the target of VD.
845   ConstantAddress GetWeakRefReference(const ValueDecl *VD);
846
847   /// Returns the assumed alignment of an opaque pointer to the given class.
848   CharUnits getClassPointerAlignment(const CXXRecordDecl *CD);
849
850   /// Returns the assumed alignment of a virtual base of a class.
851   CharUnits getVBaseAlignment(CharUnits DerivedAlign,
852                               const CXXRecordDecl *Derived,
853                               const CXXRecordDecl *VBase);
854
855   /// Given a class pointer with an actual known alignment, and the
856   /// expected alignment of an object at a dynamic offset w.r.t that
857   /// pointer, return the alignment to assume at the offset.
858   CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign,
859                                       const CXXRecordDecl *Class,
860                                       CharUnits ExpectedTargetAlign);
861
862   CharUnits
863   computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass,
864                                    CastExpr::path_const_iterator Start,
865                                    CastExpr::path_const_iterator End);
866
867   /// Returns the offset from a derived class to  a class. Returns null if the
868   /// offset is 0.
869   llvm::Constant *
870   GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
871                                CastExpr::path_const_iterator PathBegin,
872                                CastExpr::path_const_iterator PathEnd);
873
874   llvm::FoldingSet<BlockByrefHelpers> ByrefHelpersCache;
875
876   /// Fetches the global unique block count.
877   int getUniqueBlockCount() { return ++Block.GlobalUniqueCount; }
878
879   /// Fetches the type of a generic block descriptor.
880   llvm::Type *getBlockDescriptorType();
881
882   /// The type of a generic block literal.
883   llvm::Type *getGenericBlockLiteralType();
884
885   /// Gets the address of a block which requires no captures.
886   llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name);
887
888   /// Returns the address of a block which requires no caputres, or null if
889   /// we've yet to emit the block for BE.
890   llvm::Constant *getAddrOfGlobalBlockIfEmitted(const BlockExpr *BE) {
891     return EmittedGlobalBlocks.lookup(BE);
892   }
893
894   /// Notes that BE's global block is available via Addr. Asserts that BE
895   /// isn't already emitted.
896   void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
897
898   /// Return a pointer to a constant CFString object for the given string.
899   ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
900
901   /// Return a pointer to a constant NSString object for the given string. Or a
902   /// user defined String object as defined via
903   /// -fconstant-string-class=class_name option.
904   ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
905
906   /// Return a constant array for the given string.
907   llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
908
909   /// Return a pointer to a constant array for the given string literal.
910   ConstantAddress
911   GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
912                                      StringRef Name = ".str");
913
914   /// Return a pointer to a constant array for the given ObjCEncodeExpr node.
915   ConstantAddress
916   GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *);
917
918   /// Returns a pointer to a character array containing the literal and a
919   /// terminating '\0' character. The result has pointer to array type.
920   ///
921   /// \param GlobalName If provided, the name to use for the global (if one is
922   /// created).
923   ConstantAddress
924   GetAddrOfConstantCString(const std::string &Str,
925                            const char *GlobalName = nullptr);
926
927   /// Returns a pointer to a constant global variable for the given file-scope
928   /// compound literal expression.
929   ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr*E);
930
931   /// If it's been emitted already, returns the GlobalVariable corresponding to
932   /// a compound literal. Otherwise, returns null.
933   llvm::GlobalVariable *
934   getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E);
935
936   /// Notes that CLE's GlobalVariable is GV. Asserts that CLE isn't already
937   /// emitted.
938   void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE,
939                                         llvm::GlobalVariable *GV);
940
941   /// Returns a pointer to a global variable representing a temporary
942   /// with static or thread storage duration.
943   ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E,
944                                            const Expr *Inner);
945
946   /// Retrieve the record type that describes the state of an
947   /// Objective-C fast enumeration loop (for..in).
948   QualType getObjCFastEnumerationStateType();
949
950   // Produce code for this constructor/destructor. This method doesn't try
951   // to apply any ABI rules about which other constructors/destructors
952   // are needed or if they are alias to each other.
953   llvm::Function *codegenCXXStructor(const CXXMethodDecl *MD,
954                                      StructorType Type);
955
956   /// Return the address of the constructor/destructor of the given type.
957   llvm::Constant *
958   getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type,
959                        const CGFunctionInfo *FnInfo = nullptr,
960                        llvm::FunctionType *FnType = nullptr,
961                        bool DontDefer = false,
962                        ForDefinition_t IsForDefinition = NotForDefinition);
963
964   /// Given a builtin id for a function like "__builtin_fabsf", return a
965   /// Function* for "fabsf".
966   llvm::Constant *getBuiltinLibFunction(const FunctionDecl *FD,
967                                         unsigned BuiltinID);
968
969   llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
970
971   /// Emit code for a single top level declaration.
972   void EmitTopLevelDecl(Decl *D);
973
974   /// Stored a deferred empty coverage mapping for an unused
975   /// and thus uninstrumented top level declaration.
976   void AddDeferredUnusedCoverageMapping(Decl *D);
977
978   /// Remove the deferred empty coverage mapping as this
979   /// declaration is actually instrumented.
980   void ClearUnusedCoverageMapping(const Decl *D);
981
982   /// Emit all the deferred coverage mappings
983   /// for the uninstrumented functions.
984   void EmitDeferredUnusedCoverageMappings();
985
986   /// Tell the consumer that this variable has been instantiated.
987   void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
988
989   /// If the declaration has internal linkage but is inside an
990   /// extern "C" linkage specification, prepare to emit an alias for it
991   /// to the expected name.
992   template<typename SomeDecl>
993   void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
994
995   /// Add a global to a list to be added to the llvm.used metadata.
996   void addUsedGlobal(llvm::GlobalValue *GV);
997
998   /// Add a global to a list to be added to the llvm.compiler.used metadata.
999   void addCompilerUsedGlobal(llvm::GlobalValue *GV);
1000
1001   /// Add a destructor and object to add to the C++ global destructor function.
1002   void AddCXXDtorEntry(llvm::Constant *DtorFn, llvm::Constant *Object) {
1003     CXXGlobalDtors.emplace_back(DtorFn, Object);
1004   }
1005
1006   /// Create a new runtime function with the specified type and name.
1007   llvm::Constant *
1008   CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name,
1009                         llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1010                         bool Local = false);
1011
1012   /// Create a new compiler builtin function with the specified type and name.
1013   llvm::Constant *
1014   CreateBuiltinFunction(llvm::FunctionType *Ty, StringRef Name,
1015                         llvm::AttributeList ExtraAttrs = llvm::AttributeList());
1016   /// Create a new runtime global variable with the specified type and name.
1017   llvm::Constant *CreateRuntimeVariable(llvm::Type *Ty,
1018                                         StringRef Name);
1019
1020   ///@name Custom Blocks Runtime Interfaces
1021   ///@{
1022
1023   llvm::Constant *getNSConcreteGlobalBlock();
1024   llvm::Constant *getNSConcreteStackBlock();
1025   llvm::Constant *getBlockObjectAssign();
1026   llvm::Constant *getBlockObjectDispose();
1027
1028   ///@}
1029
1030   llvm::Constant *getLLVMLifetimeStartFn();
1031   llvm::Constant *getLLVMLifetimeEndFn();
1032
1033   // Make sure that this type is translated.
1034   void UpdateCompletedType(const TagDecl *TD);
1035
1036   llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
1037
1038   /// Emit type info if type of an expression is a variably modified
1039   /// type. Also emit proper debug info for cast types.
1040   void EmitExplicitCastExprType(const ExplicitCastExpr *E,
1041                                 CodeGenFunction *CGF = nullptr);
1042
1043   /// Return the result of value-initializing the given type, i.e. a null
1044   /// expression of the given type.  This is usually, but not always, an LLVM
1045   /// null constant.
1046   llvm::Constant *EmitNullConstant(QualType T);
1047
1048   /// Return a null constant appropriate for zero-initializing a base class with
1049   /// the given type. This is usually, but not always, an LLVM null constant.
1050   llvm::Constant *EmitNullConstantForBase(const CXXRecordDecl *Record);
1051
1052   /// Emit a general error that something can't be done.
1053   void Error(SourceLocation loc, StringRef error);
1054
1055   /// Print out an error that codegen doesn't support the specified stmt yet.
1056   void ErrorUnsupported(const Stmt *S, const char *Type);
1057
1058   /// Print out an error that codegen doesn't support the specified decl yet.
1059   void ErrorUnsupported(const Decl *D, const char *Type);
1060
1061   /// Set the attributes on the LLVM function for the given decl and function
1062   /// info. This applies attributes necessary for handling the ABI as well as
1063   /// user specified attributes like section.
1064   void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1065                                      const CGFunctionInfo &FI);
1066
1067   /// Set the LLVM function attributes (sext, zext, etc).
1068   void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info,
1069                                  llvm::Function *F);
1070
1071   /// Set the LLVM function attributes which only apply to a function
1072   /// definition.
1073   void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F);
1074
1075   /// Return true iff the given type uses 'sret' when used as a return type.
1076   bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
1077
1078   /// Return true iff the given type uses an argument slot when 'sret' is used
1079   /// as a return type.
1080   bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI);
1081
1082   /// Return true iff the given type uses 'fpret' when used as a return type.
1083   bool ReturnTypeUsesFPRet(QualType ResultType);
1084
1085   /// Return true iff the given type uses 'fp2ret' when used as a return type.
1086   bool ReturnTypeUsesFP2Ret(QualType ResultType);
1087
1088   /// Get the LLVM attributes and calling convention to use for a particular
1089   /// function type.
1090   ///
1091   /// \param Name - The function name.
1092   /// \param Info - The function type information.
1093   /// \param CalleeInfo - The callee information these attributes are being
1094   /// constructed for. If valid, the attributes applied to this decl may
1095   /// contribute to the function attributes and calling convention.
1096   /// \param Attrs [out] - On return, the attribute list to use.
1097   /// \param CallingConv [out] - On return, the LLVM calling convention to use.
1098   void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info,
1099                               CGCalleeInfo CalleeInfo,
1100                               llvm::AttributeList &Attrs, unsigned &CallingConv,
1101                               bool AttrOnCallSite);
1102
1103   /// Adds attributes to F according to our CodeGenOptions and LangOptions, as
1104   /// though we had emitted it ourselves.  We remove any attributes on F that
1105   /// conflict with the attributes we add here.
1106   ///
1107   /// This is useful for adding attrs to bitcode modules that you want to link
1108   /// with but don't control, such as CUDA's libdevice.  When linking with such
1109   /// a bitcode library, you might want to set e.g. its functions'
1110   /// "unsafe-fp-math" attribute to match the attr of the functions you're
1111   /// codegen'ing.  Otherwise, LLVM will interpret the bitcode module's lack of
1112   /// unsafe-fp-math attrs as tantamount to unsafe-fp-math=false, and then LLVM
1113   /// will propagate unsafe-fp-math=false up to every transitive caller of a
1114   /// function in the bitcode library!
1115   ///
1116   /// With the exception of fast-math attrs, this will only make the attributes
1117   /// on the function more conservative.  But it's unsafe to call this on a
1118   /// function which relies on particular fast-math attributes for correctness.
1119   /// It's up to you to ensure that this is safe.
1120   void AddDefaultFnAttrs(llvm::Function &F);
1121
1122   /// Parses the target attributes passed in, and returns only the ones that are
1123   /// valid feature names.
1124   TargetAttr::ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD);
1125
1126   // Fills in the supplied string map with the set of target features for the
1127   // passed in function.
1128   void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, GlobalDecl GD);
1129
1130   StringRef getMangledName(GlobalDecl GD);
1131   StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD);
1132
1133   void EmitTentativeDefinition(const VarDecl *D);
1134
1135   void EmitVTable(CXXRecordDecl *Class);
1136
1137   void RefreshTypeCacheForClass(const CXXRecordDecl *Class);
1138
1139   /// Appends Opts to the "llvm.linker.options" metadata value.
1140   void AppendLinkerOptions(StringRef Opts);
1141
1142   /// Appends a detect mismatch command to the linker options.
1143   void AddDetectMismatch(StringRef Name, StringRef Value);
1144
1145   /// Appends a dependent lib to the "llvm.linker.options" metadata
1146   /// value.
1147   void AddDependentLib(StringRef Lib);
1148
1149   void AddELFLibDirective(StringRef Lib);
1150
1151   llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);
1152
1153   void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
1154     F->setLinkage(getFunctionLinkage(GD));
1155   }
1156
1157   /// Return the appropriate linkage for the vtable, VTT, and type information
1158   /// of the given class.
1159   llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD);
1160
1161   /// Return the store size, in character units, of the given LLVM type.
1162   CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const;
1163
1164   /// Returns LLVM linkage for a declarator.
1165   llvm::GlobalValue::LinkageTypes
1166   getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage,
1167                               bool IsConstantVariable);
1168
1169   /// Returns LLVM linkage for a declarator.
1170   llvm::GlobalValue::LinkageTypes
1171   getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant);
1172
1173   /// Emit all the global annotations.
1174   void EmitGlobalAnnotations();
1175
1176   /// Emit an annotation string.
1177   llvm::Constant *EmitAnnotationString(StringRef Str);
1178
1179   /// Emit the annotation's translation unit.
1180   llvm::Constant *EmitAnnotationUnit(SourceLocation Loc);
1181
1182   /// Emit the annotation line number.
1183   llvm::Constant *EmitAnnotationLineNo(SourceLocation L);
1184
1185   /// Generate the llvm::ConstantStruct which contains the annotation
1186   /// information for a given GlobalValue. The annotation struct is
1187   /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
1188   /// GlobalValue being annotated. The second field is the constant string
1189   /// created from the AnnotateAttr's annotation. The third field is a constant
1190   /// string containing the name of the translation unit. The fourth field is
1191   /// the line number in the file of the annotated value declaration.
1192   llvm::Constant *EmitAnnotateAttr(llvm::GlobalValue *GV,
1193                                    const AnnotateAttr *AA,
1194                                    SourceLocation L);
1195
1196   /// Add global annotations that are set on D, for the global GV. Those
1197   /// annotations are emitted during finalization of the LLVM code.
1198   void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV);
1199
1200   bool isInSanitizerBlacklist(SanitizerMask Kind, llvm::Function *Fn,
1201                               SourceLocation Loc) const;
1202
1203   bool isInSanitizerBlacklist(llvm::GlobalVariable *GV, SourceLocation Loc,
1204                               QualType Ty,
1205                               StringRef Category = StringRef()) const;
1206
1207   /// Imbue XRay attributes to a function, applying the always/never attribute
1208   /// lists in the process. Returns true if we did imbue attributes this way,
1209   /// false otherwise.
1210   bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1211                       StringRef Category = StringRef()) const;
1212
1213   SanitizerMetadata *getSanitizerMetadata() {
1214     return SanitizerMD.get();
1215   }
1216
1217   void addDeferredVTable(const CXXRecordDecl *RD) {
1218     DeferredVTables.push_back(RD);
1219   }
1220
1221   /// Emit code for a single global function or var decl. Forward declarations
1222   /// are emitted lazily.
1223   void EmitGlobal(GlobalDecl D);
1224
1225   bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D);
1226
1227   llvm::GlobalValue *GetGlobalValue(StringRef Ref);
1228
1229   /// Set attributes which are common to any form of a global definition (alias,
1230   /// Objective-C method, function, global variable).
1231   ///
1232   /// NOTE: This should only be called for definitions.
1233   void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV);
1234
1235   void addReplacement(StringRef Name, llvm::Constant *C);
1236
1237   void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C);
1238
1239   /// Emit a code for threadprivate directive.
1240   /// \param D Threadprivate declaration.
1241   void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D);
1242
1243   /// Emit a code for declare reduction construct.
1244   void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1245                                CodeGenFunction *CGF = nullptr);
1246
1247   /// Emit a code for requires directive.
1248   /// \param D Requires declaration
1249   void EmitOMPRequiresDecl(const OMPRequiresDecl *D);
1250
1251   /// Returns whether the given record has hidden LTO visibility and therefore
1252   /// may participate in (single-module) CFI and whole-program vtable
1253   /// optimization.
1254   bool HasHiddenLTOVisibility(const CXXRecordDecl *RD);
1255
1256   /// Emit type metadata for the given vtable using the given layout.
1257   void EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
1258                               const VTableLayout &VTLayout);
1259
1260   /// Generate a cross-DSO type identifier for MD.
1261   llvm::ConstantInt *CreateCrossDsoCfiTypeId(llvm::Metadata *MD);
1262
1263   /// Create a metadata identifier for the given type. This may either be an
1264   /// MDString (for external identifiers) or a distinct unnamed MDNode (for
1265   /// internal identifiers).
1266   llvm::Metadata *CreateMetadataIdentifierForType(QualType T);
1267
1268   /// Create a metadata identifier that is intended to be used to check virtual
1269   /// calls via a member function pointer.
1270   llvm::Metadata *CreateMetadataIdentifierForVirtualMemPtrType(QualType T);
1271
1272   /// Create a metadata identifier for the generalization of the given type.
1273   /// This may either be an MDString (for external identifiers) or a distinct
1274   /// unnamed MDNode (for internal identifiers).
1275   llvm::Metadata *CreateMetadataIdentifierGeneralized(QualType T);
1276
1277   /// Create and attach type metadata to the given function.
1278   void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1279                                           llvm::Function *F);
1280
1281   /// Returns whether this module needs the "all-vtables" type identifier.
1282   bool NeedAllVtablesTypeId() const;
1283
1284   /// Create and attach type metadata for the given vtable.
1285   void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset,
1286                              const CXXRecordDecl *RD);
1287
1288   /// Return a vector of most-base classes for RD. This is used to implement
1289   /// control flow integrity checks for member function pointers.
1290   ///
1291   /// A most-base class of a class C is defined as a recursive base class of C,
1292   /// including C itself, that does not have any bases.
1293   std::vector<const CXXRecordDecl *>
1294   getMostBaseClasses(const CXXRecordDecl *RD);
1295
1296   /// Get the declaration of std::terminate for the platform.
1297   llvm::Constant *getTerminateFn();
1298
1299   llvm::SanitizerStatReport &getSanStats();
1300
1301   llvm::Value *
1302   createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
1303
1304   /// Get target specific null pointer.
1305   /// \param T is the LLVM type of the null pointer.
1306   /// \param QT is the clang QualType of the null pointer.
1307   llvm::Constant *getNullPointer(llvm::PointerType *T, QualType QT);
1308
1309 private:
1310   llvm::Constant *GetOrCreateLLVMFunction(
1311       StringRef MangledName, llvm::Type *Ty, GlobalDecl D, bool ForVTable,
1312       bool DontDefer = false, bool IsThunk = false,
1313       llvm::AttributeList ExtraAttrs = llvm::AttributeList(),
1314       ForDefinition_t IsForDefinition = NotForDefinition);
1315
1316   llvm::Constant *GetOrCreateMultiVersionResolver(GlobalDecl GD,
1317                                                   llvm::Type *DeclTy,
1318                                                   const FunctionDecl *FD);
1319   void UpdateMultiVersionNames(GlobalDecl GD, const FunctionDecl *FD);
1320
1321   llvm::Constant *GetOrCreateLLVMGlobal(StringRef MangledName,
1322                                         llvm::PointerType *PTy,
1323                                         const VarDecl *D,
1324                                         ForDefinition_t IsForDefinition
1325                                           = NotForDefinition);
1326
1327   bool GetCPUAndFeaturesAttributes(GlobalDecl GD,
1328                                    llvm::AttrBuilder &AttrBuilder);
1329   void setNonAliasAttributes(GlobalDecl GD, llvm::GlobalObject *GO);
1330
1331   /// Set function attributes for a function declaration.
1332   void SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1333                              bool IsIncompleteFunction, bool IsThunk);
1334
1335   void EmitGlobalDefinition(GlobalDecl D, llvm::GlobalValue *GV = nullptr);
1336
1337   void EmitGlobalFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1338   void EmitMultiVersionFunctionDefinition(GlobalDecl GD, llvm::GlobalValue *GV);
1339
1340   void EmitGlobalVarDefinition(const VarDecl *D, bool IsTentative = false);
1341   void EmitAliasDefinition(GlobalDecl GD);
1342   void emitIFuncDefinition(GlobalDecl GD);
1343   void emitCPUDispatchDefinition(GlobalDecl GD);
1344   void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
1345   void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
1346
1347   // C++ related functions.
1348
1349   void EmitDeclContext(const DeclContext *DC);
1350   void EmitLinkageSpec(const LinkageSpecDecl *D);
1351
1352   /// Emit the function that initializes C++ thread_local variables.
1353   void EmitCXXThreadLocalInitFunc();
1354
1355   /// Emit the function that initializes C++ globals.
1356   void EmitCXXGlobalInitFunc();
1357
1358   /// Emit the function that destroys C++ globals.
1359   void EmitCXXGlobalDtorFunc();
1360
1361   /// Emit the function that initializes the specified global (if PerformInit is
1362   /// true) and registers its destructor.
1363   void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
1364                                     llvm::GlobalVariable *Addr,
1365                                     bool PerformInit);
1366
1367   void EmitPointerToInitFunc(const VarDecl *VD, llvm::GlobalVariable *Addr,
1368                              llvm::Function *InitFunc, InitSegAttr *ISA);
1369
1370   // FIXME: Hardcoding priority here is gross.
1371   void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
1372                      llvm::Constant *AssociatedData = nullptr);
1373   void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535);
1374
1375   /// EmitCtorList - Generates a global array of functions and priorities using
1376   /// the given list and name. This array will have appending linkage and is
1377   /// suitable for use as a LLVM constructor or destructor array. Clears Fns.
1378   void EmitCtorList(CtorList &Fns, const char *GlobalName);
1379
1380   /// Emit any needed decls for which code generation was deferred.
1381   void EmitDeferred();
1382
1383   /// Try to emit external vtables as available_externally if they have emitted
1384   /// all inlined virtual functions.  It runs after EmitDeferred() and therefore
1385   /// is not allowed to create new references to things that need to be emitted
1386   /// lazily.
1387   void EmitVTablesOpportunistically();
1388
1389   /// Call replaceAllUsesWith on all pairs in Replacements.
1390   void applyReplacements();
1391
1392   /// Call replaceAllUsesWith on all pairs in GlobalValReplacements.
1393   void applyGlobalValReplacements();
1394
1395   void checkAliases();
1396
1397   std::map<int, llvm::TinyPtrVector<llvm::Function *>> DtorsUsingAtExit;
1398
1399   /// Register functions annotated with __attribute__((destructor)) using
1400   /// __cxa_atexit, if it is available, or atexit otherwise.
1401   void registerGlobalDtorsWithAtExit();
1402
1403   void emitMultiVersionFunctions();
1404
1405   /// Emit any vtables which we deferred and still have a use for.
1406   void EmitDeferredVTables();
1407
1408   /// Emit a dummy function that reference a CoreFoundation symbol when
1409   /// @available is used on Darwin.
1410   void emitAtAvailableLinkGuard();
1411
1412   /// Emit the llvm.used and llvm.compiler.used metadata.
1413   void emitLLVMUsed();
1414
1415   /// Emit the link options introduced by imported modules.
1416   void EmitModuleLinkOptions();
1417
1418   /// Emit aliases for internal-linkage declarations inside "C" language
1419   /// linkage specifications, giving them the "expected" name where possible.
1420   void EmitStaticExternCAliases();
1421
1422   void EmitDeclMetadata();
1423
1424   /// Emit the Clang version as llvm.ident metadata.
1425   void EmitVersionIdentMetadata();
1426
1427   /// Emit the Clang commandline as llvm.commandline metadata.
1428   void EmitCommandLineMetadata();
1429
1430   /// Emits target specific Metadata for global declarations.
1431   void EmitTargetMetadata();
1432
1433   /// Emits OpenCL specific Metadata e.g. OpenCL version.
1434   void EmitOpenCLMetadata();
1435
1436   /// Emit the llvm.gcov metadata used to tell LLVM where to emit the .gcno and
1437   /// .gcda files in a way that persists in .bc files.
1438   void EmitCoverageFile();
1439
1440   /// Emits the initializer for a uuidof string.
1441   llvm::Constant *EmitUuidofInitializer(StringRef uuidstr);
1442
1443   /// Determine whether the definition must be emitted; if this returns \c
1444   /// false, the definition can be emitted lazily if it's used.
1445   bool MustBeEmitted(const ValueDecl *D);
1446
1447   /// Determine whether the definition can be emitted eagerly, or should be
1448   /// delayed until the end of the translation unit. This is relevant for
1449   /// definitions whose linkage can change, e.g. implicit function instantions
1450   /// which may later be explicitly instantiated.
1451   bool MayBeEmittedEagerly(const ValueDecl *D);
1452
1453   /// Check whether we can use a "simpler", more core exceptions personality
1454   /// function.
1455   void SimplifyPersonality();
1456
1457   /// Helper function for ConstructAttributeList and AddDefaultFnAttrs.
1458   /// Constructs an AttrList for a function with the given properties.
1459   void ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
1460                                   bool AttrOnCallSite,
1461                                   llvm::AttrBuilder &FuncAttrs);
1462
1463   llvm::Metadata *CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
1464                                                StringRef Suffix);
1465 };
1466
1467 }  // end namespace CodeGen
1468 }  // end namespace clang
1469
1470 #endif // LLVM_CLANG_LIB_CODEGEN_CODEGENMODULE_H