]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CodeGenFunction.h
Merge ^/head r318380 through r318559.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CodeGenFunction.h
1 //===-- CodeGenFunction.h - Per-Function 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-function state used for llvm translation.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
15 #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
16
17 #include "CGBuilder.h"
18 #include "CGDebugInfo.h"
19 #include "CGLoopInfo.h"
20 #include "CGValue.h"
21 #include "CodeGenModule.h"
22 #include "CodeGenPGO.h"
23 #include "EHScopeStack.h"
24 #include "VarBypassDetector.h"
25 #include "clang/AST/CharUnits.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/Type.h"
30 #include "clang/Basic/ABI.h"
31 #include "clang/Basic/CapturedStmt.h"
32 #include "clang/Basic/OpenMPKinds.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Frontend/CodeGenOptions.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/IR/ValueHandle.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Transforms/Utils/SanitizerStats.h"
41
42 namespace llvm {
43 class BasicBlock;
44 class LLVMContext;
45 class MDNode;
46 class Module;
47 class SwitchInst;
48 class Twine;
49 class Value;
50 class CallSite;
51 }
52
53 namespace clang {
54 class ASTContext;
55 class BlockDecl;
56 class CXXDestructorDecl;
57 class CXXForRangeStmt;
58 class CXXTryStmt;
59 class Decl;
60 class LabelDecl;
61 class EnumConstantDecl;
62 class FunctionDecl;
63 class FunctionProtoType;
64 class LabelStmt;
65 class ObjCContainerDecl;
66 class ObjCInterfaceDecl;
67 class ObjCIvarDecl;
68 class ObjCMethodDecl;
69 class ObjCImplementationDecl;
70 class ObjCPropertyImplDecl;
71 class TargetInfo;
72 class VarDecl;
73 class ObjCForCollectionStmt;
74 class ObjCAtTryStmt;
75 class ObjCAtThrowStmt;
76 class ObjCAtSynchronizedStmt;
77 class ObjCAutoreleasePoolStmt;
78
79 namespace CodeGen {
80 class CodeGenTypes;
81 class CGCallee;
82 class CGFunctionInfo;
83 class CGRecordLayout;
84 class CGBlockInfo;
85 class CGCXXABI;
86 class BlockByrefHelpers;
87 class BlockByrefInfo;
88 class BlockFlags;
89 class BlockFieldFlags;
90 class RegionCodeGenTy;
91 class TargetCodeGenInfo;
92 struct OMPTaskDataTy;
93 struct CGCoroData;
94
95 /// The kind of evaluation to perform on values of a particular
96 /// type.  Basically, is the code in CGExprScalar, CGExprComplex, or
97 /// CGExprAgg?
98 ///
99 /// TODO: should vectors maybe be split out into their own thing?
100 enum TypeEvaluationKind {
101   TEK_Scalar,
102   TEK_Complex,
103   TEK_Aggregate
104 };
105
106 #define LIST_SANITIZER_CHECKS                                                  \
107   SANITIZER_CHECK(AddOverflow, add_overflow, 0)                                \
108   SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0)                  \
109   SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0)                             \
110   SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0)                          \
111   SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0)            \
112   SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0)                   \
113   SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 0)             \
114   SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0)                     \
115   SANITIZER_CHECK(MissingReturn, missing_return, 0)                            \
116   SANITIZER_CHECK(MulOverflow, mul_overflow, 0)                                \
117   SANITIZER_CHECK(NegateOverflow, negate_overflow, 0)                          \
118   SANITIZER_CHECK(NullabilityArg, nullability_arg, 0)                          \
119   SANITIZER_CHECK(NullabilityReturn, nullability_return, 0)                    \
120   SANITIZER_CHECK(NonnullArg, nonnull_arg, 0)                                  \
121   SANITIZER_CHECK(NonnullReturn, nonnull_return, 0)                            \
122   SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0)                               \
123   SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0)                    \
124   SANITIZER_CHECK(SubOverflow, sub_overflow, 0)                                \
125   SANITIZER_CHECK(TypeMismatch, type_mismatch, 1)                              \
126   SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
127
128 enum SanitizerHandler {
129 #define SANITIZER_CHECK(Enum, Name, Version) Enum,
130   LIST_SANITIZER_CHECKS
131 #undef SANITIZER_CHECK
132 };
133
134 /// CodeGenFunction - This class organizes the per-function state that is used
135 /// while generating LLVM code.
136 class CodeGenFunction : public CodeGenTypeCache {
137   CodeGenFunction(const CodeGenFunction &) = delete;
138   void operator=(const CodeGenFunction &) = delete;
139
140   friend class CGCXXABI;
141 public:
142   /// A jump destination is an abstract label, branching to which may
143   /// require a jump out through normal cleanups.
144   struct JumpDest {
145     JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
146     JumpDest(llvm::BasicBlock *Block,
147              EHScopeStack::stable_iterator Depth,
148              unsigned Index)
149       : Block(Block), ScopeDepth(Depth), Index(Index) {}
150
151     bool isValid() const { return Block != nullptr; }
152     llvm::BasicBlock *getBlock() const { return Block; }
153     EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
154     unsigned getDestIndex() const { return Index; }
155
156     // This should be used cautiously.
157     void setScopeDepth(EHScopeStack::stable_iterator depth) {
158       ScopeDepth = depth;
159     }
160
161   private:
162     llvm::BasicBlock *Block;
163     EHScopeStack::stable_iterator ScopeDepth;
164     unsigned Index;
165   };
166
167   CodeGenModule &CGM;  // Per-module state.
168   const TargetInfo &Target;
169
170   typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
171   LoopInfoStack LoopStack;
172   CGBuilderTy Builder;
173
174   // Stores variables for which we can't generate correct lifetime markers
175   // because of jumps.
176   VarBypassDetector Bypasses;
177
178   // CodeGen lambda for loops and support for ordered clause
179   typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
180                                   JumpDest)>
181       CodeGenLoopTy;
182   typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
183                                   const unsigned, const bool)>
184       CodeGenOrderedTy;
185
186   // Codegen lambda for loop bounds in worksharing loop constructs
187   typedef llvm::function_ref<std::pair<LValue, LValue>(
188       CodeGenFunction &, const OMPExecutableDirective &S)>
189       CodeGenLoopBoundsTy;
190
191   // Codegen lambda for loop bounds in dispatch-based loop implementation
192   typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
193       CodeGenFunction &, const OMPExecutableDirective &S, Address LB,
194       Address UB)>
195       CodeGenDispatchBoundsTy;
196
197   /// \brief CGBuilder insert helper. This function is called after an
198   /// instruction is created using Builder.
199   void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
200                     llvm::BasicBlock *BB,
201                     llvm::BasicBlock::iterator InsertPt) const;
202
203   /// CurFuncDecl - Holds the Decl for the current outermost
204   /// non-closure context.
205   const Decl *CurFuncDecl;
206   /// CurCodeDecl - This is the inner-most code context, which includes blocks.
207   const Decl *CurCodeDecl;
208   const CGFunctionInfo *CurFnInfo;
209   QualType FnRetTy;
210   llvm::Function *CurFn;
211
212   // Holds coroutine data if the current function is a coroutine. We use a
213   // wrapper to manage its lifetime, so that we don't have to define CGCoroData
214   // in this header.
215   struct CGCoroInfo {
216     std::unique_ptr<CGCoroData> Data;
217     CGCoroInfo();
218     ~CGCoroInfo();
219   };
220   CGCoroInfo CurCoro;
221
222   /// CurGD - The GlobalDecl for the current function being compiled.
223   GlobalDecl CurGD;
224
225   /// PrologueCleanupDepth - The cleanup depth enclosing all the
226   /// cleanups associated with the parameters.
227   EHScopeStack::stable_iterator PrologueCleanupDepth;
228
229   /// ReturnBlock - Unified return block.
230   JumpDest ReturnBlock;
231
232   /// ReturnValue - The temporary alloca to hold the return
233   /// value. This is invalid iff the function has no return value.
234   Address ReturnValue;
235
236   /// Return true if a label was seen in the current scope.
237   bool hasLabelBeenSeenInCurrentScope() const {
238     if (CurLexicalScope)
239       return CurLexicalScope->hasLabels();
240     return !LabelMap.empty();
241   }
242
243   /// AllocaInsertPoint - This is an instruction in the entry block before which
244   /// we prefer to insert allocas.
245   llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
246
247   /// \brief API for captured statement code generation.
248   class CGCapturedStmtInfo {
249   public:
250     explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
251         : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
252     explicit CGCapturedStmtInfo(const CapturedStmt &S,
253                                 CapturedRegionKind K = CR_Default)
254       : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
255
256       RecordDecl::field_iterator Field =
257         S.getCapturedRecordDecl()->field_begin();
258       for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
259                                                 E = S.capture_end();
260            I != E; ++I, ++Field) {
261         if (I->capturesThis())
262           CXXThisFieldDecl = *Field;
263         else if (I->capturesVariable())
264           CaptureFields[I->getCapturedVar()] = *Field;
265         else if (I->capturesVariableByCopy())
266           CaptureFields[I->getCapturedVar()] = *Field;
267       }
268     }
269
270     virtual ~CGCapturedStmtInfo();
271
272     CapturedRegionKind getKind() const { return Kind; }
273
274     virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
275     // \brief Retrieve the value of the context parameter.
276     virtual llvm::Value *getContextValue() const { return ThisValue; }
277
278     /// \brief Lookup the captured field decl for a variable.
279     virtual const FieldDecl *lookup(const VarDecl *VD) const {
280       return CaptureFields.lookup(VD);
281     }
282
283     bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
284     virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
285
286     static bool classof(const CGCapturedStmtInfo *) {
287       return true;
288     }
289
290     /// \brief Emit the captured statement body.
291     virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
292       CGF.incrementProfileCounter(S);
293       CGF.EmitStmt(S);
294     }
295
296     /// \brief Get the name of the capture helper.
297     virtual StringRef getHelperName() const { return "__captured_stmt"; }
298
299   private:
300     /// \brief The kind of captured statement being generated.
301     CapturedRegionKind Kind;
302
303     /// \brief Keep the map between VarDecl and FieldDecl.
304     llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
305
306     /// \brief The base address of the captured record, passed in as the first
307     /// argument of the parallel region function.
308     llvm::Value *ThisValue;
309
310     /// \brief Captured 'this' type.
311     FieldDecl *CXXThisFieldDecl;
312   };
313   CGCapturedStmtInfo *CapturedStmtInfo;
314
315   /// \brief RAII for correct setting/restoring of CapturedStmtInfo.
316   class CGCapturedStmtRAII {
317   private:
318     CodeGenFunction &CGF;
319     CGCapturedStmtInfo *PrevCapturedStmtInfo;
320   public:
321     CGCapturedStmtRAII(CodeGenFunction &CGF,
322                        CGCapturedStmtInfo *NewCapturedStmtInfo)
323         : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
324       CGF.CapturedStmtInfo = NewCapturedStmtInfo;
325     }
326     ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
327   };
328
329   /// An abstract representation of regular/ObjC call/message targets.
330   class AbstractCallee {
331     /// The function declaration of the callee.
332     const Decl *CalleeDecl;
333
334   public:
335     AbstractCallee() : CalleeDecl(nullptr) {}
336     AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
337     AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
338     bool hasFunctionDecl() const {
339       return dyn_cast_or_null<FunctionDecl>(CalleeDecl);
340     }
341     const Decl *getDecl() const { return CalleeDecl; }
342     unsigned getNumParams() const {
343       if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
344         return FD->getNumParams();
345       return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
346     }
347     const ParmVarDecl *getParamDecl(unsigned I) const {
348       if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
349         return FD->getParamDecl(I);
350       return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
351     }
352   };
353
354   /// \brief Sanitizers enabled for this function.
355   SanitizerSet SanOpts;
356
357   /// \brief True if CodeGen currently emits code implementing sanitizer checks.
358   bool IsSanitizerScope;
359
360   /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope.
361   class SanitizerScope {
362     CodeGenFunction *CGF;
363   public:
364     SanitizerScope(CodeGenFunction *CGF);
365     ~SanitizerScope();
366   };
367
368   /// In C++, whether we are code generating a thunk.  This controls whether we
369   /// should emit cleanups.
370   bool CurFuncIsThunk;
371
372   /// In ARC, whether we should autorelease the return value.
373   bool AutoreleaseResult;
374
375   /// Whether we processed a Microsoft-style asm block during CodeGen. These can
376   /// potentially set the return value.
377   bool SawAsmBlock;
378
379   const FunctionDecl *CurSEHParent = nullptr;
380
381   /// True if the current function is an outlined SEH helper. This can be a
382   /// finally block or filter expression.
383   bool IsOutlinedSEHHelper;
384
385   const CodeGen::CGBlockInfo *BlockInfo;
386   llvm::Value *BlockPointer;
387
388   llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
389   FieldDecl *LambdaThisCaptureField;
390
391   /// \brief A mapping from NRVO variables to the flags used to indicate
392   /// when the NRVO has been applied to this variable.
393   llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
394
395   EHScopeStack EHStack;
396   llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
397   llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
398
399   llvm::Instruction *CurrentFuncletPad = nullptr;
400
401   class CallLifetimeEnd final : public EHScopeStack::Cleanup {
402     llvm::Value *Addr;
403     llvm::Value *Size;
404
405   public:
406     CallLifetimeEnd(Address addr, llvm::Value *size)
407         : Addr(addr.getPointer()), Size(size) {}
408
409     void Emit(CodeGenFunction &CGF, Flags flags) override {
410       CGF.EmitLifetimeEnd(Size, Addr);
411     }
412   };
413
414   /// Header for data within LifetimeExtendedCleanupStack.
415   struct LifetimeExtendedCleanupHeader {
416     /// The size of the following cleanup object.
417     unsigned Size;
418     /// The kind of cleanup to push: a value from the CleanupKind enumeration.
419     CleanupKind Kind;
420
421     size_t getSize() const { return Size; }
422     CleanupKind getKind() const { return Kind; }
423   };
424
425   /// i32s containing the indexes of the cleanup destinations.
426   llvm::AllocaInst *NormalCleanupDest;
427
428   unsigned NextCleanupDestIndex;
429
430   /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
431   CGBlockInfo *FirstBlockInfo;
432
433   /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
434   llvm::BasicBlock *EHResumeBlock;
435
436   /// The exception slot.  All landing pads write the current exception pointer
437   /// into this alloca.
438   llvm::Value *ExceptionSlot;
439
440   /// The selector slot.  Under the MandatoryCleanup model, all landing pads
441   /// write the current selector value into this alloca.
442   llvm::AllocaInst *EHSelectorSlot;
443
444   /// A stack of exception code slots. Entering an __except block pushes a slot
445   /// on the stack and leaving pops one. The __exception_code() intrinsic loads
446   /// a value from the top of the stack.
447   SmallVector<Address, 1> SEHCodeSlotStack;
448
449   /// Value returned by __exception_info intrinsic.
450   llvm::Value *SEHInfo = nullptr;
451
452   /// Emits a landing pad for the current EH stack.
453   llvm::BasicBlock *EmitLandingPad();
454
455   llvm::BasicBlock *getInvokeDestImpl();
456
457   template <class T>
458   typename DominatingValue<T>::saved_type saveValueInCond(T value) {
459     return DominatingValue<T>::save(*this, value);
460   }
461
462 public:
463   /// ObjCEHValueStack - Stack of Objective-C exception values, used for
464   /// rethrows.
465   SmallVector<llvm::Value*, 8> ObjCEHValueStack;
466
467   /// A class controlling the emission of a finally block.
468   class FinallyInfo {
469     /// Where the catchall's edge through the cleanup should go.
470     JumpDest RethrowDest;
471
472     /// A function to call to enter the catch.
473     llvm::Constant *BeginCatchFn;
474
475     /// An i1 variable indicating whether or not the @finally is
476     /// running for an exception.
477     llvm::AllocaInst *ForEHVar;
478
479     /// An i8* variable into which the exception pointer to rethrow
480     /// has been saved.
481     llvm::AllocaInst *SavedExnVar;
482
483   public:
484     void enter(CodeGenFunction &CGF, const Stmt *Finally,
485                llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
486                llvm::Constant *rethrowFn);
487     void exit(CodeGenFunction &CGF);
488   };
489
490   /// Returns true inside SEH __try blocks.
491   bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
492
493   /// Returns true while emitting a cleanuppad.
494   bool isCleanupPadScope() const {
495     return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
496   }
497
498   /// pushFullExprCleanup - Push a cleanup to be run at the end of the
499   /// current full-expression.  Safe against the possibility that
500   /// we're currently inside a conditionally-evaluated expression.
501   template <class T, class... As>
502   void pushFullExprCleanup(CleanupKind kind, As... A) {
503     // If we're not in a conditional branch, or if none of the
504     // arguments requires saving, then use the unconditional cleanup.
505     if (!isInConditionalBranch())
506       return EHStack.pushCleanup<T>(kind, A...);
507
508     // Stash values in a tuple so we can guarantee the order of saves.
509     typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
510     SavedTuple Saved{saveValueInCond(A)...};
511
512     typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
513     EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
514     initFullExprCleanup();
515   }
516
517   /// \brief Queue a cleanup to be pushed after finishing the current
518   /// full-expression.
519   template <class T, class... As>
520   void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
521     assert(!isInConditionalBranch() && "can't defer conditional cleanup");
522
523     LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
524
525     size_t OldSize = LifetimeExtendedCleanupStack.size();
526     LifetimeExtendedCleanupStack.resize(
527         LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
528
529     static_assert(sizeof(Header) % alignof(T) == 0,
530                   "Cleanup will be allocated on misaligned address");
531     char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
532     new (Buffer) LifetimeExtendedCleanupHeader(Header);
533     new (Buffer + sizeof(Header)) T(A...);
534   }
535
536   /// Set up the last cleaup that was pushed as a conditional
537   /// full-expression cleanup.
538   void initFullExprCleanup();
539
540   /// PushDestructorCleanup - Push a cleanup to call the
541   /// complete-object destructor of an object of the given type at the
542   /// given address.  Does nothing if T is not a C++ class type with a
543   /// non-trivial destructor.
544   void PushDestructorCleanup(QualType T, Address Addr);
545
546   /// PushDestructorCleanup - Push a cleanup to call the
547   /// complete-object variant of the given destructor on the object at
548   /// the given address.
549   void PushDestructorCleanup(const CXXDestructorDecl *Dtor, Address Addr);
550
551   /// PopCleanupBlock - Will pop the cleanup entry on the stack and
552   /// process all branch fixups.
553   void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
554
555   /// DeactivateCleanupBlock - Deactivates the given cleanup block.
556   /// The block cannot be reactivated.  Pops it if it's the top of the
557   /// stack.
558   ///
559   /// \param DominatingIP - An instruction which is known to
560   ///   dominate the current IP (if set) and which lies along
561   ///   all paths of execution between the current IP and the
562   ///   the point at which the cleanup comes into scope.
563   void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
564                               llvm::Instruction *DominatingIP);
565
566   /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
567   /// Cannot be used to resurrect a deactivated cleanup.
568   ///
569   /// \param DominatingIP - An instruction which is known to
570   ///   dominate the current IP (if set) and which lies along
571   ///   all paths of execution between the current IP and the
572   ///   the point at which the cleanup comes into scope.
573   void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
574                             llvm::Instruction *DominatingIP);
575
576   /// \brief Enters a new scope for capturing cleanups, all of which
577   /// will be executed once the scope is exited.
578   class RunCleanupsScope {
579     EHScopeStack::stable_iterator CleanupStackDepth;
580     size_t LifetimeExtendedCleanupStackSize;
581     bool OldDidCallStackSave;
582   protected:
583     bool PerformCleanup;
584   private:
585
586     RunCleanupsScope(const RunCleanupsScope &) = delete;
587     void operator=(const RunCleanupsScope &) = delete;
588
589   protected:
590     CodeGenFunction& CGF;
591
592   public:
593     /// \brief Enter a new cleanup scope.
594     explicit RunCleanupsScope(CodeGenFunction &CGF)
595       : PerformCleanup(true), CGF(CGF)
596     {
597       CleanupStackDepth = CGF.EHStack.stable_begin();
598       LifetimeExtendedCleanupStackSize =
599           CGF.LifetimeExtendedCleanupStack.size();
600       OldDidCallStackSave = CGF.DidCallStackSave;
601       CGF.DidCallStackSave = false;
602     }
603
604     /// \brief Exit this cleanup scope, emitting any accumulated cleanups.
605     ~RunCleanupsScope() {
606       if (PerformCleanup)
607         ForceCleanup();
608     }
609
610     /// \brief Determine whether this scope requires any cleanups.
611     bool requiresCleanups() const {
612       return CGF.EHStack.stable_begin() != CleanupStackDepth;
613     }
614
615     /// \brief Force the emission of cleanups now, instead of waiting
616     /// until this object is destroyed.
617     /// \param ValuesToReload - A list of values that need to be available at
618     /// the insertion point after cleanup emission. If cleanup emission created
619     /// a shared cleanup block, these value pointers will be rewritten.
620     /// Otherwise, they not will be modified.
621     void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) {
622       assert(PerformCleanup && "Already forced cleanup");
623       CGF.DidCallStackSave = OldDidCallStackSave;
624       CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize,
625                            ValuesToReload);
626       PerformCleanup = false;
627     }
628   };
629
630   class LexicalScope : public RunCleanupsScope {
631     SourceRange Range;
632     SmallVector<const LabelDecl*, 4> Labels;
633     LexicalScope *ParentScope;
634
635     LexicalScope(const LexicalScope &) = delete;
636     void operator=(const LexicalScope &) = delete;
637
638   public:
639     /// \brief Enter a new cleanup scope.
640     explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
641       : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
642       CGF.CurLexicalScope = this;
643       if (CGDebugInfo *DI = CGF.getDebugInfo())
644         DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
645     }
646
647     void addLabel(const LabelDecl *label) {
648       assert(PerformCleanup && "adding label to dead scope?");
649       Labels.push_back(label);
650     }
651
652     /// \brief Exit this cleanup scope, emitting any accumulated
653     /// cleanups.
654     ~LexicalScope() {
655       if (CGDebugInfo *DI = CGF.getDebugInfo())
656         DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
657
658       // If we should perform a cleanup, force them now.  Note that
659       // this ends the cleanup scope before rescoping any labels.
660       if (PerformCleanup) {
661         ApplyDebugLocation DL(CGF, Range.getEnd());
662         ForceCleanup();
663       }
664     }
665
666     /// \brief Force the emission of cleanups now, instead of waiting
667     /// until this object is destroyed.
668     void ForceCleanup() {
669       CGF.CurLexicalScope = ParentScope;
670       RunCleanupsScope::ForceCleanup();
671
672       if (!Labels.empty())
673         rescopeLabels();
674     }
675
676     bool hasLabels() const {
677       return !Labels.empty();
678     }
679
680     void rescopeLabels();
681   };
682
683   typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
684
685   /// \brief The scope used to remap some variables as private in the OpenMP
686   /// loop body (or other captured region emitted without outlining), and to
687   /// restore old vars back on exit.
688   class OMPPrivateScope : public RunCleanupsScope {
689     DeclMapTy SavedLocals;
690     DeclMapTy SavedPrivates;
691
692   private:
693     OMPPrivateScope(const OMPPrivateScope &) = delete;
694     void operator=(const OMPPrivateScope &) = delete;
695
696   public:
697     /// \brief Enter a new OpenMP private scope.
698     explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
699
700     /// \brief Registers \a LocalVD variable as a private and apply \a
701     /// PrivateGen function for it to generate corresponding private variable.
702     /// \a PrivateGen returns an address of the generated private variable.
703     /// \return true if the variable is registered as private, false if it has
704     /// been privatized already.
705     bool
706     addPrivate(const VarDecl *LocalVD,
707                llvm::function_ref<Address()> PrivateGen) {
708       assert(PerformCleanup && "adding private to dead scope");
709
710       // Only save it once.
711       if (SavedLocals.count(LocalVD)) return false;
712
713       // Copy the existing local entry to SavedLocals.
714       auto it = CGF.LocalDeclMap.find(LocalVD);
715       if (it != CGF.LocalDeclMap.end()) {
716         SavedLocals.insert({LocalVD, it->second});
717       } else {
718         SavedLocals.insert({LocalVD, Address::invalid()});
719       }
720
721       // Generate the private entry.
722       Address Addr = PrivateGen();
723       QualType VarTy = LocalVD->getType();
724       if (VarTy->isReferenceType()) {
725         Address Temp = CGF.CreateMemTemp(VarTy);
726         CGF.Builder.CreateStore(Addr.getPointer(), Temp);
727         Addr = Temp;
728       }
729       SavedPrivates.insert({LocalVD, Addr});
730
731       return true;
732     }
733
734     /// \brief Privatizes local variables previously registered as private.
735     /// Registration is separate from the actual privatization to allow
736     /// initializers use values of the original variables, not the private one.
737     /// This is important, for example, if the private variable is a class
738     /// variable initialized by a constructor that references other private
739     /// variables. But at initialization original variables must be used, not
740     /// private copies.
741     /// \return true if at least one variable was privatized, false otherwise.
742     bool Privatize() {
743       copyInto(SavedPrivates, CGF.LocalDeclMap);
744       SavedPrivates.clear();
745       return !SavedLocals.empty();
746     }
747
748     void ForceCleanup() {
749       RunCleanupsScope::ForceCleanup();
750       copyInto(SavedLocals, CGF.LocalDeclMap);
751       SavedLocals.clear();
752     }
753
754     /// \brief Exit scope - all the mapped variables are restored.
755     ~OMPPrivateScope() {
756       if (PerformCleanup)
757         ForceCleanup();
758     }
759
760     /// Checks if the global variable is captured in current function. 
761     bool isGlobalVarCaptured(const VarDecl *VD) const {
762       return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
763     }
764
765   private:
766     /// Copy all the entries in the source map over the corresponding
767     /// entries in the destination, which must exist.
768     static void copyInto(const DeclMapTy &src, DeclMapTy &dest) {
769       for (auto &pair : src) {
770         if (!pair.second.isValid()) {
771           dest.erase(pair.first);
772           continue;
773         }
774
775         auto it = dest.find(pair.first);
776         if (it != dest.end()) {
777           it->second = pair.second;
778         } else {
779           dest.insert(pair);
780         }
781       }
782     }
783   };
784
785   /// \brief Takes the old cleanup stack size and emits the cleanup blocks
786   /// that have been added.
787   void
788   PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
789                    std::initializer_list<llvm::Value **> ValuesToReload = {});
790
791   /// \brief Takes the old cleanup stack size and emits the cleanup blocks
792   /// that have been added, then adds all lifetime-extended cleanups from
793   /// the given position to the stack.
794   void
795   PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
796                    size_t OldLifetimeExtendedStackSize,
797                    std::initializer_list<llvm::Value **> ValuesToReload = {});
798
799   void ResolveBranchFixups(llvm::BasicBlock *Target);
800
801   /// The given basic block lies in the current EH scope, but may be a
802   /// target of a potentially scope-crossing jump; get a stable handle
803   /// to which we can perform this jump later.
804   JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
805     return JumpDest(Target,
806                     EHStack.getInnermostNormalCleanup(),
807                     NextCleanupDestIndex++);
808   }
809
810   /// The given basic block lies in the current EH scope, but may be a
811   /// target of a potentially scope-crossing jump; get a stable handle
812   /// to which we can perform this jump later.
813   JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
814     return getJumpDestInCurrentScope(createBasicBlock(Name));
815   }
816
817   /// EmitBranchThroughCleanup - Emit a branch from the current insert
818   /// block through the normal cleanup handling code (if any) and then
819   /// on to \arg Dest.
820   void EmitBranchThroughCleanup(JumpDest Dest);
821   
822   /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
823   /// specified destination obviously has no cleanups to run.  'false' is always
824   /// a conservatively correct answer for this method.
825   bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
826
827   /// popCatchScope - Pops the catch scope at the top of the EHScope
828   /// stack, emitting any required code (other than the catch handlers
829   /// themselves).
830   void popCatchScope();
831
832   llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
833   llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
834   llvm::BasicBlock *getMSVCDispatchBlock(EHScopeStack::stable_iterator scope);
835
836   /// An object to manage conditionally-evaluated expressions.
837   class ConditionalEvaluation {
838     llvm::BasicBlock *StartBB;
839
840   public:
841     ConditionalEvaluation(CodeGenFunction &CGF)
842       : StartBB(CGF.Builder.GetInsertBlock()) {}
843
844     void begin(CodeGenFunction &CGF) {
845       assert(CGF.OutermostConditional != this);
846       if (!CGF.OutermostConditional)
847         CGF.OutermostConditional = this;
848     }
849
850     void end(CodeGenFunction &CGF) {
851       assert(CGF.OutermostConditional != nullptr);
852       if (CGF.OutermostConditional == this)
853         CGF.OutermostConditional = nullptr;
854     }
855
856     /// Returns a block which will be executed prior to each
857     /// evaluation of the conditional code.
858     llvm::BasicBlock *getStartingBlock() const {
859       return StartBB;
860     }
861   };
862
863   /// isInConditionalBranch - Return true if we're currently emitting
864   /// one branch or the other of a conditional expression.
865   bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
866
867   void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
868     assert(isInConditionalBranch());
869     llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
870     auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
871     store->setAlignment(addr.getAlignment().getQuantity());
872   }
873
874   /// An RAII object to record that we're evaluating a statement
875   /// expression.
876   class StmtExprEvaluation {
877     CodeGenFunction &CGF;
878
879     /// We have to save the outermost conditional: cleanups in a
880     /// statement expression aren't conditional just because the
881     /// StmtExpr is.
882     ConditionalEvaluation *SavedOutermostConditional;
883
884   public:
885     StmtExprEvaluation(CodeGenFunction &CGF)
886       : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
887       CGF.OutermostConditional = nullptr;
888     }
889
890     ~StmtExprEvaluation() {
891       CGF.OutermostConditional = SavedOutermostConditional;
892       CGF.EnsureInsertPoint();
893     }
894   };
895
896   /// An object which temporarily prevents a value from being
897   /// destroyed by aggressive peephole optimizations that assume that
898   /// all uses of a value have been realized in the IR.
899   class PeepholeProtection {
900     llvm::Instruction *Inst;
901     friend class CodeGenFunction;
902
903   public:
904     PeepholeProtection() : Inst(nullptr) {}
905   };
906
907   /// A non-RAII class containing all the information about a bound
908   /// opaque value.  OpaqueValueMapping, below, is a RAII wrapper for
909   /// this which makes individual mappings very simple; using this
910   /// class directly is useful when you have a variable number of
911   /// opaque values or don't want the RAII functionality for some
912   /// reason.
913   class OpaqueValueMappingData {
914     const OpaqueValueExpr *OpaqueValue;
915     bool BoundLValue;
916     CodeGenFunction::PeepholeProtection Protection;
917
918     OpaqueValueMappingData(const OpaqueValueExpr *ov,
919                            bool boundLValue)
920       : OpaqueValue(ov), BoundLValue(boundLValue) {}
921   public:
922     OpaqueValueMappingData() : OpaqueValue(nullptr) {}
923
924     static bool shouldBindAsLValue(const Expr *expr) {
925       // gl-values should be bound as l-values for obvious reasons.
926       // Records should be bound as l-values because IR generation
927       // always keeps them in memory.  Expressions of function type
928       // act exactly like l-values but are formally required to be
929       // r-values in C.
930       return expr->isGLValue() ||
931              expr->getType()->isFunctionType() ||
932              hasAggregateEvaluationKind(expr->getType());
933     }
934
935     static OpaqueValueMappingData bind(CodeGenFunction &CGF,
936                                        const OpaqueValueExpr *ov,
937                                        const Expr *e) {
938       if (shouldBindAsLValue(ov))
939         return bind(CGF, ov, CGF.EmitLValue(e));
940       return bind(CGF, ov, CGF.EmitAnyExpr(e));
941     }
942
943     static OpaqueValueMappingData bind(CodeGenFunction &CGF,
944                                        const OpaqueValueExpr *ov,
945                                        const LValue &lv) {
946       assert(shouldBindAsLValue(ov));
947       CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
948       return OpaqueValueMappingData(ov, true);
949     }
950
951     static OpaqueValueMappingData bind(CodeGenFunction &CGF,
952                                        const OpaqueValueExpr *ov,
953                                        const RValue &rv) {
954       assert(!shouldBindAsLValue(ov));
955       CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
956
957       OpaqueValueMappingData data(ov, false);
958
959       // Work around an extremely aggressive peephole optimization in
960       // EmitScalarConversion which assumes that all other uses of a
961       // value are extant.
962       data.Protection = CGF.protectFromPeepholes(rv);
963
964       return data;
965     }
966
967     bool isValid() const { return OpaqueValue != nullptr; }
968     void clear() { OpaqueValue = nullptr; }
969
970     void unbind(CodeGenFunction &CGF) {
971       assert(OpaqueValue && "no data to unbind!");
972
973       if (BoundLValue) {
974         CGF.OpaqueLValues.erase(OpaqueValue);
975       } else {
976         CGF.OpaqueRValues.erase(OpaqueValue);
977         CGF.unprotectFromPeepholes(Protection);
978       }
979     }
980   };
981
982   /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
983   class OpaqueValueMapping {
984     CodeGenFunction &CGF;
985     OpaqueValueMappingData Data;
986
987   public:
988     static bool shouldBindAsLValue(const Expr *expr) {
989       return OpaqueValueMappingData::shouldBindAsLValue(expr);
990     }
991
992     /// Build the opaque value mapping for the given conditional
993     /// operator if it's the GNU ?: extension.  This is a common
994     /// enough pattern that the convenience operator is really
995     /// helpful.
996     ///
997     OpaqueValueMapping(CodeGenFunction &CGF,
998                        const AbstractConditionalOperator *op) : CGF(CGF) {
999       if (isa<ConditionalOperator>(op))
1000         // Leave Data empty.
1001         return;
1002
1003       const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
1004       Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
1005                                           e->getCommon());
1006     }
1007
1008     /// Build the opaque value mapping for an OpaqueValueExpr whose source
1009     /// expression is set to the expression the OVE represents.
1010     OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
1011         : CGF(CGF) {
1012       if (OV) {
1013         assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
1014                                       "for OVE with no source expression");
1015         Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
1016       }
1017     }
1018
1019     OpaqueValueMapping(CodeGenFunction &CGF,
1020                        const OpaqueValueExpr *opaqueValue,
1021                        LValue lvalue)
1022       : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
1023     }
1024
1025     OpaqueValueMapping(CodeGenFunction &CGF,
1026                        const OpaqueValueExpr *opaqueValue,
1027                        RValue rvalue)
1028       : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
1029     }
1030
1031     void pop() {
1032       Data.unbind(CGF);
1033       Data.clear();
1034     }
1035
1036     ~OpaqueValueMapping() {
1037       if (Data.isValid()) Data.unbind(CGF);
1038     }
1039   };
1040   
1041 private:
1042   CGDebugInfo *DebugInfo;
1043   bool DisableDebugInfo;
1044
1045   /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
1046   /// calling llvm.stacksave for multiple VLAs in the same scope.
1047   bool DidCallStackSave;
1048
1049   /// IndirectBranch - The first time an indirect goto is seen we create a block
1050   /// with an indirect branch.  Every time we see the address of a label taken,
1051   /// we add the label to the indirect goto.  Every subsequent indirect goto is
1052   /// codegen'd as a jump to the IndirectBranch's basic block.
1053   llvm::IndirectBrInst *IndirectBranch;
1054
1055   /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
1056   /// decls.
1057   DeclMapTy LocalDeclMap;
1058
1059   /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
1060   /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
1061   /// parameter.
1062   llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
1063       SizeArguments;
1064
1065   /// Track escaped local variables with auto storage. Used during SEH
1066   /// outlining to produce a call to llvm.localescape.
1067   llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
1068
1069   /// LabelMap - This keeps track of the LLVM basic block for each C label.
1070   llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
1071
1072   // BreakContinueStack - This keeps track of where break and continue
1073   // statements should jump to.
1074   struct BreakContinue {
1075     BreakContinue(JumpDest Break, JumpDest Continue)
1076       : BreakBlock(Break), ContinueBlock(Continue) {}
1077
1078     JumpDest BreakBlock;
1079     JumpDest ContinueBlock;
1080   };
1081   SmallVector<BreakContinue, 8> BreakContinueStack;
1082
1083   /// Handles cancellation exit points in OpenMP-related constructs.
1084   class OpenMPCancelExitStack {
1085     /// Tracks cancellation exit point and join point for cancel-related exit
1086     /// and normal exit.
1087     struct CancelExit {
1088       CancelExit() = default;
1089       CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
1090                  JumpDest ContBlock)
1091           : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
1092       OpenMPDirectiveKind Kind = OMPD_unknown;
1093       /// true if the exit block has been emitted already by the special
1094       /// emitExit() call, false if the default codegen is used.
1095       bool HasBeenEmitted = false;
1096       JumpDest ExitBlock;
1097       JumpDest ContBlock;
1098     };
1099
1100     SmallVector<CancelExit, 8> Stack;
1101
1102   public:
1103     OpenMPCancelExitStack() : Stack(1) {}
1104     ~OpenMPCancelExitStack() = default;
1105     /// Fetches the exit block for the current OpenMP construct.
1106     JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
1107     /// Emits exit block with special codegen procedure specific for the related
1108     /// OpenMP construct + emits code for normal construct cleanup.
1109     void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1110                   const llvm::function_ref<void(CodeGenFunction &)> &CodeGen) {
1111       if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
1112         assert(CGF.getOMPCancelDestination(Kind).isValid());
1113         assert(CGF.HaveInsertPoint());
1114         assert(!Stack.back().HasBeenEmitted);
1115         auto IP = CGF.Builder.saveAndClearIP();
1116         CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1117         CodeGen(CGF);
1118         CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1119         CGF.Builder.restoreIP(IP);
1120         Stack.back().HasBeenEmitted = true;
1121       }
1122       CodeGen(CGF);
1123     }
1124     /// Enter the cancel supporting \a Kind construct.
1125     /// \param Kind OpenMP directive that supports cancel constructs.
1126     /// \param HasCancel true, if the construct has inner cancel directive,
1127     /// false otherwise.
1128     void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
1129       Stack.push_back({Kind,
1130                        HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
1131                                  : JumpDest(),
1132                        HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
1133                                  : JumpDest()});
1134     }
1135     /// Emits default exit point for the cancel construct (if the special one
1136     /// has not be used) + join point for cancel/normal exits.
1137     void exit(CodeGenFunction &CGF) {
1138       if (getExitBlock().isValid()) {
1139         assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
1140         bool HaveIP = CGF.HaveInsertPoint();
1141         if (!Stack.back().HasBeenEmitted) {
1142           if (HaveIP)
1143             CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1144           CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1145           CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1146         }
1147         CGF.EmitBlock(Stack.back().ContBlock.getBlock());
1148         if (!HaveIP) {
1149           CGF.Builder.CreateUnreachable();
1150           CGF.Builder.ClearInsertionPoint();
1151         }
1152       }
1153       Stack.pop_back();
1154     }
1155   };
1156   OpenMPCancelExitStack OMPCancelStack;
1157
1158   /// Controls insertion of cancellation exit blocks in worksharing constructs.
1159   class OMPCancelStackRAII {
1160     CodeGenFunction &CGF;
1161
1162   public:
1163     OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1164                        bool HasCancel)
1165         : CGF(CGF) {
1166       CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
1167     }
1168     ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
1169   };
1170
1171   CodeGenPGO PGO;
1172
1173   /// Calculate branch weights appropriate for PGO data
1174   llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
1175   llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
1176   llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1177                                             uint64_t LoopCount);
1178
1179 public:
1180   /// Increment the profiler's counter for the given statement by \p StepV.
1181   /// If \p StepV is null, the default increment is 1.
1182   void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
1183     if (CGM.getCodeGenOpts().hasProfileClangInstr())
1184       PGO.emitCounterIncrement(Builder, S, StepV);
1185     PGO.setCurrentStmt(S);
1186   }
1187
1188   /// Get the profiler's count for the given statement.
1189   uint64_t getProfileCount(const Stmt *S) {
1190     Optional<uint64_t> Count = PGO.getStmtCount(S);
1191     if (!Count.hasValue())
1192       return 0;
1193     return *Count;
1194   }
1195
1196   /// Set the profiler's current count.
1197   void setCurrentProfileCount(uint64_t Count) {
1198     PGO.setCurrentRegionCount(Count);
1199   }
1200
1201   /// Get the profiler's current count. This is generally the count for the most
1202   /// recently incremented counter.
1203   uint64_t getCurrentProfileCount() {
1204     return PGO.getCurrentRegionCount();
1205   }
1206
1207 private:
1208
1209   /// SwitchInsn - This is nearest current switch instruction. It is null if
1210   /// current context is not in a switch.
1211   llvm::SwitchInst *SwitchInsn;
1212   /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1213   SmallVector<uint64_t, 16> *SwitchWeights;
1214
1215   /// CaseRangeBlock - This block holds if condition check for last case
1216   /// statement range in current switch instruction.
1217   llvm::BasicBlock *CaseRangeBlock;
1218
1219   /// OpaqueLValues - Keeps track of the current set of opaque value
1220   /// expressions.
1221   llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1222   llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1223
1224   // VLASizeMap - This keeps track of the associated size for each VLA type.
1225   // We track this by the size expression rather than the type itself because
1226   // in certain situations, like a const qualifier applied to an VLA typedef,
1227   // multiple VLA types can share the same size expression.
1228   // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1229   // enter/leave scopes.
1230   llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
1231
1232   /// A block containing a single 'unreachable' instruction.  Created
1233   /// lazily by getUnreachableBlock().
1234   llvm::BasicBlock *UnreachableBlock;
1235
1236   /// Counts of the number return expressions in the function.
1237   unsigned NumReturnExprs;
1238
1239   /// Count the number of simple (constant) return expressions in the function.
1240   unsigned NumSimpleReturnExprs;
1241
1242   /// The last regular (non-return) debug location (breakpoint) in the function.
1243   SourceLocation LastStopPoint;
1244
1245 public:
1246   /// A scope within which we are constructing the fields of an object which
1247   /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1248   /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1249   class FieldConstructionScope {
1250   public:
1251     FieldConstructionScope(CodeGenFunction &CGF, Address This)
1252         : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1253       CGF.CXXDefaultInitExprThis = This;
1254     }
1255     ~FieldConstructionScope() {
1256       CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1257     }
1258
1259   private:
1260     CodeGenFunction &CGF;
1261     Address OldCXXDefaultInitExprThis;
1262   };
1263
1264   /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1265   /// is overridden to be the object under construction.
1266   class CXXDefaultInitExprScope {
1267   public:
1268     CXXDefaultInitExprScope(CodeGenFunction &CGF)
1269       : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1270         OldCXXThisAlignment(CGF.CXXThisAlignment) {
1271       CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
1272       CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
1273     }
1274     ~CXXDefaultInitExprScope() {
1275       CGF.CXXThisValue = OldCXXThisValue;
1276       CGF.CXXThisAlignment = OldCXXThisAlignment;
1277     }
1278
1279   public:
1280     CodeGenFunction &CGF;
1281     llvm::Value *OldCXXThisValue;
1282     CharUnits OldCXXThisAlignment;
1283   };
1284
1285   /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1286   /// current loop index is overridden.
1287   class ArrayInitLoopExprScope {
1288   public:
1289     ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
1290       : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
1291       CGF.ArrayInitIndex = Index;
1292     }
1293     ~ArrayInitLoopExprScope() {
1294       CGF.ArrayInitIndex = OldArrayInitIndex;
1295     }
1296
1297   private:
1298     CodeGenFunction &CGF;
1299     llvm::Value *OldArrayInitIndex;
1300   };
1301
1302   class InlinedInheritingConstructorScope {
1303   public:
1304     InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
1305         : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1306           OldCurCodeDecl(CGF.CurCodeDecl),
1307           OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1308           OldCXXABIThisValue(CGF.CXXABIThisValue),
1309           OldCXXThisValue(CGF.CXXThisValue),
1310           OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1311           OldCXXThisAlignment(CGF.CXXThisAlignment),
1312           OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1313           OldCXXInheritedCtorInitExprArgs(
1314               std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1315       CGF.CurGD = GD;
1316       CGF.CurFuncDecl = CGF.CurCodeDecl =
1317           cast<CXXConstructorDecl>(GD.getDecl());
1318       CGF.CXXABIThisDecl = nullptr;
1319       CGF.CXXABIThisValue = nullptr;
1320       CGF.CXXThisValue = nullptr;
1321       CGF.CXXABIThisAlignment = CharUnits();
1322       CGF.CXXThisAlignment = CharUnits();
1323       CGF.ReturnValue = Address::invalid();
1324       CGF.FnRetTy = QualType();
1325       CGF.CXXInheritedCtorInitExprArgs.clear();
1326     }
1327     ~InlinedInheritingConstructorScope() {
1328       CGF.CurGD = OldCurGD;
1329       CGF.CurFuncDecl = OldCurFuncDecl;
1330       CGF.CurCodeDecl = OldCurCodeDecl;
1331       CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1332       CGF.CXXABIThisValue = OldCXXABIThisValue;
1333       CGF.CXXThisValue = OldCXXThisValue;
1334       CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1335       CGF.CXXThisAlignment = OldCXXThisAlignment;
1336       CGF.ReturnValue = OldReturnValue;
1337       CGF.FnRetTy = OldFnRetTy;
1338       CGF.CXXInheritedCtorInitExprArgs =
1339           std::move(OldCXXInheritedCtorInitExprArgs);
1340     }
1341
1342   private:
1343     CodeGenFunction &CGF;
1344     GlobalDecl OldCurGD;
1345     const Decl *OldCurFuncDecl;
1346     const Decl *OldCurCodeDecl;
1347     ImplicitParamDecl *OldCXXABIThisDecl;
1348     llvm::Value *OldCXXABIThisValue;
1349     llvm::Value *OldCXXThisValue;
1350     CharUnits OldCXXABIThisAlignment;
1351     CharUnits OldCXXThisAlignment;
1352     Address OldReturnValue;
1353     QualType OldFnRetTy;
1354     CallArgList OldCXXInheritedCtorInitExprArgs;
1355   };
1356
1357 private:
1358   /// CXXThisDecl - When generating code for a C++ member function,
1359   /// this will hold the implicit 'this' declaration.
1360   ImplicitParamDecl *CXXABIThisDecl;
1361   llvm::Value *CXXABIThisValue;
1362   llvm::Value *CXXThisValue;
1363   CharUnits CXXABIThisAlignment;
1364   CharUnits CXXThisAlignment;
1365
1366   /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1367   /// this expression.
1368   Address CXXDefaultInitExprThis = Address::invalid();
1369
1370   /// The current array initialization index when evaluating an
1371   /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
1372   llvm::Value *ArrayInitIndex = nullptr;
1373
1374   /// The values of function arguments to use when evaluating
1375   /// CXXInheritedCtorInitExprs within this context.
1376   CallArgList CXXInheritedCtorInitExprArgs;
1377
1378   /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1379   /// destructor, this will hold the implicit argument (e.g. VTT).
1380   ImplicitParamDecl *CXXStructorImplicitParamDecl;
1381   llvm::Value *CXXStructorImplicitParamValue;
1382
1383   /// OutermostConditional - Points to the outermost active
1384   /// conditional control.  This is used so that we know if a
1385   /// temporary should be destroyed conditionally.
1386   ConditionalEvaluation *OutermostConditional;
1387
1388   /// The current lexical scope.
1389   LexicalScope *CurLexicalScope;
1390
1391   /// The current source location that should be used for exception
1392   /// handling code.
1393   SourceLocation CurEHLocation;
1394
1395   /// BlockByrefInfos - For each __block variable, contains
1396   /// information about the layout of the variable.
1397   llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
1398
1399   /// Used by -fsanitize=nullability-return to determine whether the return
1400   /// value can be checked.
1401   llvm::Value *RetValNullabilityPrecondition = nullptr;
1402
1403   /// Check if -fsanitize=nullability-return instrumentation is required for
1404   /// this function.
1405   bool requiresReturnValueNullabilityCheck() const {
1406     return RetValNullabilityPrecondition;
1407   }
1408
1409   llvm::BasicBlock *TerminateLandingPad;
1410   llvm::BasicBlock *TerminateHandler;
1411   llvm::BasicBlock *TrapBB;
1412
1413   /// True if we need emit the life-time markers.
1414   const bool ShouldEmitLifetimeMarkers;
1415
1416   /// Add OpenCL kernel arg metadata and the kernel attribute meatadata to
1417   /// the function metadata.
1418   void EmitOpenCLKernelMetadata(const FunctionDecl *FD, 
1419                                 llvm::Function *Fn);
1420
1421 public:
1422   CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
1423   ~CodeGenFunction();
1424
1425   CodeGenTypes &getTypes() const { return CGM.getTypes(); }
1426   ASTContext &getContext() const { return CGM.getContext(); }
1427   CGDebugInfo *getDebugInfo() { 
1428     if (DisableDebugInfo) 
1429       return nullptr;
1430     return DebugInfo; 
1431   }
1432   void disableDebugInfo() { DisableDebugInfo = true; }
1433   void enableDebugInfo() { DisableDebugInfo = false; }
1434
1435   bool shouldUseFusedARCCalls() {
1436     return CGM.getCodeGenOpts().OptimizationLevel == 0;
1437   }
1438
1439   const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
1440
1441   /// Returns a pointer to the function's exception object and selector slot,
1442   /// which is assigned in every landing pad.
1443   Address getExceptionSlot();
1444   Address getEHSelectorSlot();
1445
1446   /// Returns the contents of the function's exception object and selector
1447   /// slots.
1448   llvm::Value *getExceptionFromSlot();
1449   llvm::Value *getSelectorFromSlot();
1450
1451   Address getNormalCleanupDestSlot();
1452
1453   llvm::BasicBlock *getUnreachableBlock() {
1454     if (!UnreachableBlock) {
1455       UnreachableBlock = createBasicBlock("unreachable");
1456       new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
1457     }
1458     return UnreachableBlock;
1459   }
1460
1461   llvm::BasicBlock *getInvokeDest() {
1462     if (!EHStack.requiresLandingPad()) return nullptr;
1463     return getInvokeDestImpl();
1464   }
1465
1466   bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
1467
1468   const TargetInfo &getTarget() const { return Target; }
1469   llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
1470
1471   //===--------------------------------------------------------------------===//
1472   //                                  Cleanups
1473   //===--------------------------------------------------------------------===//
1474
1475   typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
1476
1477   void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1478                                         Address arrayEndPointer,
1479                                         QualType elementType,
1480                                         CharUnits elementAlignment,
1481                                         Destroyer *destroyer);
1482   void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1483                                       llvm::Value *arrayEnd,
1484                                       QualType elementType,
1485                                       CharUnits elementAlignment,
1486                                       Destroyer *destroyer);
1487
1488   void pushDestroy(QualType::DestructionKind dtorKind,
1489                    Address addr, QualType type);
1490   void pushEHDestroy(QualType::DestructionKind dtorKind,
1491                      Address addr, QualType type);
1492   void pushDestroy(CleanupKind kind, Address addr, QualType type,
1493                    Destroyer *destroyer, bool useEHCleanupForArray);
1494   void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
1495                                    QualType type, Destroyer *destroyer,
1496                                    bool useEHCleanupForArray);
1497   void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1498                                    llvm::Value *CompletePtr,
1499                                    QualType ElementType);
1500   void pushStackRestore(CleanupKind kind, Address SPMem);
1501   void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
1502                    bool useEHCleanupForArray);
1503   llvm::Function *generateDestroyHelper(Address addr, QualType type,
1504                                         Destroyer *destroyer,
1505                                         bool useEHCleanupForArray,
1506                                         const VarDecl *VD);
1507   void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
1508                         QualType elementType, CharUnits elementAlign,
1509                         Destroyer *destroyer,
1510                         bool checkZeroLength, bool useEHCleanup);
1511
1512   Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
1513
1514   /// Determines whether an EH cleanup is required to destroy a type
1515   /// with the given destruction kind.
1516   bool needsEHCleanup(QualType::DestructionKind kind) {
1517     switch (kind) {
1518     case QualType::DK_none:
1519       return false;
1520     case QualType::DK_cxx_destructor:
1521     case QualType::DK_objc_weak_lifetime:
1522       return getLangOpts().Exceptions;
1523     case QualType::DK_objc_strong_lifetime:
1524       return getLangOpts().Exceptions &&
1525              CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1526     }
1527     llvm_unreachable("bad destruction kind");
1528   }
1529
1530   CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1531     return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1532   }
1533
1534   //===--------------------------------------------------------------------===//
1535   //                                  Objective-C
1536   //===--------------------------------------------------------------------===//
1537
1538   void GenerateObjCMethod(const ObjCMethodDecl *OMD);
1539
1540   void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
1541
1542   /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
1543   void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1544                           const ObjCPropertyImplDecl *PID);
1545   void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1546                               const ObjCPropertyImplDecl *propImpl,
1547                               const ObjCMethodDecl *GetterMothodDecl,
1548                               llvm::Constant *AtomicHelperFn);
1549
1550   void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1551                                   ObjCMethodDecl *MD, bool ctor);
1552
1553   /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1554   /// for the given property.
1555   void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1556                           const ObjCPropertyImplDecl *PID);
1557   void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1558                               const ObjCPropertyImplDecl *propImpl,
1559                               llvm::Constant *AtomicHelperFn);
1560
1561   //===--------------------------------------------------------------------===//
1562   //                                  Block Bits
1563   //===--------------------------------------------------------------------===//
1564
1565   llvm::Value *EmitBlockLiteral(const BlockExpr *);
1566   static void destroyBlockInfos(CGBlockInfo *info);
1567
1568   llvm::Function *GenerateBlockFunction(GlobalDecl GD,
1569                                         const CGBlockInfo &Info,
1570                                         const DeclMapTy &ldm,
1571                                         bool IsLambdaConversionToBlock);
1572
1573   llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1574   llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
1575   llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
1576                                              const ObjCPropertyImplDecl *PID);
1577   llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
1578                                              const ObjCPropertyImplDecl *PID);
1579   llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
1580
1581   void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
1582
1583   class AutoVarEmission;
1584
1585   void emitByrefStructureInit(const AutoVarEmission &emission);
1586   void enterByrefCleanup(const AutoVarEmission &emission);
1587
1588   void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
1589                                 llvm::Value *ptr);
1590
1591   Address LoadBlockStruct();
1592   Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
1593
1594   /// BuildBlockByrefAddress - Computes the location of the
1595   /// data in a variable which is declared as __block.
1596   Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
1597                                 bool followForward = true);
1598   Address emitBlockByrefAddress(Address baseAddr,
1599                                 const BlockByrefInfo &info,
1600                                 bool followForward,
1601                                 const llvm::Twine &name);
1602
1603   const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
1604
1605   QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
1606
1607   void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1608                     const CGFunctionInfo &FnInfo);
1609   /// \brief Emit code for the start of a function.
1610   /// \param Loc       The location to be associated with the function.
1611   /// \param StartLoc  The location of the function body.
1612   void StartFunction(GlobalDecl GD,
1613                      QualType RetTy,
1614                      llvm::Function *Fn,
1615                      const CGFunctionInfo &FnInfo,
1616                      const FunctionArgList &Args,
1617                      SourceLocation Loc = SourceLocation(),
1618                      SourceLocation StartLoc = SourceLocation());
1619
1620   static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
1621
1622   void EmitConstructorBody(FunctionArgList &Args);
1623   void EmitDestructorBody(FunctionArgList &Args);
1624   void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
1625   void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
1626   void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
1627
1628   void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
1629                                   CallArgList &CallArgs);
1630   void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
1631   void EmitLambdaBlockInvokeBody();
1632   void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
1633   void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
1634   void EmitAsanPrologueOrEpilogue(bool Prologue);
1635
1636   /// \brief Emit the unified return block, trying to avoid its emission when
1637   /// possible.
1638   /// \return The debug location of the user written return statement if the
1639   /// return block is is avoided.
1640   llvm::DebugLoc EmitReturnBlock();
1641
1642   /// FinishFunction - Complete IR generation of the current function. It is
1643   /// legal to call this function even if there is no current insertion point.
1644   void FinishFunction(SourceLocation EndLoc=SourceLocation());
1645
1646   void StartThunk(llvm::Function *Fn, GlobalDecl GD,
1647                   const CGFunctionInfo &FnInfo);
1648
1649   void EmitCallAndReturnForThunk(llvm::Constant *Callee,
1650                                  const ThunkInfo *Thunk);
1651
1652   void FinishThunk();
1653
1654   /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
1655   void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
1656                          llvm::Value *Callee);
1657
1658   /// Generate a thunk for the given method.
1659   void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1660                      GlobalDecl GD, const ThunkInfo &Thunk);
1661
1662   llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
1663                                        const CGFunctionInfo &FnInfo,
1664                                        GlobalDecl GD, const ThunkInfo &Thunk);
1665
1666   void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1667                         FunctionArgList &Args);
1668
1669   void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
1670
1671   /// Struct with all informations about dynamic [sub]class needed to set vptr.
1672   struct VPtr {
1673     BaseSubobject Base;
1674     const CXXRecordDecl *NearestVBase;
1675     CharUnits OffsetFromNearestVBase;
1676     const CXXRecordDecl *VTableClass;
1677   };
1678
1679   /// Initialize the vtable pointer of the given subobject.
1680   void InitializeVTablePointer(const VPtr &vptr);
1681
1682   typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
1683
1684   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1685   VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
1686
1687   void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
1688                          CharUnits OffsetFromNearestVBase,
1689                          bool BaseIsNonVirtualPrimaryBase,
1690                          const CXXRecordDecl *VTableClass,
1691                          VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
1692
1693   void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1694
1695   /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1696   /// to by This.
1697   llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
1698                             const CXXRecordDecl *VTableClass);
1699
1700   enum CFITypeCheckKind {
1701     CFITCK_VCall,
1702     CFITCK_NVCall,
1703     CFITCK_DerivedCast,
1704     CFITCK_UnrelatedCast,
1705     CFITCK_ICall,
1706   };
1707
1708   /// \brief Derived is the presumed address of an object of type T after a
1709   /// cast. If T is a polymorphic class type, emit a check that the virtual
1710   /// table for Derived belongs to a class derived from T.
1711   void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
1712                                  bool MayBeNull, CFITypeCheckKind TCK,
1713                                  SourceLocation Loc);
1714
1715   /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
1716   /// If vptr CFI is enabled, emit a check that VTable is valid.
1717   void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
1718                                  CFITypeCheckKind TCK, SourceLocation Loc);
1719
1720   /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
1721   /// RD using llvm.type.test.
1722   void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
1723                           CFITypeCheckKind TCK, SourceLocation Loc);
1724
1725   /// If whole-program virtual table optimization is enabled, emit an assumption
1726   /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
1727   /// enabled, emit a check that VTable is a member of RD's type identifier.
1728   void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
1729                                     llvm::Value *VTable, SourceLocation Loc);
1730
1731   /// Returns whether we should perform a type checked load when loading a
1732   /// virtual function for virtual calls to members of RD. This is generally
1733   /// true when both vcall CFI and whole-program-vtables are enabled.
1734   bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
1735
1736   /// Emit a type checked load from the given vtable.
1737   llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
1738                                          uint64_t VTableByteOffset);
1739
1740   /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
1741   /// expr can be devirtualized.
1742   bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
1743                                          const CXXMethodDecl *MD);
1744
1745   /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1746   /// given phase of destruction for a destructor.  The end result
1747   /// should call destructors on members and base classes in reverse
1748   /// order of their construction.
1749   void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1750
1751   /// ShouldInstrumentFunction - Return true if the current function should be
1752   /// instrumented with __cyg_profile_func_* calls
1753   bool ShouldInstrumentFunction();
1754
1755   /// ShouldXRayInstrument - Return true if the current function should be
1756   /// instrumented with XRay nop sleds.
1757   bool ShouldXRayInstrumentFunction() const;
1758
1759   /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
1760   /// instrumentation function with the current function and the call site, if
1761   /// function instrumentation is enabled.
1762   void EmitFunctionInstrumentation(const char *Fn);
1763
1764   /// EmitMCountInstrumentation - Emit call to .mcount.
1765   void EmitMCountInstrumentation();
1766
1767   /// EmitFunctionProlog - Emit the target specific LLVM code to load the
1768   /// arguments for the given function. This is also responsible for naming the
1769   /// LLVM function arguments.
1770   void EmitFunctionProlog(const CGFunctionInfo &FI,
1771                           llvm::Function *Fn,
1772                           const FunctionArgList &Args);
1773
1774   /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
1775   /// given temporary.
1776   void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
1777                           SourceLocation EndLoc);
1778
1779   /// Emit a test that checks if the return value \p RV is nonnull.
1780   void EmitReturnValueCheck(llvm::Value *RV, SourceLocation EndLoc);
1781
1782   /// EmitStartEHSpec - Emit the start of the exception spec.
1783   void EmitStartEHSpec(const Decl *D);
1784
1785   /// EmitEndEHSpec - Emit the end of the exception spec.
1786   void EmitEndEHSpec(const Decl *D);
1787
1788   /// getTerminateLandingPad - Return a landing pad that just calls terminate.
1789   llvm::BasicBlock *getTerminateLandingPad();
1790
1791   /// getTerminateHandler - Return a handler (not a landing pad, just
1792   /// a catch handler) that just calls terminate.  This is used when
1793   /// a terminate scope encloses a try.
1794   llvm::BasicBlock *getTerminateHandler();
1795
1796   llvm::Type *ConvertTypeForMem(QualType T);
1797   llvm::Type *ConvertType(QualType T);
1798   llvm::Type *ConvertType(const TypeDecl *T) {
1799     return ConvertType(getContext().getTypeDeclType(T));
1800   }
1801
1802   /// LoadObjCSelf - Load the value of self. This function is only valid while
1803   /// generating code for an Objective-C method.
1804   llvm::Value *LoadObjCSelf();
1805
1806   /// TypeOfSelfObject - Return type of object that this self represents.
1807   QualType TypeOfSelfObject();
1808
1809   /// hasAggregateLLVMType - Return true if the specified AST type will map into
1810   /// an aggregate LLVM type or is void.
1811   static TypeEvaluationKind getEvaluationKind(QualType T);
1812
1813   static bool hasScalarEvaluationKind(QualType T) {
1814     return getEvaluationKind(T) == TEK_Scalar;
1815   }
1816
1817   static bool hasAggregateEvaluationKind(QualType T) {
1818     return getEvaluationKind(T) == TEK_Aggregate;
1819   }
1820
1821   /// createBasicBlock - Create an LLVM basic block.
1822   llvm::BasicBlock *createBasicBlock(const Twine &name = "",
1823                                      llvm::Function *parent = nullptr,
1824                                      llvm::BasicBlock *before = nullptr) {
1825 #ifdef NDEBUG
1826     return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
1827 #else
1828     return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
1829 #endif
1830   }
1831
1832   /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
1833   /// label maps to.
1834   JumpDest getJumpDestForLabel(const LabelDecl *S);
1835
1836   /// SimplifyForwardingBlocks - If the given basic block is only a branch to
1837   /// another basic block, simplify it. This assumes that no other code could
1838   /// potentially reference the basic block.
1839   void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
1840
1841   /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
1842   /// adding a fall-through branch from the current insert block if
1843   /// necessary. It is legal to call this function even if there is no current
1844   /// insertion point.
1845   ///
1846   /// IsFinished - If true, indicates that the caller has finished emitting
1847   /// branches to the given block and does not expect to emit code into it. This
1848   /// means the block can be ignored if it is unreachable.
1849   void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
1850
1851   /// EmitBlockAfterUses - Emit the given block somewhere hopefully
1852   /// near its uses, and leave the insertion point in it.
1853   void EmitBlockAfterUses(llvm::BasicBlock *BB);
1854
1855   /// EmitBranch - Emit a branch to the specified basic block from the current
1856   /// insert block, taking care to avoid creation of branches from dummy
1857   /// blocks. It is legal to call this function even if there is no current
1858   /// insertion point.
1859   ///
1860   /// This function clears the current insertion point. The caller should follow
1861   /// calls to this function with calls to Emit*Block prior to generation new
1862   /// code.
1863   void EmitBranch(llvm::BasicBlock *Block);
1864
1865   /// HaveInsertPoint - True if an insertion point is defined. If not, this
1866   /// indicates that the current code being emitted is unreachable.
1867   bool HaveInsertPoint() const {
1868     return Builder.GetInsertBlock() != nullptr;
1869   }
1870
1871   /// EnsureInsertPoint - Ensure that an insertion point is defined so that
1872   /// emitted IR has a place to go. Note that by definition, if this function
1873   /// creates a block then that block is unreachable; callers may do better to
1874   /// detect when no insertion point is defined and simply skip IR generation.
1875   void EnsureInsertPoint() {
1876     if (!HaveInsertPoint())
1877       EmitBlock(createBasicBlock());
1878   }
1879
1880   /// ErrorUnsupported - Print out an error that codegen doesn't support the
1881   /// specified stmt yet.
1882   void ErrorUnsupported(const Stmt *S, const char *Type);
1883
1884   //===--------------------------------------------------------------------===//
1885   //                                  Helpers
1886   //===--------------------------------------------------------------------===//
1887
1888   LValue MakeAddrLValue(Address Addr, QualType T,
1889                         AlignmentSource AlignSource = AlignmentSource::Type) {
1890     return LValue::MakeAddr(Addr, T, getContext(), AlignSource,
1891                             CGM.getTBAAInfo(T));
1892   }
1893
1894   LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
1895                         AlignmentSource AlignSource = AlignmentSource::Type) {
1896     return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
1897                             AlignSource, CGM.getTBAAInfo(T));
1898   }
1899
1900   LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
1901   LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
1902   CharUnits getNaturalTypeAlignment(QualType T,
1903                                     AlignmentSource *Source = nullptr,
1904                                     bool forPointeeType = false);
1905   CharUnits getNaturalPointeeTypeAlignment(QualType T,
1906                                            AlignmentSource *Source = nullptr);
1907
1908   Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy,
1909                               AlignmentSource *Source = nullptr);
1910   LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy);
1911
1912   Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
1913                             AlignmentSource *Source = nullptr);
1914   LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
1915
1916   /// CreateTempAlloca - This creates a alloca and inserts it into the entry
1917   /// block. The caller is responsible for setting an appropriate alignment on
1918   /// the alloca.
1919   llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
1920                                      const Twine &Name = "tmp");
1921   Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
1922                            const Twine &Name = "tmp");
1923
1924   /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
1925   /// default ABI alignment of the given LLVM type.
1926   ///
1927   /// IMPORTANT NOTE: This is *not* generally the right alignment for
1928   /// any given AST type that happens to have been lowered to the
1929   /// given IR type.  This should only ever be used for function-local,
1930   /// IR-driven manipulations like saving and restoring a value.  Do
1931   /// not hand this address off to arbitrary IRGen routines, and especially
1932   /// do not pass it as an argument to a function that might expect a
1933   /// properly ABI-aligned value.
1934   Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
1935                                        const Twine &Name = "tmp");
1936
1937   /// InitTempAlloca - Provide an initial value for the given alloca which
1938   /// will be observable at all locations in the function.
1939   ///
1940   /// The address should be something that was returned from one of
1941   /// the CreateTempAlloca or CreateMemTemp routines, and the
1942   /// initializer must be valid in the entry block (i.e. it must
1943   /// either be a constant or an argument value).
1944   void InitTempAlloca(Address Alloca, llvm::Value *Value);
1945
1946   /// CreateIRTemp - Create a temporary IR object of the given type, with
1947   /// appropriate alignment. This routine should only be used when an temporary
1948   /// value needs to be stored into an alloca (for example, to avoid explicit
1949   /// PHI construction), but the type is the IR type, not the type appropriate
1950   /// for storing in memory.
1951   ///
1952   /// That is, this is exactly equivalent to CreateMemTemp, but calling
1953   /// ConvertType instead of ConvertTypeForMem.
1954   Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
1955
1956   /// CreateMemTemp - Create a temporary memory object of the given type, with
1957   /// appropriate alignment.
1958   Address CreateMemTemp(QualType T, const Twine &Name = "tmp");
1959   Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp");
1960
1961   /// CreateAggTemp - Create a temporary memory object for the given
1962   /// aggregate type.
1963   AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
1964     return AggValueSlot::forAddr(CreateMemTemp(T, Name),
1965                                  T.getQualifiers(),
1966                                  AggValueSlot::IsNotDestructed,
1967                                  AggValueSlot::DoesNotNeedGCBarriers,
1968                                  AggValueSlot::IsNotAliased);
1969   }
1970
1971   /// Emit a cast to void* in the appropriate address space.
1972   llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
1973
1974   /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1975   /// expression and compare the result against zero, returning an Int1Ty value.
1976   llvm::Value *EvaluateExprAsBool(const Expr *E);
1977
1978   /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1979   void EmitIgnoredExpr(const Expr *E);
1980
1981   /// EmitAnyExpr - Emit code to compute the specified expression which can have
1982   /// any type.  The result is returned as an RValue struct.  If this is an
1983   /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1984   /// the result should be returned.
1985   ///
1986   /// \param ignoreResult True if the resulting value isn't used.
1987   RValue EmitAnyExpr(const Expr *E,
1988                      AggValueSlot aggSlot = AggValueSlot::ignored(),
1989                      bool ignoreResult = false);
1990
1991   // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1992   // or the value of the expression, depending on how va_list is defined.
1993   Address EmitVAListRef(const Expr *E);
1994
1995   /// Emit a "reference" to a __builtin_ms_va_list; this is
1996   /// always the value of the expression, because a __builtin_ms_va_list is a
1997   /// pointer to a char.
1998   Address EmitMSVAListRef(const Expr *E);
1999
2000   /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
2001   /// always be accessible even if no aggregate location is provided.
2002   RValue EmitAnyExprToTemp(const Expr *E);
2003
2004   /// EmitAnyExprToMem - Emits the code necessary to evaluate an
2005   /// arbitrary expression into the given memory location.
2006   void EmitAnyExprToMem(const Expr *E, Address Location,
2007                         Qualifiers Quals, bool IsInitializer);
2008
2009   void EmitAnyExprToExn(const Expr *E, Address Addr);
2010
2011   /// EmitExprAsInit - Emits the code necessary to initialize a
2012   /// location in memory with the given initializer.
2013   void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2014                       bool capturedByInit);
2015
2016   /// hasVolatileMember - returns true if aggregate type has a volatile
2017   /// member.
2018   bool hasVolatileMember(QualType T) {
2019     if (const RecordType *RT = T->getAs<RecordType>()) {
2020       const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2021       return RD->hasVolatileMember();
2022     }
2023     return false;
2024   }
2025   /// EmitAggregateCopy - Emit an aggregate assignment.
2026   ///
2027   /// The difference to EmitAggregateCopy is that tail padding is not copied.
2028   /// This is required for correctness when assigning non-POD structures in C++.
2029   void EmitAggregateAssign(Address DestPtr, Address SrcPtr,
2030                            QualType EltTy) {
2031     bool IsVolatile = hasVolatileMember(EltTy);
2032     EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true);
2033   }
2034
2035   void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr,
2036                              QualType DestTy, QualType SrcTy) {
2037     EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
2038                       /*IsAssignment=*/false);
2039   }
2040
2041   /// EmitAggregateCopy - Emit an aggregate copy.
2042   ///
2043   /// \param isVolatile - True iff either the source or the destination is
2044   /// volatile.
2045   /// \param isAssignment - If false, allow padding to be copied.  This often
2046   /// yields more efficient.
2047   void EmitAggregateCopy(Address DestPtr, Address SrcPtr,
2048                          QualType EltTy, bool isVolatile=false,
2049                          bool isAssignment = false);
2050
2051   /// GetAddrOfLocalVar - Return the address of a local variable.
2052   Address GetAddrOfLocalVar(const VarDecl *VD) {
2053     auto it = LocalDeclMap.find(VD);
2054     assert(it != LocalDeclMap.end() &&
2055            "Invalid argument to GetAddrOfLocalVar(), no decl!");
2056     return it->second;
2057   }
2058
2059   /// getOpaqueLValueMapping - Given an opaque value expression (which
2060   /// must be mapped to an l-value), return its mapping.
2061   const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
2062     assert(OpaqueValueMapping::shouldBindAsLValue(e));
2063
2064     llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
2065       it = OpaqueLValues.find(e);
2066     assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
2067     return it->second;
2068   }
2069
2070   /// getOpaqueRValueMapping - Given an opaque value expression (which
2071   /// must be mapped to an r-value), return its mapping.
2072   const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
2073     assert(!OpaqueValueMapping::shouldBindAsLValue(e));
2074
2075     llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
2076       it = OpaqueRValues.find(e);
2077     assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
2078     return it->second;
2079   }
2080
2081   /// Get the index of the current ArrayInitLoopExpr, if any.
2082   llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2083
2084   /// getAccessedFieldNo - Given an encoded value and a result number, return
2085   /// the input field number being accessed.
2086   static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2087
2088   llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
2089   llvm::BasicBlock *GetIndirectGotoBlock();
2090
2091   /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
2092   static bool IsWrappedCXXThis(const Expr *E);
2093
2094   /// EmitNullInitialization - Generate code to set a value of the given type to
2095   /// null, If the type contains data member pointers, they will be initialized
2096   /// to -1 in accordance with the Itanium C++ ABI.
2097   void EmitNullInitialization(Address DestPtr, QualType Ty);
2098
2099   /// Emits a call to an LLVM variable-argument intrinsic, either
2100   /// \c llvm.va_start or \c llvm.va_end.
2101   /// \param ArgValue A reference to the \c va_list as emitted by either
2102   /// \c EmitVAListRef or \c EmitMSVAListRef.
2103   /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2104   /// calls \c llvm.va_end.
2105   llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2106
2107   /// Generate code to get an argument from the passed in pointer
2108   /// and update it accordingly.
2109   /// \param VE The \c VAArgExpr for which to generate code.
2110   /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2111   /// either \c EmitVAListRef or \c EmitMSVAListRef.
2112   /// \returns A pointer to the argument.
2113   // FIXME: We should be able to get rid of this method and use the va_arg
2114   // instruction in LLVM instead once it works well enough.
2115   Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
2116
2117   /// emitArrayLength - Compute the length of an array, even if it's a
2118   /// VLA, and drill down to the base element type.
2119   llvm::Value *emitArrayLength(const ArrayType *arrayType,
2120                                QualType &baseType,
2121                                Address &addr);
2122
2123   /// EmitVLASize - Capture all the sizes for the VLA expressions in
2124   /// the given variably-modified type and store them in the VLASizeMap.
2125   ///
2126   /// This function can be called with a null (unreachable) insert point.
2127   void EmitVariablyModifiedType(QualType Ty);
2128
2129   /// getVLASize - Returns an LLVM value that corresponds to the size,
2130   /// in non-variably-sized elements, of a variable length array type,
2131   /// plus that largest non-variably-sized element type.  Assumes that
2132   /// the type has already been emitted with EmitVariablyModifiedType.
2133   std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
2134   std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
2135
2136   /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2137   /// generating code for an C++ member function.
2138   llvm::Value *LoadCXXThis() {
2139     assert(CXXThisValue && "no 'this' value for this function");
2140     return CXXThisValue;
2141   }
2142   Address LoadCXXThisAddress();
2143
2144   /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2145   /// virtual bases.
2146   // FIXME: Every place that calls LoadCXXVTT is something
2147   // that needs to be abstracted properly.
2148   llvm::Value *LoadCXXVTT() {
2149     assert(CXXStructorImplicitParamValue && "no VTT value for this function");
2150     return CXXStructorImplicitParamValue;
2151   }
2152
2153   /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
2154   /// complete class to the given direct base.
2155   Address
2156   GetAddressOfDirectBaseInCompleteClass(Address Value,
2157                                         const CXXRecordDecl *Derived,
2158                                         const CXXRecordDecl *Base,
2159                                         bool BaseIsVirtual);
2160
2161   static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2162
2163   /// GetAddressOfBaseClass - This function will add the necessary delta to the
2164   /// load of 'this' and returns address of the base class.
2165   Address GetAddressOfBaseClass(Address Value,
2166                                 const CXXRecordDecl *Derived,
2167                                 CastExpr::path_const_iterator PathBegin,
2168                                 CastExpr::path_const_iterator PathEnd,
2169                                 bool NullCheckValue, SourceLocation Loc);
2170
2171   Address GetAddressOfDerivedClass(Address Value,
2172                                    const CXXRecordDecl *Derived,
2173                                    CastExpr::path_const_iterator PathBegin,
2174                                    CastExpr::path_const_iterator PathEnd,
2175                                    bool NullCheckValue);
2176
2177   /// GetVTTParameter - Return the VTT parameter that should be passed to a
2178   /// base constructor/destructor with virtual bases.
2179   /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2180   /// to ItaniumCXXABI.cpp together with all the references to VTT.
2181   llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2182                                bool Delegating);
2183
2184   void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2185                                       CXXCtorType CtorType,
2186                                       const FunctionArgList &Args,
2187                                       SourceLocation Loc);
2188   // It's important not to confuse this and the previous function. Delegating
2189   // constructors are the C++0x feature. The constructor delegate optimization
2190   // is used to reduce duplication in the base and complete consturctors where
2191   // they are substantially the same.
2192   void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2193                                         const FunctionArgList &Args);
2194
2195   /// Emit a call to an inheriting constructor (that is, one that invokes a
2196   /// constructor inherited from a base class) by inlining its definition. This
2197   /// is necessary if the ABI does not support forwarding the arguments to the
2198   /// base class constructor (because they're variadic or similar).
2199   void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2200                                                CXXCtorType CtorType,
2201                                                bool ForVirtualBase,
2202                                                bool Delegating,
2203                                                CallArgList &Args);
2204
2205   /// Emit a call to a constructor inherited from a base class, passing the
2206   /// current constructor's arguments along unmodified (without even making
2207   /// a copy).
2208   void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
2209                                        bool ForVirtualBase, Address This,
2210                                        bool InheritedFromVBase,
2211                                        const CXXInheritedCtorInitExpr *E);
2212
2213   void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2214                               bool ForVirtualBase, bool Delegating,
2215                               Address This, const CXXConstructExpr *E);
2216
2217   void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2218                               bool ForVirtualBase, bool Delegating,
2219                               Address This, CallArgList &Args);
2220
2221   /// Emit assumption load for all bases. Requires to be be called only on
2222   /// most-derived class and not under construction of the object.
2223   void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2224
2225   /// Emit assumption that vptr load == global vtable.
2226   void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2227
2228   void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2229                                       Address This, Address Src,
2230                                       const CXXConstructExpr *E);
2231
2232   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2233                                   const ArrayType *ArrayTy,
2234                                   Address ArrayPtr,
2235                                   const CXXConstructExpr *E,
2236                                   bool ZeroInitialization = false);
2237
2238   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2239                                   llvm::Value *NumElements,
2240                                   Address ArrayPtr,
2241                                   const CXXConstructExpr *E,
2242                                   bool ZeroInitialization = false);
2243
2244   static Destroyer destroyCXXObject;
2245
2246   void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
2247                              bool ForVirtualBase, bool Delegating,
2248                              Address This);
2249
2250   void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2251                                llvm::Type *ElementTy, Address NewPtr,
2252                                llvm::Value *NumElements,
2253                                llvm::Value *AllocSizeWithoutCookie);
2254
2255   void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2256                         Address Ptr);
2257
2258   llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
2259   void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2260
2261   llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
2262   void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
2263
2264   void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
2265                       QualType DeleteTy, llvm::Value *NumElements = nullptr,
2266                       CharUnits CookieSize = CharUnits());
2267
2268   RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
2269                                   const Expr *Arg, bool IsDelete);
2270
2271   llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2272   llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2273   Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
2274
2275   /// \brief Situations in which we might emit a check for the suitability of a
2276   ///        pointer or glvalue.
2277   enum TypeCheckKind {
2278     /// Checking the operand of a load. Must be suitably sized and aligned.
2279     TCK_Load,
2280     /// Checking the destination of a store. Must be suitably sized and aligned.
2281     TCK_Store,
2282     /// Checking the bound value in a reference binding. Must be suitably sized
2283     /// and aligned, but is not required to refer to an object (until the
2284     /// reference is used), per core issue 453.
2285     TCK_ReferenceBinding,
2286     /// Checking the object expression in a non-static data member access. Must
2287     /// be an object within its lifetime.
2288     TCK_MemberAccess,
2289     /// Checking the 'this' pointer for a call to a non-static member function.
2290     /// Must be an object within its lifetime.
2291     TCK_MemberCall,
2292     /// Checking the 'this' pointer for a constructor call.
2293     TCK_ConstructorCall,
2294     /// Checking the operand of a static_cast to a derived pointer type. Must be
2295     /// null or an object within its lifetime.
2296     TCK_DowncastPointer,
2297     /// Checking the operand of a static_cast to a derived reference type. Must
2298     /// be an object within its lifetime.
2299     TCK_DowncastReference,
2300     /// Checking the operand of a cast to a base object. Must be suitably sized
2301     /// and aligned.
2302     TCK_Upcast,
2303     /// Checking the operand of a cast to a virtual base object. Must be an
2304     /// object within its lifetime.
2305     TCK_UpcastToVirtualBase,
2306     /// Checking the value assigned to a _Nonnull pointer. Must not be null.
2307     TCK_NonnullAssign
2308   };
2309
2310   /// \brief Whether any type-checking sanitizers are enabled. If \c false,
2311   /// calls to EmitTypeCheck can be skipped.
2312   bool sanitizePerformTypeCheck() const;
2313
2314   /// \brief Emit a check that \p V is the address of storage of the
2315   /// appropriate size and alignment for an object of type \p Type.
2316   void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
2317                      QualType Type, CharUnits Alignment = CharUnits::Zero(),
2318                      SanitizerSet SkippedChecks = SanitizerSet());
2319
2320   /// \brief Emit a check that \p Base points into an array object, which
2321   /// we can access at index \p Index. \p Accessed should be \c false if we
2322   /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
2323   void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
2324                        QualType IndexType, bool Accessed);
2325
2326   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2327                                        bool isInc, bool isPre);
2328   ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
2329                                          bool isInc, bool isPre);
2330
2331   void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
2332                                llvm::Value *OffsetValue = nullptr) {
2333     Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2334                                       OffsetValue);
2335   }
2336
2337   /// Converts Location to a DebugLoc, if debug information is enabled.
2338   llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
2339
2340
2341   //===--------------------------------------------------------------------===//
2342   //                            Declaration Emission
2343   //===--------------------------------------------------------------------===//
2344
2345   /// EmitDecl - Emit a declaration.
2346   ///
2347   /// This function can be called with a null (unreachable) insert point.
2348   void EmitDecl(const Decl &D);
2349
2350   /// EmitVarDecl - Emit a local variable declaration.
2351   ///
2352   /// This function can be called with a null (unreachable) insert point.
2353   void EmitVarDecl(const VarDecl &D);
2354
2355   void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2356                       bool capturedByInit);
2357
2358   typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
2359                              llvm::Value *Address);
2360
2361   /// \brief Determine whether the given initializer is trivial in the sense
2362   /// that it requires no code to be generated.
2363   bool isTrivialInitializer(const Expr *Init);
2364
2365   /// EmitAutoVarDecl - Emit an auto variable declaration.
2366   ///
2367   /// This function can be called with a null (unreachable) insert point.
2368   void EmitAutoVarDecl(const VarDecl &D);
2369
2370   class AutoVarEmission {
2371     friend class CodeGenFunction;
2372
2373     const VarDecl *Variable;
2374
2375     /// The address of the alloca.  Invalid if the variable was emitted
2376     /// as a global constant.
2377     Address Addr;
2378
2379     llvm::Value *NRVOFlag;
2380
2381     /// True if the variable is a __block variable.
2382     bool IsByRef;
2383
2384     /// True if the variable is of aggregate type and has a constant
2385     /// initializer.
2386     bool IsConstantAggregate;
2387
2388     /// Non-null if we should use lifetime annotations.
2389     llvm::Value *SizeForLifetimeMarkers;
2390
2391     struct Invalid {};
2392     AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {}
2393
2394     AutoVarEmission(const VarDecl &variable)
2395       : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
2396         IsByRef(false), IsConstantAggregate(false),
2397         SizeForLifetimeMarkers(nullptr) {}
2398
2399     bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
2400
2401   public:
2402     static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
2403
2404     bool useLifetimeMarkers() const {
2405       return SizeForLifetimeMarkers != nullptr;
2406     }
2407     llvm::Value *getSizeForLifetimeMarkers() const {
2408       assert(useLifetimeMarkers());
2409       return SizeForLifetimeMarkers;
2410     }
2411
2412     /// Returns the raw, allocated address, which is not necessarily
2413     /// the address of the object itself.
2414     Address getAllocatedAddress() const {
2415       return Addr;
2416     }
2417
2418     /// Returns the address of the object within this declaration.
2419     /// Note that this does not chase the forwarding pointer for
2420     /// __block decls.
2421     Address getObjectAddress(CodeGenFunction &CGF) const {
2422       if (!IsByRef) return Addr;
2423
2424       return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
2425     }
2426   };
2427   AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
2428   void EmitAutoVarInit(const AutoVarEmission &emission);
2429   void EmitAutoVarCleanups(const AutoVarEmission &emission);  
2430   void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
2431                               QualType::DestructionKind dtorKind);
2432
2433   void EmitStaticVarDecl(const VarDecl &D,
2434                          llvm::GlobalValue::LinkageTypes Linkage);
2435
2436   class ParamValue {
2437     llvm::Value *Value;
2438     unsigned Alignment;
2439     ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
2440   public:
2441     static ParamValue forDirect(llvm::Value *value) {
2442       return ParamValue(value, 0);
2443     }
2444     static ParamValue forIndirect(Address addr) {
2445       assert(!addr.getAlignment().isZero());
2446       return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
2447     }
2448
2449     bool isIndirect() const { return Alignment != 0; }
2450     llvm::Value *getAnyValue() const { return Value; }
2451     
2452     llvm::Value *getDirectValue() const {
2453       assert(!isIndirect());
2454       return Value;
2455     }
2456
2457     Address getIndirectAddress() const {
2458       assert(isIndirect());
2459       return Address(Value, CharUnits::fromQuantity(Alignment));
2460     }
2461   };
2462
2463   /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
2464   void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
2465
2466   /// protectFromPeepholes - Protect a value that we're intending to
2467   /// store to the side, but which will probably be used later, from
2468   /// aggressive peepholing optimizations that might delete it.
2469   ///
2470   /// Pass the result to unprotectFromPeepholes to declare that
2471   /// protection is no longer required.
2472   ///
2473   /// There's no particular reason why this shouldn't apply to
2474   /// l-values, it's just that no existing peepholes work on pointers.
2475   PeepholeProtection protectFromPeepholes(RValue rvalue);
2476   void unprotectFromPeepholes(PeepholeProtection protection);
2477
2478   void EmitAlignmentAssumption(llvm::Value *PtrValue, llvm::Value *Alignment,
2479                                llvm::Value *OffsetValue = nullptr) {
2480     Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2481                                       OffsetValue);
2482   }
2483
2484   //===--------------------------------------------------------------------===//
2485   //                             Statement Emission
2486   //===--------------------------------------------------------------------===//
2487
2488   /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
2489   void EmitStopPoint(const Stmt *S);
2490
2491   /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
2492   /// this function even if there is no current insertion point.
2493   ///
2494   /// This function may clear the current insertion point; callers should use
2495   /// EnsureInsertPoint if they wish to subsequently generate code without first
2496   /// calling EmitBlock, EmitBranch, or EmitStmt.
2497   void EmitStmt(const Stmt *S);
2498
2499   /// EmitSimpleStmt - Try to emit a "simple" statement which does not
2500   /// necessarily require an insertion point or debug information; typically
2501   /// because the statement amounts to a jump or a container of other
2502   /// statements.
2503   ///
2504   /// \return True if the statement was handled.
2505   bool EmitSimpleStmt(const Stmt *S);
2506
2507   Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
2508                            AggValueSlot AVS = AggValueSlot::ignored());
2509   Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
2510                                        bool GetLast = false,
2511                                        AggValueSlot AVS =
2512                                                 AggValueSlot::ignored());
2513
2514   /// EmitLabel - Emit the block for the given label. It is legal to call this
2515   /// function even if there is no current insertion point.
2516   void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
2517
2518   void EmitLabelStmt(const LabelStmt &S);
2519   void EmitAttributedStmt(const AttributedStmt &S);
2520   void EmitGotoStmt(const GotoStmt &S);
2521   void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
2522   void EmitIfStmt(const IfStmt &S);
2523
2524   void EmitWhileStmt(const WhileStmt &S,
2525                      ArrayRef<const Attr *> Attrs = None);
2526   void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
2527   void EmitForStmt(const ForStmt &S,
2528                    ArrayRef<const Attr *> Attrs = None);
2529   void EmitReturnStmt(const ReturnStmt &S);
2530   void EmitDeclStmt(const DeclStmt &S);
2531   void EmitBreakStmt(const BreakStmt &S);
2532   void EmitContinueStmt(const ContinueStmt &S);
2533   void EmitSwitchStmt(const SwitchStmt &S);
2534   void EmitDefaultStmt(const DefaultStmt &S);
2535   void EmitCaseStmt(const CaseStmt &S);
2536   void EmitCaseStmtRange(const CaseStmt &S);
2537   void EmitAsmStmt(const AsmStmt &S);
2538
2539   void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
2540   void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
2541   void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
2542   void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
2543   void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
2544
2545   void EmitCoroutineBody(const CoroutineBodyStmt &S);
2546   void EmitCoreturnStmt(const CoreturnStmt &S);
2547   RValue EmitCoawaitExpr(const CoawaitExpr &E,
2548                          AggValueSlot aggSlot = AggValueSlot::ignored(),
2549                          bool ignoreResult = false);
2550   RValue EmitCoyieldExpr(const CoyieldExpr &E,
2551                          AggValueSlot aggSlot = AggValueSlot::ignored(),
2552                          bool ignoreResult = false);
2553   RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
2554
2555   void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2556   void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2557
2558   void EmitCXXTryStmt(const CXXTryStmt &S);
2559   void EmitSEHTryStmt(const SEHTryStmt &S);
2560   void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
2561   void EnterSEHTryStmt(const SEHTryStmt &S);
2562   void ExitSEHTryStmt(const SEHTryStmt &S);
2563
2564   void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
2565                               const Stmt *OutlinedStmt);
2566
2567   llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2568                                             const SEHExceptStmt &Except);
2569
2570   llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2571                                              const SEHFinallyStmt &Finally);
2572
2573   void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
2574                                 llvm::Value *ParentFP,
2575                                 llvm::Value *EntryEBP);
2576   llvm::Value *EmitSEHExceptionCode();
2577   llvm::Value *EmitSEHExceptionInfo();
2578   llvm::Value *EmitSEHAbnormalTermination();
2579
2580   /// Scan the outlined statement for captures from the parent function. For
2581   /// each capture, mark the capture as escaped and emit a call to
2582   /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
2583   void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
2584                           bool IsFilter);
2585
2586   /// Recovers the address of a local in a parent function. ParentVar is the
2587   /// address of the variable used in the immediate parent function. It can
2588   /// either be an alloca or a call to llvm.localrecover if there are nested
2589   /// outlined functions. ParentFP is the frame pointer of the outermost parent
2590   /// frame.
2591   Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
2592                                     Address ParentVar,
2593                                     llvm::Value *ParentFP);
2594
2595   void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
2596                            ArrayRef<const Attr *> Attrs = None);
2597
2598   /// Returns calculated size of the specified type.
2599   llvm::Value *getTypeSize(QualType Ty);
2600   LValue InitCapturedStruct(const CapturedStmt &S);
2601   llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
2602   llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
2603   Address GenerateCapturedStmtArgument(const CapturedStmt &S);
2604   llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
2605   void GenerateOpenMPCapturedVars(const CapturedStmt &S,
2606                                   SmallVectorImpl<llvm::Value *> &CapturedVars);
2607   void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
2608                           SourceLocation Loc);
2609   /// \brief Perform element by element copying of arrays with type \a
2610   /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
2611   /// generated by \a CopyGen.
2612   ///
2613   /// \param DestAddr Address of the destination array.
2614   /// \param SrcAddr Address of the source array.
2615   /// \param OriginalType Type of destination and source arrays.
2616   /// \param CopyGen Copying procedure that copies value of single array element
2617   /// to another single array element.
2618   void EmitOMPAggregateAssign(
2619       Address DestAddr, Address SrcAddr, QualType OriginalType,
2620       const llvm::function_ref<void(Address, Address)> &CopyGen);
2621   /// \brief Emit proper copying of data from one variable to another.
2622   ///
2623   /// \param OriginalType Original type of the copied variables.
2624   /// \param DestAddr Destination address.
2625   /// \param SrcAddr Source address.
2626   /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
2627   /// type of the base array element).
2628   /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
2629   /// the base array element).
2630   /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
2631   /// DestVD.
2632   void EmitOMPCopy(QualType OriginalType,
2633                    Address DestAddr, Address SrcAddr,
2634                    const VarDecl *DestVD, const VarDecl *SrcVD,
2635                    const Expr *Copy);
2636   /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
2637   /// \a X = \a E \a BO \a E.
2638   ///
2639   /// \param X Value to be updated.
2640   /// \param E Update value.
2641   /// \param BO Binary operation for update operation.
2642   /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
2643   /// expression, false otherwise.
2644   /// \param AO Atomic ordering of the generated atomic instructions.
2645   /// \param CommonGen Code generator for complex expressions that cannot be
2646   /// expressed through atomicrmw instruction.
2647   /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
2648   /// generated, <false, RValue::get(nullptr)> otherwise.
2649   std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
2650       LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2651       llvm::AtomicOrdering AO, SourceLocation Loc,
2652       const llvm::function_ref<RValue(RValue)> &CommonGen);
2653   bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
2654                                  OMPPrivateScope &PrivateScope);
2655   void EmitOMPPrivateClause(const OMPExecutableDirective &D,
2656                             OMPPrivateScope &PrivateScope);
2657   void EmitOMPUseDevicePtrClause(
2658       const OMPClause &C, OMPPrivateScope &PrivateScope,
2659       const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
2660   /// \brief Emit code for copyin clause in \a D directive. The next code is
2661   /// generated at the start of outlined functions for directives:
2662   /// \code
2663   /// threadprivate_var1 = master_threadprivate_var1;
2664   /// operator=(threadprivate_var2, master_threadprivate_var2);
2665   /// ...
2666   /// __kmpc_barrier(&loc, global_tid);
2667   /// \endcode
2668   ///
2669   /// \param D OpenMP directive possibly with 'copyin' clause(s).
2670   /// \returns true if at least one copyin variable is found, false otherwise.
2671   bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
2672   /// \brief Emit initial code for lastprivate variables. If some variable is
2673   /// not also firstprivate, then the default initialization is used. Otherwise
2674   /// initialization of this variable is performed by EmitOMPFirstprivateClause
2675   /// method.
2676   ///
2677   /// \param D Directive that may have 'lastprivate' directives.
2678   /// \param PrivateScope Private scope for capturing lastprivate variables for
2679   /// proper codegen in internal captured statement.
2680   ///
2681   /// \returns true if there is at least one lastprivate variable, false
2682   /// otherwise.
2683   bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
2684                                     OMPPrivateScope &PrivateScope);
2685   /// \brief Emit final copying of lastprivate values to original variables at
2686   /// the end of the worksharing or simd directive.
2687   ///
2688   /// \param D Directive that has at least one 'lastprivate' directives.
2689   /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
2690   /// it is the last iteration of the loop code in associated directive, or to
2691   /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
2692   void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
2693                                      bool NoFinals,
2694                                      llvm::Value *IsLastIterCond = nullptr);
2695   /// Emit initial code for linear clauses.
2696   void EmitOMPLinearClause(const OMPLoopDirective &D,
2697                            CodeGenFunction::OMPPrivateScope &PrivateScope);
2698   /// Emit final code for linear clauses.
2699   /// \param CondGen Optional conditional code for final part of codegen for
2700   /// linear clause.
2701   void EmitOMPLinearClauseFinal(
2702       const OMPLoopDirective &D,
2703       const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2704   /// \brief Emit initial code for reduction variables. Creates reduction copies
2705   /// and initializes them with the values according to OpenMP standard.
2706   ///
2707   /// \param D Directive (possibly) with the 'reduction' clause.
2708   /// \param PrivateScope Private scope for capturing reduction variables for
2709   /// proper codegen in internal captured statement.
2710   ///
2711   void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
2712                                   OMPPrivateScope &PrivateScope);
2713   /// \brief Emit final update of reduction values to original variables at
2714   /// the end of the directive.
2715   ///
2716   /// \param D Directive that has at least one 'reduction' directives.
2717   /// \param ReductionKind The kind of reduction to perform.
2718   void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
2719                                    const OpenMPDirectiveKind ReductionKind);
2720   /// \brief Emit initial code for linear variables. Creates private copies
2721   /// and initializes them with the values according to OpenMP standard.
2722   ///
2723   /// \param D Directive (possibly) with the 'linear' clause.
2724   void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
2725
2726   typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
2727                                         llvm::Value * /*OutlinedFn*/,
2728                                         const OMPTaskDataTy & /*Data*/)>
2729       TaskGenTy;
2730   void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2731                                  const RegionCodeGenTy &BodyGen,
2732                                  const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
2733
2734   void EmitOMPParallelDirective(const OMPParallelDirective &S);
2735   void EmitOMPSimdDirective(const OMPSimdDirective &S);
2736   void EmitOMPForDirective(const OMPForDirective &S);
2737   void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
2738   void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
2739   void EmitOMPSectionDirective(const OMPSectionDirective &S);
2740   void EmitOMPSingleDirective(const OMPSingleDirective &S);
2741   void EmitOMPMasterDirective(const OMPMasterDirective &S);
2742   void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
2743   void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
2744   void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
2745   void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
2746   void EmitOMPTaskDirective(const OMPTaskDirective &S);
2747   void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
2748   void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
2749   void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
2750   void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
2751   void EmitOMPFlushDirective(const OMPFlushDirective &S);
2752   void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
2753   void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
2754   void EmitOMPTargetDirective(const OMPTargetDirective &S);
2755   void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
2756   void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
2757   void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
2758   void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
2759   void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
2760   void
2761   EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
2762   void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
2763   void
2764   EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
2765   void EmitOMPCancelDirective(const OMPCancelDirective &S);
2766   void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
2767   void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
2768   void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
2769   void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
2770   void EmitOMPDistributeParallelForDirective(
2771       const OMPDistributeParallelForDirective &S);
2772   void EmitOMPDistributeParallelForSimdDirective(
2773       const OMPDistributeParallelForSimdDirective &S);
2774   void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
2775   void EmitOMPTargetParallelForSimdDirective(
2776       const OMPTargetParallelForSimdDirective &S);
2777   void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
2778   void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
2779   void
2780   EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
2781   void EmitOMPTeamsDistributeParallelForSimdDirective(
2782       const OMPTeamsDistributeParallelForSimdDirective &S);
2783   void EmitOMPTeamsDistributeParallelForDirective(
2784       const OMPTeamsDistributeParallelForDirective &S);
2785   void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
2786   void EmitOMPTargetTeamsDistributeDirective(
2787       const OMPTargetTeamsDistributeDirective &S);
2788   void EmitOMPTargetTeamsDistributeParallelForDirective(
2789       const OMPTargetTeamsDistributeParallelForDirective &S);
2790   void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2791       const OMPTargetTeamsDistributeParallelForSimdDirective &S);
2792   void EmitOMPTargetTeamsDistributeSimdDirective(
2793       const OMPTargetTeamsDistributeSimdDirective &S);
2794
2795   /// Emit device code for the target directive.
2796   static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
2797                                           StringRef ParentName,
2798                                           const OMPTargetDirective &S);
2799   static void
2800   EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
2801                                       const OMPTargetParallelDirective &S);
2802   static void
2803   EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
2804                                    const OMPTargetTeamsDirective &S);
2805   /// \brief Emit inner loop of the worksharing/simd construct.
2806   ///
2807   /// \param S Directive, for which the inner loop must be emitted.
2808   /// \param RequiresCleanup true, if directive has some associated private
2809   /// variables.
2810   /// \param LoopCond Bollean condition for loop continuation.
2811   /// \param IncExpr Increment expression for loop control variable.
2812   /// \param BodyGen Generator for the inner body of the inner loop.
2813   /// \param PostIncGen Genrator for post-increment code (required for ordered
2814   /// loop directvies).
2815   void EmitOMPInnerLoop(
2816       const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
2817       const Expr *IncExpr,
2818       const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
2819       const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
2820
2821   JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
2822   /// Emit initial code for loop counters of loop-based directives.
2823   void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
2824                                   OMPPrivateScope &LoopScope);
2825
2826   /// Helper for the OpenMP loop directives.
2827   void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
2828
2829   /// \brief Emit code for the worksharing loop-based directive.
2830   /// \return true, if this construct has any lastprivate clause, false -
2831   /// otherwise.
2832   bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB,
2833                               const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2834                               const CodeGenDispatchBoundsTy &CGDispatchBounds);
2835
2836 private:
2837   /// Helpers for blocks
2838   llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
2839
2840   /// Helpers for the OpenMP loop directives.
2841   void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
2842   void EmitOMPSimdFinal(
2843       const OMPLoopDirective &D,
2844       const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2845
2846   void EmitOMPDistributeLoop(const OMPLoopDirective &S,
2847                              const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
2848
2849   /// struct with the values to be passed to the OpenMP loop-related functions
2850   struct OMPLoopArguments {
2851     /// loop lower bound
2852     Address LB = Address::invalid();
2853     /// loop upper bound
2854     Address UB = Address::invalid();
2855     /// loop stride
2856     Address ST = Address::invalid();
2857     /// isLastIteration argument for runtime functions
2858     Address IL = Address::invalid();
2859     /// Chunk value generated by sema
2860     llvm::Value *Chunk = nullptr;
2861     /// EnsureUpperBound
2862     Expr *EUB = nullptr;
2863     /// IncrementExpression
2864     Expr *IncExpr = nullptr;
2865     /// Loop initialization
2866     Expr *Init = nullptr;
2867     /// Loop exit condition
2868     Expr *Cond = nullptr;
2869     /// Update of LB after a whole chunk has been executed
2870     Expr *NextLB = nullptr;
2871     /// Update of UB after a whole chunk has been executed
2872     Expr *NextUB = nullptr;
2873     OMPLoopArguments() = default;
2874     OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
2875                      llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
2876                      Expr *IncExpr = nullptr, Expr *Init = nullptr,
2877                      Expr *Cond = nullptr, Expr *NextLB = nullptr,
2878                      Expr *NextUB = nullptr)
2879         : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
2880           IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
2881           NextUB(NextUB) {}
2882   };
2883   void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
2884                         const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
2885                         const OMPLoopArguments &LoopArgs,
2886                         const CodeGenLoopTy &CodeGenLoop,
2887                         const CodeGenOrderedTy &CodeGenOrdered);
2888   void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
2889                            bool IsMonotonic, const OMPLoopDirective &S,
2890                            OMPPrivateScope &LoopScope, bool Ordered,
2891                            const OMPLoopArguments &LoopArgs,
2892                            const CodeGenDispatchBoundsTy &CGDispatchBounds);
2893   void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
2894                                   const OMPLoopDirective &S,
2895                                   OMPPrivateScope &LoopScope,
2896                                   const OMPLoopArguments &LoopArgs,
2897                                   const CodeGenLoopTy &CodeGenLoopContent);
2898   /// \brief Emit code for sections directive.
2899   void EmitSections(const OMPExecutableDirective &S);
2900
2901 public:
2902
2903   //===--------------------------------------------------------------------===//
2904   //                         LValue Expression Emission
2905   //===--------------------------------------------------------------------===//
2906
2907   /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
2908   RValue GetUndefRValue(QualType Ty);
2909
2910   /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
2911   /// and issue an ErrorUnsupported style diagnostic (using the
2912   /// provided Name).
2913   RValue EmitUnsupportedRValue(const Expr *E,
2914                                const char *Name);
2915
2916   /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
2917   /// an ErrorUnsupported style diagnostic (using the provided Name).
2918   LValue EmitUnsupportedLValue(const Expr *E,
2919                                const char *Name);
2920
2921   /// EmitLValue - Emit code to compute a designator that specifies the location
2922   /// of the expression.
2923   ///
2924   /// This can return one of two things: a simple address or a bitfield
2925   /// reference.  In either case, the LLVM Value* in the LValue structure is
2926   /// guaranteed to be an LLVM pointer type.
2927   ///
2928   /// If this returns a bitfield reference, nothing about the pointee type of
2929   /// the LLVM value is known: For example, it may not be a pointer to an
2930   /// integer.
2931   ///
2932   /// If this returns a normal address, and if the lvalue's C type is fixed
2933   /// size, this method guarantees that the returned pointer type will point to
2934   /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
2935   /// variable length type, this is not possible.
2936   ///
2937   LValue EmitLValue(const Expr *E);
2938
2939   /// \brief Same as EmitLValue but additionally we generate checking code to
2940   /// guard against undefined behavior.  This is only suitable when we know
2941   /// that the address will be used to access the object.
2942   LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
2943
2944   RValue convertTempToRValue(Address addr, QualType type,
2945                              SourceLocation Loc);
2946
2947   void EmitAtomicInit(Expr *E, LValue lvalue);
2948
2949   bool LValueIsSuitableForInlineAtomic(LValue Src);
2950
2951   RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
2952                         AggValueSlot Slot = AggValueSlot::ignored());
2953
2954   RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
2955                         llvm::AtomicOrdering AO, bool IsVolatile = false,
2956                         AggValueSlot slot = AggValueSlot::ignored());
2957
2958   void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
2959
2960   void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
2961                        bool IsVolatile, bool isInit);
2962
2963   std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
2964       LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2965       llvm::AtomicOrdering Success =
2966           llvm::AtomicOrdering::SequentiallyConsistent,
2967       llvm::AtomicOrdering Failure =
2968           llvm::AtomicOrdering::SequentiallyConsistent,
2969       bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
2970
2971   void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
2972                         const llvm::function_ref<RValue(RValue)> &UpdateOp,
2973                         bool IsVolatile);
2974
2975   /// EmitToMemory - Change a scalar value from its value
2976   /// representation to its in-memory representation.
2977   llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
2978
2979   /// EmitFromMemory - Change a scalar value from its memory
2980   /// representation to its value representation.
2981   llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
2982
2983   /// Check if the scalar \p Value is within the valid range for the given
2984   /// type \p Ty.
2985   ///
2986   /// Returns true if a check is needed (even if the range is unknown).
2987   bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
2988                             SourceLocation Loc);
2989
2990   /// EmitLoadOfScalar - Load a scalar value from an address, taking
2991   /// care to appropriately convert from the memory representation to
2992   /// the LLVM value representation.
2993   llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
2994                                 SourceLocation Loc,
2995                                 AlignmentSource AlignSource =
2996                                   AlignmentSource::Type,
2997                                 llvm::MDNode *TBAAInfo = nullptr,
2998                                 QualType TBAABaseTy = QualType(),
2999                                 uint64_t TBAAOffset = 0,
3000                                 bool isNontemporal = false);
3001
3002   /// EmitLoadOfScalar - Load a scalar value from an address, taking
3003   /// care to appropriately convert from the memory representation to
3004   /// the LLVM value representation.  The l-value must be a simple
3005   /// l-value.
3006   llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
3007
3008   /// EmitStoreOfScalar - Store a scalar value to an address, taking
3009   /// care to appropriately convert from the memory representation to
3010   /// the LLVM value representation.
3011   void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3012                          bool Volatile, QualType Ty,
3013                          AlignmentSource AlignSource = AlignmentSource::Type,
3014                          llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
3015                          QualType TBAABaseTy = QualType(),
3016                          uint64_t TBAAOffset = 0, bool isNontemporal = false);
3017
3018   /// EmitStoreOfScalar - Store a scalar value to an address, taking
3019   /// care to appropriately convert from the memory representation to
3020   /// the LLVM value representation.  The l-value must be a simple
3021   /// l-value.  The isInit flag indicates whether this is an initialization.
3022   /// If so, atomic qualifiers are ignored and the store is always non-atomic.
3023   void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
3024
3025   /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
3026   /// this method emits the address of the lvalue, then loads the result as an
3027   /// rvalue, returning the rvalue.
3028   RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
3029   RValue EmitLoadOfExtVectorElementLValue(LValue V);
3030   RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc);
3031   RValue EmitLoadOfGlobalRegLValue(LValue LV);
3032
3033   /// EmitStoreThroughLValue - Store the specified rvalue into the specified
3034   /// lvalue, where both are guaranteed to the have the same type, and that type
3035   /// is 'Ty'.
3036   void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
3037   void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
3038   void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
3039
3040   /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
3041   /// as EmitStoreThroughLValue.
3042   ///
3043   /// \param Result [out] - If non-null, this will be set to a Value* for the
3044   /// bit-field contents after the store, appropriate for use as the result of
3045   /// an assignment to the bit-field.
3046   void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
3047                                       llvm::Value **Result=nullptr);
3048
3049   /// Emit an l-value for an assignment (simple or compound) of complex type.
3050   LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
3051   LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
3052   LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
3053                                              llvm::Value *&Result);
3054
3055   // Note: only available for agg return types
3056   LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
3057   LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
3058   // Note: only available for agg return types
3059   LValue EmitCallExprLValue(const CallExpr *E);
3060   // Note: only available for agg return types
3061   LValue EmitVAArgExprLValue(const VAArgExpr *E);
3062   LValue EmitDeclRefLValue(const DeclRefExpr *E);
3063   LValue EmitStringLiteralLValue(const StringLiteral *E);
3064   LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
3065   LValue EmitPredefinedLValue(const PredefinedExpr *E);
3066   LValue EmitUnaryOpLValue(const UnaryOperator *E);
3067   LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3068                                 bool Accessed = false);
3069   LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3070                                  bool IsLowerBound = true);
3071   LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
3072   LValue EmitMemberExpr(const MemberExpr *E);
3073   LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
3074   LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
3075   LValue EmitInitListLValue(const InitListExpr *E);
3076   LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
3077   LValue EmitCastLValue(const CastExpr *E);
3078   LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
3079   LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
3080   
3081   Address EmitExtVectorElementLValue(LValue V);
3082
3083   RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
3084
3085   Address EmitArrayToPointerDecay(const Expr *Array,
3086                                   AlignmentSource *AlignSource = nullptr);
3087
3088   class ConstantEmission {
3089     llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
3090     ConstantEmission(llvm::Constant *C, bool isReference)
3091       : ValueAndIsReference(C, isReference) {}
3092   public:
3093     ConstantEmission() {}
3094     static ConstantEmission forReference(llvm::Constant *C) {
3095       return ConstantEmission(C, true);
3096     }
3097     static ConstantEmission forValue(llvm::Constant *C) {
3098       return ConstantEmission(C, false);
3099     }
3100
3101     explicit operator bool() const {
3102       return ValueAndIsReference.getOpaqueValue() != nullptr;
3103     }
3104
3105     bool isReference() const { return ValueAndIsReference.getInt(); }
3106     LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
3107       assert(isReference());
3108       return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
3109                                             refExpr->getType());
3110     }
3111
3112     llvm::Constant *getValue() const {
3113       assert(!isReference());
3114       return ValueAndIsReference.getPointer();
3115     }
3116   };
3117
3118   ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
3119
3120   RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
3121                                 AggValueSlot slot = AggValueSlot::ignored());
3122   LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
3123
3124   llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
3125                               const ObjCIvarDecl *Ivar);
3126   LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
3127   LValue EmitLValueForLambdaField(const FieldDecl *Field);
3128
3129   /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
3130   /// if the Field is a reference, this will return the address of the reference
3131   /// and not the address of the value stored in the reference.
3132   LValue EmitLValueForFieldInitialization(LValue Base,
3133                                           const FieldDecl* Field);
3134
3135   LValue EmitLValueForIvar(QualType ObjectTy,
3136                            llvm::Value* Base, const ObjCIvarDecl *Ivar,
3137                            unsigned CVRQualifiers);
3138
3139   LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
3140   LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
3141   LValue EmitLambdaLValue(const LambdaExpr *E);
3142   LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
3143   LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
3144
3145   LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
3146   LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
3147   LValue EmitStmtExprLValue(const StmtExpr *E);
3148   LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
3149   LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
3150   void   EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
3151
3152   //===--------------------------------------------------------------------===//
3153   //                         Scalar Expression Emission
3154   //===--------------------------------------------------------------------===//
3155
3156   /// EmitCall - Generate a call of the given function, expecting the given
3157   /// result type, and using the given argument list which specifies both the
3158   /// LLVM arguments and the types they were derived from.
3159   RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
3160                   ReturnValueSlot ReturnValue, const CallArgList &Args,
3161                   llvm::Instruction **callOrInvoke = nullptr);
3162
3163   RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
3164                   ReturnValueSlot ReturnValue,
3165                   llvm::Value *Chain = nullptr);
3166   RValue EmitCallExpr(const CallExpr *E,
3167                       ReturnValueSlot ReturnValue = ReturnValueSlot());
3168   RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3169   CGCallee EmitCallee(const Expr *E);
3170
3171   void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
3172
3173   llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3174                                   const Twine &name = "");
3175   llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3176                                   ArrayRef<llvm::Value*> args,
3177                                   const Twine &name = "");
3178   llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3179                                           const Twine &name = "");
3180   llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3181                                           ArrayRef<llvm::Value*> args,
3182                                           const Twine &name = "");
3183
3184   llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
3185                                   ArrayRef<llvm::Value *> Args,
3186                                   const Twine &Name = "");
3187   llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3188                                          ArrayRef<llvm::Value*> args,
3189                                          const Twine &name = "");
3190   llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3191                                          const Twine &name = "");
3192   void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3193                                        ArrayRef<llvm::Value*> args);
3194
3195   CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 
3196                                      NestedNameSpecifier *Qual,
3197                                      llvm::Type *Ty);
3198   
3199   CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
3200                                                CXXDtorType Type, 
3201                                                const CXXRecordDecl *RD);
3202
3203   RValue
3204   EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
3205                               const CGCallee &Callee,
3206                               ReturnValueSlot ReturnValue, llvm::Value *This,
3207                               llvm::Value *ImplicitParam,
3208                               QualType ImplicitParamTy, const CallExpr *E,
3209                               CallArgList *RtlArgs);
3210   RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD,
3211                                const CGCallee &Callee,
3212                                llvm::Value *This, llvm::Value *ImplicitParam,
3213                                QualType ImplicitParamTy, const CallExpr *E,
3214                                StructorType Type);
3215   RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
3216                                ReturnValueSlot ReturnValue);
3217   RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
3218                                                const CXXMethodDecl *MD,
3219                                                ReturnValueSlot ReturnValue,
3220                                                bool HasQualifier,
3221                                                NestedNameSpecifier *Qualifier,
3222                                                bool IsArrow, const Expr *Base);
3223   // Compute the object pointer.
3224   Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
3225                                           llvm::Value *memberPtr,
3226                                           const MemberPointerType *memberPtrType,
3227                                           AlignmentSource *AlignSource = nullptr);
3228   RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
3229                                       ReturnValueSlot ReturnValue);
3230
3231   RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
3232                                        const CXXMethodDecl *MD,
3233                                        ReturnValueSlot ReturnValue);
3234   RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
3235
3236   RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
3237                                 ReturnValueSlot ReturnValue);
3238
3239   RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E,
3240                                        ReturnValueSlot ReturnValue);
3241
3242   RValue EmitBuiltinExpr(const FunctionDecl *FD,
3243                          unsigned BuiltinID, const CallExpr *E,
3244                          ReturnValueSlot ReturnValue);
3245
3246   RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3247
3248   /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
3249   /// is unhandled by the current target.
3250   llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3251
3252   llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
3253                                              const llvm::CmpInst::Predicate Fp,
3254                                              const llvm::CmpInst::Predicate Ip,
3255                                              const llvm::Twine &Name = "");
3256   llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3257
3258   llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
3259                                          unsigned LLVMIntrinsic,
3260                                          unsigned AltLLVMIntrinsic,
3261                                          const char *NameHint,
3262                                          unsigned Modifier,
3263                                          const CallExpr *E,
3264                                          SmallVectorImpl<llvm::Value *> &Ops,
3265                                          Address PtrOp0, Address PtrOp1);
3266   llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
3267                                           unsigned Modifier, llvm::Type *ArgTy,
3268                                           const CallExpr *E);
3269   llvm::Value *EmitNeonCall(llvm::Function *F,
3270                             SmallVectorImpl<llvm::Value*> &O,
3271                             const char *name,
3272                             unsigned shift = 0, bool rightshift = false);
3273   llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
3274   llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
3275                                    bool negateForRightShift);
3276   llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
3277                                  llvm::Type *Ty, bool usgn, const char *name);
3278   llvm::Value *vectorWrapScalar16(llvm::Value *Op);
3279   llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3280
3281   llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
3282   llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3283   llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3284   llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3285   llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3286   llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3287   llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
3288                                           const CallExpr *E);
3289
3290 private:
3291   enum class MSVCIntrin;
3292
3293 public:
3294   llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
3295
3296   llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args);
3297
3298   llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
3299   llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
3300   llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
3301   llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
3302   llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
3303   llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
3304                                 const ObjCMethodDecl *MethodWithObjects);
3305   llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
3306   RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
3307                              ReturnValueSlot Return = ReturnValueSlot());
3308
3309   /// Retrieves the default cleanup kind for an ARC cleanup.
3310   /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
3311   CleanupKind getARCCleanupKind() {
3312     return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
3313              ? NormalAndEHCleanup : NormalCleanup;
3314   }
3315
3316   // ARC primitives.
3317   void EmitARCInitWeak(Address addr, llvm::Value *value);
3318   void EmitARCDestroyWeak(Address addr);
3319   llvm::Value *EmitARCLoadWeak(Address addr);
3320   llvm::Value *EmitARCLoadWeakRetained(Address addr);
3321   llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
3322   void EmitARCCopyWeak(Address dst, Address src);
3323   void EmitARCMoveWeak(Address dst, Address src);
3324   llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
3325   llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
3326   llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
3327                                   bool resultIgnored);
3328   llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
3329                                       bool resultIgnored);
3330   llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
3331   llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
3332   llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
3333   void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
3334   void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
3335   llvm::Value *EmitARCAutorelease(llvm::Value *value);
3336   llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
3337   llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
3338   llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
3339   llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
3340
3341   std::pair<LValue,llvm::Value*>
3342   EmitARCStoreAutoreleasing(const BinaryOperator *e);
3343   std::pair<LValue,llvm::Value*>
3344   EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
3345   std::pair<LValue,llvm::Value*>
3346   EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
3347
3348   llvm::Value *EmitObjCThrowOperand(const Expr *expr);
3349   llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
3350   llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
3351
3352   llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
3353   llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
3354                                             bool allowUnsafeClaim);
3355   llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
3356   llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
3357   llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
3358
3359   void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
3360
3361   static Destroyer destroyARCStrongImprecise;
3362   static Destroyer destroyARCStrongPrecise;
3363   static Destroyer destroyARCWeak;
3364   static Destroyer emitARCIntrinsicUse;
3365
3366   void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 
3367   llvm::Value *EmitObjCAutoreleasePoolPush();
3368   llvm::Value *EmitObjCMRRAutoreleasePoolPush();
3369   void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
3370   void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 
3371
3372   /// \brief Emits a reference binding to the passed in expression.
3373   RValue EmitReferenceBindingToExpr(const Expr *E);
3374
3375   //===--------------------------------------------------------------------===//
3376   //                           Expression Emission
3377   //===--------------------------------------------------------------------===//
3378
3379   // Expressions are broken into three classes: scalar, complex, aggregate.
3380
3381   /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
3382   /// scalar type, returning the result.
3383   llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
3384
3385   /// Emit a conversion from the specified type to the specified destination
3386   /// type, both of which are LLVM scalar types.
3387   llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
3388                                     QualType DstTy, SourceLocation Loc);
3389
3390   /// Emit a conversion from the specified complex type to the specified
3391   /// destination type, where the destination type is an LLVM scalar type.
3392   llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
3393                                              QualType DstTy,
3394                                              SourceLocation Loc);
3395
3396   /// EmitAggExpr - Emit the computation of the specified expression
3397   /// of aggregate type.  The result is computed into the given slot,
3398   /// which may be null to indicate that the value is not needed.
3399   void EmitAggExpr(const Expr *E, AggValueSlot AS);
3400
3401   /// EmitAggExprToLValue - Emit the computation of the specified expression of
3402   /// aggregate type into a temporary LValue.
3403   LValue EmitAggExprToLValue(const Expr *E);
3404
3405   /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3406   /// make sure it survives garbage collection until this point.
3407   void EmitExtendGCLifetime(llvm::Value *object);
3408
3409   /// EmitComplexExpr - Emit the computation of the specified expression of
3410   /// complex type, returning the result.
3411   ComplexPairTy EmitComplexExpr(const Expr *E,
3412                                 bool IgnoreReal = false,
3413                                 bool IgnoreImag = false);
3414
3415   /// EmitComplexExprIntoLValue - Emit the given expression of complex
3416   /// type and place its result into the specified l-value.
3417   void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
3418
3419   /// EmitStoreOfComplex - Store a complex number into the specified l-value.
3420   void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
3421
3422   /// EmitLoadOfComplex - Load a complex number from the specified l-value.
3423   ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
3424
3425   Address emitAddrOfRealComponent(Address complex, QualType complexType);
3426   Address emitAddrOfImagComponent(Address complex, QualType complexType);
3427
3428   /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
3429   /// global variable that has already been created for it.  If the initializer
3430   /// has a different type than GV does, this may free GV and return a different
3431   /// one.  Otherwise it just returns GV.
3432   llvm::GlobalVariable *
3433   AddInitializerToStaticVarDecl(const VarDecl &D,
3434                                 llvm::GlobalVariable *GV);
3435
3436
3437   /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
3438   /// variable with global storage.
3439   void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
3440                                 bool PerformInit);
3441
3442   llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
3443                                    llvm::Constant *Addr);
3444
3445   /// Call atexit() with a function that passes the given argument to
3446   /// the given function.
3447   void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
3448                                     llvm::Constant *addr);
3449
3450   /// Emit code in this function to perform a guarded variable
3451   /// initialization.  Guarded initializations are used when it's not
3452   /// possible to prove that an initialization will be done exactly
3453   /// once, e.g. with a static local variable or a static data member
3454   /// of a class template.
3455   void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
3456                           bool PerformInit);
3457
3458   /// GenerateCXXGlobalInitFunc - Generates code for initializing global
3459   /// variables.
3460   void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
3461                                  ArrayRef<llvm::Function *> CXXThreadLocals,
3462                                  Address Guard = Address::invalid());
3463
3464   /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
3465   /// variables.
3466   void GenerateCXXGlobalDtorsFunc(
3467       llvm::Function *Fn,
3468       const std::vector<std::pair<llvm::WeakTrackingVH, llvm::Constant *>>
3469           &DtorsAndObjects);
3470
3471   void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
3472                                         const VarDecl *D,
3473                                         llvm::GlobalVariable *Addr,
3474                                         bool PerformInit);
3475
3476   void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
3477   
3478   void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
3479
3480   void enterFullExpression(const ExprWithCleanups *E) {
3481     if (E->getNumObjects() == 0) return;
3482     enterNonTrivialFullExpression(E);
3483   }
3484   void enterNonTrivialFullExpression(const ExprWithCleanups *E);
3485
3486   void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
3487
3488   void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
3489
3490   RValue EmitAtomicExpr(AtomicExpr *E);
3491
3492   //===--------------------------------------------------------------------===//
3493   //                         Annotations Emission
3494   //===--------------------------------------------------------------------===//
3495
3496   /// Emit an annotation call (intrinsic or builtin).
3497   llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
3498                                   llvm::Value *AnnotatedVal,
3499                                   StringRef AnnotationStr,
3500                                   SourceLocation Location);
3501
3502   /// Emit local annotations for the local variable V, declared by D.
3503   void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
3504
3505   /// Emit field annotations for the given field & value. Returns the
3506   /// annotation result.
3507   Address EmitFieldAnnotations(const FieldDecl *D, Address V);
3508
3509   //===--------------------------------------------------------------------===//
3510   //                             Internal Helpers
3511   //===--------------------------------------------------------------------===//
3512
3513   /// ContainsLabel - Return true if the statement contains a label in it.  If
3514   /// this statement is not executed normally, it not containing a label means
3515   /// that we can just remove the code.
3516   static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
3517
3518   /// containsBreak - Return true if the statement contains a break out of it.
3519   /// If the statement (recursively) contains a switch or loop with a break
3520   /// inside of it, this is fine.
3521   static bool containsBreak(const Stmt *S);
3522
3523   /// Determine if the given statement might introduce a declaration into the
3524   /// current scope, by being a (possibly-labelled) DeclStmt.
3525   static bool mightAddDeclToScope(const Stmt *S);
3526   
3527   /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3528   /// to a constant, or if it does but contains a label, return false.  If it
3529   /// constant folds return true and set the boolean result in Result.
3530   bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
3531                                     bool AllowLabels = false);
3532
3533   /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3534   /// to a constant, or if it does but contains a label, return false.  If it
3535   /// constant folds return true and set the folded value.
3536   bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
3537                                     bool AllowLabels = false);
3538
3539   /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
3540   /// if statement) to the specified blocks.  Based on the condition, this might
3541   /// try to simplify the codegen of the conditional based on the branch.
3542   /// TrueCount should be the number of times we expect the condition to
3543   /// evaluate to true based on PGO data.
3544   void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
3545                             llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
3546
3547   /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is
3548   /// nonnull, if \p LHS is marked _Nonnull.
3549   void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc);
3550
3551   /// \brief Emit a description of a type in a format suitable for passing to
3552   /// a runtime sanitizer handler.
3553   llvm::Constant *EmitCheckTypeDescriptor(QualType T);
3554
3555   /// \brief Convert a value into a format suitable for passing to a runtime
3556   /// sanitizer handler.
3557   llvm::Value *EmitCheckValue(llvm::Value *V);
3558
3559   /// \brief Emit a description of a source location in a format suitable for
3560   /// passing to a runtime sanitizer handler.
3561   llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
3562
3563   /// \brief Create a basic block that will call a handler function in a
3564   /// sanitizer runtime with the provided arguments, and create a conditional
3565   /// branch to it.
3566   void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3567                  SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
3568                  ArrayRef<llvm::Value *> DynamicArgs);
3569
3570   /// \brief Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
3571   /// if Cond if false.
3572   void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
3573                             llvm::ConstantInt *TypeId, llvm::Value *Ptr,
3574                             ArrayRef<llvm::Constant *> StaticArgs);
3575
3576   /// \brief Create a basic block that will call the trap intrinsic, and emit a
3577   /// conditional branch to it, for the -ftrapv checks.
3578   void EmitTrapCheck(llvm::Value *Checked);
3579
3580   /// \brief Emit a call to trap or debugtrap and attach function attribute
3581   /// "trap-func-name" if specified.
3582   llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
3583
3584   /// \brief Emit a stub for the cross-DSO CFI check function.
3585   void EmitCfiCheckStub();
3586
3587   /// \brief Emit a cross-DSO CFI failure handling function.
3588   void EmitCfiCheckFail();
3589
3590   /// \brief Create a check for a function parameter that may potentially be
3591   /// declared as non-null.
3592   void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
3593                            AbstractCallee AC, unsigned ParmNum);
3594
3595   /// EmitCallArg - Emit a single call argument.
3596   void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
3597
3598   /// EmitDelegateCallArg - We are performing a delegate call; that
3599   /// is, the current function is delegating to another one.  Produce
3600   /// a r-value suitable for passing the given parameter.
3601   void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
3602                            SourceLocation loc);
3603
3604   /// SetFPAccuracy - Set the minimum required accuracy of the given floating
3605   /// point operation, expressed as the maximum relative error in ulp.
3606   void SetFPAccuracy(llvm::Value *Val, float Accuracy);
3607
3608 private:
3609   llvm::MDNode *getRangeForLoadFromType(QualType Ty);
3610   void EmitReturnOfRValue(RValue RV, QualType Ty);
3611
3612   void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
3613
3614   llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
3615   DeferredReplacements;
3616
3617   /// Set the address of a local variable.
3618   void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
3619     assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
3620     LocalDeclMap.insert({VD, Addr});
3621   }
3622
3623   /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
3624   /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
3625   ///
3626   /// \param AI - The first function argument of the expansion.
3627   void ExpandTypeFromArgs(QualType Ty, LValue Dst,
3628                           SmallVectorImpl<llvm::Value *>::iterator &AI);
3629
3630   /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
3631   /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
3632   /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
3633   void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
3634                         SmallVectorImpl<llvm::Value *> &IRCallArgs,
3635                         unsigned &IRCallArgPos);
3636
3637   llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
3638                             const Expr *InputExpr, std::string &ConstraintStr);
3639
3640   llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
3641                                   LValue InputValue, QualType InputType,
3642                                   std::string &ConstraintStr,
3643                                   SourceLocation Loc);
3644
3645   /// \brief Attempts to statically evaluate the object size of E. If that
3646   /// fails, emits code to figure the size of E out for us. This is
3647   /// pass_object_size aware.
3648   ///
3649   /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
3650   llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
3651                                                llvm::IntegerType *ResType,
3652                                                llvm::Value *EmittedE);
3653
3654   /// \brief Emits the size of E, as required by __builtin_object_size. This
3655   /// function is aware of pass_object_size parameters, and will act accordingly
3656   /// if E is a parameter with the pass_object_size attribute.
3657   llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
3658                                      llvm::IntegerType *ResType,
3659                                      llvm::Value *EmittedE);
3660
3661 public:
3662 #ifndef NDEBUG
3663   // Determine whether the given argument is an Objective-C method
3664   // that may have type parameters in its signature.
3665   static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
3666     const DeclContext *dc = method->getDeclContext();
3667     if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
3668       return classDecl->getTypeParamListAsWritten();
3669     }
3670
3671     if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
3672       return catDecl->getTypeParamList();
3673     }
3674
3675     return false;
3676   }
3677
3678   template<typename T>
3679   static bool isObjCMethodWithTypeParams(const T *) { return false; }
3680 #endif
3681
3682   enum class EvaluationOrder {
3683     ///! No language constraints on evaluation order.
3684     Default,
3685     ///! Language semantics require left-to-right evaluation.
3686     ForceLeftToRight,
3687     ///! Language semantics require right-to-left evaluation.
3688     ForceRightToLeft
3689   };
3690
3691   /// EmitCallArgs - Emit call arguments for a function.
3692   template <typename T>
3693   void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
3694                     llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3695                     AbstractCallee AC = AbstractCallee(),
3696                     unsigned ParamsToSkip = 0,
3697                     EvaluationOrder Order = EvaluationOrder::Default) {
3698     SmallVector<QualType, 16> ArgTypes;
3699     CallExpr::const_arg_iterator Arg = ArgRange.begin();
3700
3701     assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
3702            "Can't skip parameters if type info is not provided");
3703     if (CallArgTypeInfo) {
3704 #ifndef NDEBUG
3705       bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
3706 #endif
3707
3708       // First, use the argument types that the type info knows about
3709       for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
3710                 E = CallArgTypeInfo->param_type_end();
3711            I != E; ++I, ++Arg) {
3712         assert(Arg != ArgRange.end() && "Running over edge of argument list!");
3713         assert((isGenericMethod ||
3714                 ((*I)->isVariablyModifiedType() ||
3715                  (*I).getNonReferenceType()->isObjCRetainableType() ||
3716                  getContext()
3717                          .getCanonicalType((*I).getNonReferenceType())
3718                          .getTypePtr() ==
3719                      getContext()
3720                          .getCanonicalType((*Arg)->getType())
3721                          .getTypePtr())) &&
3722                "type mismatch in call argument!");
3723         ArgTypes.push_back(*I);
3724       }
3725     }
3726
3727     // Either we've emitted all the call args, or we have a call to variadic
3728     // function.
3729     assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
3730             CallArgTypeInfo->isVariadic()) &&
3731            "Extra arguments in non-variadic function!");
3732
3733     // If we still have any arguments, emit them using the type of the argument.
3734     for (auto *A : llvm::make_range(Arg, ArgRange.end()))
3735       ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType());
3736
3737     EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order);
3738   }
3739
3740   void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
3741                     llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3742                     AbstractCallee AC = AbstractCallee(),
3743                     unsigned ParamsToSkip = 0,
3744                     EvaluationOrder Order = EvaluationOrder::Default);
3745
3746   /// EmitPointerWithAlignment - Given an expression with a pointer
3747   /// type, emit the value and compute our best estimate of the
3748   /// alignment of the pointee.
3749   ///
3750   /// Note that this function will conservatively fall back on the type
3751   /// when it doesn't 
3752   ///
3753   /// \param Source - If non-null, this will be initialized with
3754   ///   information about the source of the alignment.  Note that this
3755   ///   function will conservatively fall back on the type when it
3756   ///   doesn't recognize the expression, which means that sometimes
3757   ///   
3758   ///   a worst-case One
3759   ///   reasonable way to use this information is when there's a
3760   ///   language guarantee that the pointer must be aligned to some
3761   ///   stricter value, and we're simply trying to ensure that
3762   ///   sufficiently obvious uses of under-aligned objects don't get
3763   ///   miscompiled; for example, a placement new into the address of
3764   ///   a local variable.  In such a case, it's quite reasonable to
3765   ///   just ignore the returned alignment when it isn't from an
3766   ///   explicit source.
3767   Address EmitPointerWithAlignment(const Expr *Addr,
3768                                    AlignmentSource *Source = nullptr);
3769
3770   void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
3771
3772 private:
3773   QualType getVarArgType(const Expr *Arg);
3774
3775   const TargetCodeGenInfo &getTargetHooks() const {
3776     return CGM.getTargetCodeGenInfo();
3777   }
3778
3779   void EmitDeclMetadata();
3780
3781   BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
3782                                   const AutoVarEmission &emission);
3783
3784   void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
3785
3786   llvm::Value *GetValueForARMHint(unsigned BuiltinID);
3787 };
3788
3789 /// Helper class with most of the code for saving a value for a
3790 /// conditional expression cleanup.
3791 struct DominatingLLVMValue {
3792   typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
3793
3794   /// Answer whether the given value needs extra work to be saved.
3795   static bool needsSaving(llvm::Value *value) {
3796     // If it's not an instruction, we don't need to save.
3797     if (!isa<llvm::Instruction>(value)) return false;
3798
3799     // If it's an instruction in the entry block, we don't need to save.
3800     llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
3801     return (block != &block->getParent()->getEntryBlock());
3802   }
3803
3804   /// Try to save the given value.
3805   static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
3806     if (!needsSaving(value)) return saved_type(value, false);
3807
3808     // Otherwise, we need an alloca.
3809     auto align = CharUnits::fromQuantity(
3810               CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
3811     Address alloca =
3812       CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
3813     CGF.Builder.CreateStore(value, alloca);
3814
3815     return saved_type(alloca.getPointer(), true);
3816   }
3817
3818   static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
3819     // If the value says it wasn't saved, trust that it's still dominating.
3820     if (!value.getInt()) return value.getPointer();
3821
3822     // Otherwise, it should be an alloca instruction, as set up in save().
3823     auto alloca = cast<llvm::AllocaInst>(value.getPointer());
3824     return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
3825   }
3826 };
3827
3828 /// A partial specialization of DominatingValue for llvm::Values that
3829 /// might be llvm::Instructions.
3830 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
3831   typedef T *type;
3832   static type restore(CodeGenFunction &CGF, saved_type value) {
3833     return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
3834   }
3835 };
3836
3837 /// A specialization of DominatingValue for Address.
3838 template <> struct DominatingValue<Address> {
3839   typedef Address type;
3840
3841   struct saved_type {
3842     DominatingLLVMValue::saved_type SavedValue;
3843     CharUnits Alignment;
3844   };
3845
3846   static bool needsSaving(type value) {
3847     return DominatingLLVMValue::needsSaving(value.getPointer());
3848   }
3849   static saved_type save(CodeGenFunction &CGF, type value) {
3850     return { DominatingLLVMValue::save(CGF, value.getPointer()),
3851              value.getAlignment() };
3852   }
3853   static type restore(CodeGenFunction &CGF, saved_type value) {
3854     return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
3855                    value.Alignment);
3856   }
3857 };
3858
3859 /// A specialization of DominatingValue for RValue.
3860 template <> struct DominatingValue<RValue> {
3861   typedef RValue type;
3862   class saved_type {
3863     enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
3864                 AggregateAddress, ComplexAddress };
3865
3866     llvm::Value *Value;
3867     unsigned K : 3;
3868     unsigned Align : 29;
3869     saved_type(llvm::Value *v, Kind k, unsigned a = 0)
3870       : Value(v), K(k), Align(a) {}
3871
3872   public:
3873     static bool needsSaving(RValue value);
3874     static saved_type save(CodeGenFunction &CGF, RValue value);
3875     RValue restore(CodeGenFunction &CGF);
3876
3877     // implementations in CGCleanup.cpp
3878   };
3879
3880   static bool needsSaving(type value) {
3881     return saved_type::needsSaving(value);
3882   }
3883   static saved_type save(CodeGenFunction &CGF, type value) {
3884     return saved_type::save(CGF, value);
3885   }
3886   static type restore(CodeGenFunction &CGF, saved_type value) {
3887     return value.restore(CGF);
3888   }
3889 };
3890
3891 }  // end namespace CodeGen
3892 }  // end namespace clang
3893
3894 #endif