]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CodeGenFunction.h
Merge ^/head r318964 through r319164.
[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                         LValueBaseInfo BaseInfo =
1890                             LValueBaseInfo(AlignmentSource::Type)) {
1891     return LValue::MakeAddr(Addr, T, getContext(), BaseInfo,
1892                             CGM.getTBAAInfo(T));
1893   }
1894
1895   LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
1896                         LValueBaseInfo BaseInfo =
1897                             LValueBaseInfo(AlignmentSource::Type)) {
1898     return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
1899                             BaseInfo, CGM.getTBAAInfo(T));
1900   }
1901
1902   LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
1903   LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
1904   CharUnits getNaturalTypeAlignment(QualType T,
1905                                     LValueBaseInfo *BaseInfo = nullptr,
1906                                     bool forPointeeType = false);
1907   CharUnits getNaturalPointeeTypeAlignment(QualType T,
1908                                            LValueBaseInfo *BaseInfo = nullptr);
1909
1910   Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy,
1911                               LValueBaseInfo *BaseInfo = nullptr);
1912   LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy);
1913
1914   Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
1915                             LValueBaseInfo *BaseInfo = nullptr);
1916   LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
1917
1918   /// CreateTempAlloca - This creates a alloca and inserts it into the entry
1919   /// block. The caller is responsible for setting an appropriate alignment on
1920   /// the alloca.
1921   llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
1922                                      const Twine &Name = "tmp");
1923   Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
1924                            const Twine &Name = "tmp");
1925
1926   /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
1927   /// default ABI alignment of the given LLVM type.
1928   ///
1929   /// IMPORTANT NOTE: This is *not* generally the right alignment for
1930   /// any given AST type that happens to have been lowered to the
1931   /// given IR type.  This should only ever be used for function-local,
1932   /// IR-driven manipulations like saving and restoring a value.  Do
1933   /// not hand this address off to arbitrary IRGen routines, and especially
1934   /// do not pass it as an argument to a function that might expect a
1935   /// properly ABI-aligned value.
1936   Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
1937                                        const Twine &Name = "tmp");
1938
1939   /// InitTempAlloca - Provide an initial value for the given alloca which
1940   /// will be observable at all locations in the function.
1941   ///
1942   /// The address should be something that was returned from one of
1943   /// the CreateTempAlloca or CreateMemTemp routines, and the
1944   /// initializer must be valid in the entry block (i.e. it must
1945   /// either be a constant or an argument value).
1946   void InitTempAlloca(Address Alloca, llvm::Value *Value);
1947
1948   /// CreateIRTemp - Create a temporary IR object of the given type, with
1949   /// appropriate alignment. This routine should only be used when an temporary
1950   /// value needs to be stored into an alloca (for example, to avoid explicit
1951   /// PHI construction), but the type is the IR type, not the type appropriate
1952   /// for storing in memory.
1953   ///
1954   /// That is, this is exactly equivalent to CreateMemTemp, but calling
1955   /// ConvertType instead of ConvertTypeForMem.
1956   Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
1957
1958   /// CreateMemTemp - Create a temporary memory object of the given type, with
1959   /// appropriate alignment.
1960   Address CreateMemTemp(QualType T, const Twine &Name = "tmp");
1961   Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp");
1962
1963   /// CreateAggTemp - Create a temporary memory object for the given
1964   /// aggregate type.
1965   AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
1966     return AggValueSlot::forAddr(CreateMemTemp(T, Name),
1967                                  T.getQualifiers(),
1968                                  AggValueSlot::IsNotDestructed,
1969                                  AggValueSlot::DoesNotNeedGCBarriers,
1970                                  AggValueSlot::IsNotAliased);
1971   }
1972
1973   /// Emit a cast to void* in the appropriate address space.
1974   llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
1975
1976   /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1977   /// expression and compare the result against zero, returning an Int1Ty value.
1978   llvm::Value *EvaluateExprAsBool(const Expr *E);
1979
1980   /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1981   void EmitIgnoredExpr(const Expr *E);
1982
1983   /// EmitAnyExpr - Emit code to compute the specified expression which can have
1984   /// any type.  The result is returned as an RValue struct.  If this is an
1985   /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1986   /// the result should be returned.
1987   ///
1988   /// \param ignoreResult True if the resulting value isn't used.
1989   RValue EmitAnyExpr(const Expr *E,
1990                      AggValueSlot aggSlot = AggValueSlot::ignored(),
1991                      bool ignoreResult = false);
1992
1993   // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1994   // or the value of the expression, depending on how va_list is defined.
1995   Address EmitVAListRef(const Expr *E);
1996
1997   /// Emit a "reference" to a __builtin_ms_va_list; this is
1998   /// always the value of the expression, because a __builtin_ms_va_list is a
1999   /// pointer to a char.
2000   Address EmitMSVAListRef(const Expr *E);
2001
2002   /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
2003   /// always be accessible even if no aggregate location is provided.
2004   RValue EmitAnyExprToTemp(const Expr *E);
2005
2006   /// EmitAnyExprToMem - Emits the code necessary to evaluate an
2007   /// arbitrary expression into the given memory location.
2008   void EmitAnyExprToMem(const Expr *E, Address Location,
2009                         Qualifiers Quals, bool IsInitializer);
2010
2011   void EmitAnyExprToExn(const Expr *E, Address Addr);
2012
2013   /// EmitExprAsInit - Emits the code necessary to initialize a
2014   /// location in memory with the given initializer.
2015   void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2016                       bool capturedByInit);
2017
2018   /// hasVolatileMember - returns true if aggregate type has a volatile
2019   /// member.
2020   bool hasVolatileMember(QualType T) {
2021     if (const RecordType *RT = T->getAs<RecordType>()) {
2022       const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2023       return RD->hasVolatileMember();
2024     }
2025     return false;
2026   }
2027   /// EmitAggregateCopy - Emit an aggregate assignment.
2028   ///
2029   /// The difference to EmitAggregateCopy is that tail padding is not copied.
2030   /// This is required for correctness when assigning non-POD structures in C++.
2031   void EmitAggregateAssign(Address DestPtr, Address SrcPtr,
2032                            QualType EltTy) {
2033     bool IsVolatile = hasVolatileMember(EltTy);
2034     EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true);
2035   }
2036
2037   void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr,
2038                              QualType DestTy, QualType SrcTy) {
2039     EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
2040                       /*IsAssignment=*/false);
2041   }
2042
2043   /// EmitAggregateCopy - Emit an aggregate copy.
2044   ///
2045   /// \param isVolatile - True iff either the source or the destination is
2046   /// volatile.
2047   /// \param isAssignment - If false, allow padding to be copied.  This often
2048   /// yields more efficient.
2049   void EmitAggregateCopy(Address DestPtr, Address SrcPtr,
2050                          QualType EltTy, bool isVolatile=false,
2051                          bool isAssignment = false);
2052
2053   /// GetAddrOfLocalVar - Return the address of a local variable.
2054   Address GetAddrOfLocalVar(const VarDecl *VD) {
2055     auto it = LocalDeclMap.find(VD);
2056     assert(it != LocalDeclMap.end() &&
2057            "Invalid argument to GetAddrOfLocalVar(), no decl!");
2058     return it->second;
2059   }
2060
2061   /// getOpaqueLValueMapping - Given an opaque value expression (which
2062   /// must be mapped to an l-value), return its mapping.
2063   const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
2064     assert(OpaqueValueMapping::shouldBindAsLValue(e));
2065
2066     llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
2067       it = OpaqueLValues.find(e);
2068     assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
2069     return it->second;
2070   }
2071
2072   /// getOpaqueRValueMapping - Given an opaque value expression (which
2073   /// must be mapped to an r-value), return its mapping.
2074   const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
2075     assert(!OpaqueValueMapping::shouldBindAsLValue(e));
2076
2077     llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
2078       it = OpaqueRValues.find(e);
2079     assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
2080     return it->second;
2081   }
2082
2083   /// Get the index of the current ArrayInitLoopExpr, if any.
2084   llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2085
2086   /// getAccessedFieldNo - Given an encoded value and a result number, return
2087   /// the input field number being accessed.
2088   static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2089
2090   llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
2091   llvm::BasicBlock *GetIndirectGotoBlock();
2092
2093   /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
2094   static bool IsWrappedCXXThis(const Expr *E);
2095
2096   /// EmitNullInitialization - Generate code to set a value of the given type to
2097   /// null, If the type contains data member pointers, they will be initialized
2098   /// to -1 in accordance with the Itanium C++ ABI.
2099   void EmitNullInitialization(Address DestPtr, QualType Ty);
2100
2101   /// Emits a call to an LLVM variable-argument intrinsic, either
2102   /// \c llvm.va_start or \c llvm.va_end.
2103   /// \param ArgValue A reference to the \c va_list as emitted by either
2104   /// \c EmitVAListRef or \c EmitMSVAListRef.
2105   /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2106   /// calls \c llvm.va_end.
2107   llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2108
2109   /// Generate code to get an argument from the passed in pointer
2110   /// and update it accordingly.
2111   /// \param VE The \c VAArgExpr for which to generate code.
2112   /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2113   /// either \c EmitVAListRef or \c EmitMSVAListRef.
2114   /// \returns A pointer to the argument.
2115   // FIXME: We should be able to get rid of this method and use the va_arg
2116   // instruction in LLVM instead once it works well enough.
2117   Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
2118
2119   /// emitArrayLength - Compute the length of an array, even if it's a
2120   /// VLA, and drill down to the base element type.
2121   llvm::Value *emitArrayLength(const ArrayType *arrayType,
2122                                QualType &baseType,
2123                                Address &addr);
2124
2125   /// EmitVLASize - Capture all the sizes for the VLA expressions in
2126   /// the given variably-modified type and store them in the VLASizeMap.
2127   ///
2128   /// This function can be called with a null (unreachable) insert point.
2129   void EmitVariablyModifiedType(QualType Ty);
2130
2131   /// getVLASize - Returns an LLVM value that corresponds to the size,
2132   /// in non-variably-sized elements, of a variable length array type,
2133   /// plus that largest non-variably-sized element type.  Assumes that
2134   /// the type has already been emitted with EmitVariablyModifiedType.
2135   std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
2136   std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
2137
2138   /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2139   /// generating code for an C++ member function.
2140   llvm::Value *LoadCXXThis() {
2141     assert(CXXThisValue && "no 'this' value for this function");
2142     return CXXThisValue;
2143   }
2144   Address LoadCXXThisAddress();
2145
2146   /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2147   /// virtual bases.
2148   // FIXME: Every place that calls LoadCXXVTT is something
2149   // that needs to be abstracted properly.
2150   llvm::Value *LoadCXXVTT() {
2151     assert(CXXStructorImplicitParamValue && "no VTT value for this function");
2152     return CXXStructorImplicitParamValue;
2153   }
2154
2155   /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
2156   /// complete class to the given direct base.
2157   Address
2158   GetAddressOfDirectBaseInCompleteClass(Address Value,
2159                                         const CXXRecordDecl *Derived,
2160                                         const CXXRecordDecl *Base,
2161                                         bool BaseIsVirtual);
2162
2163   static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2164
2165   /// GetAddressOfBaseClass - This function will add the necessary delta to the
2166   /// load of 'this' and returns address of the base class.
2167   Address GetAddressOfBaseClass(Address Value,
2168                                 const CXXRecordDecl *Derived,
2169                                 CastExpr::path_const_iterator PathBegin,
2170                                 CastExpr::path_const_iterator PathEnd,
2171                                 bool NullCheckValue, SourceLocation Loc);
2172
2173   Address GetAddressOfDerivedClass(Address Value,
2174                                    const CXXRecordDecl *Derived,
2175                                    CastExpr::path_const_iterator PathBegin,
2176                                    CastExpr::path_const_iterator PathEnd,
2177                                    bool NullCheckValue);
2178
2179   /// GetVTTParameter - Return the VTT parameter that should be passed to a
2180   /// base constructor/destructor with virtual bases.
2181   /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2182   /// to ItaniumCXXABI.cpp together with all the references to VTT.
2183   llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2184                                bool Delegating);
2185
2186   void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2187                                       CXXCtorType CtorType,
2188                                       const FunctionArgList &Args,
2189                                       SourceLocation Loc);
2190   // It's important not to confuse this and the previous function. Delegating
2191   // constructors are the C++0x feature. The constructor delegate optimization
2192   // is used to reduce duplication in the base and complete consturctors where
2193   // they are substantially the same.
2194   void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2195                                         const FunctionArgList &Args);
2196
2197   /// Emit a call to an inheriting constructor (that is, one that invokes a
2198   /// constructor inherited from a base class) by inlining its definition. This
2199   /// is necessary if the ABI does not support forwarding the arguments to the
2200   /// base class constructor (because they're variadic or similar).
2201   void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2202                                                CXXCtorType CtorType,
2203                                                bool ForVirtualBase,
2204                                                bool Delegating,
2205                                                CallArgList &Args);
2206
2207   /// Emit a call to a constructor inherited from a base class, passing the
2208   /// current constructor's arguments along unmodified (without even making
2209   /// a copy).
2210   void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
2211                                        bool ForVirtualBase, Address This,
2212                                        bool InheritedFromVBase,
2213                                        const CXXInheritedCtorInitExpr *E);
2214
2215   void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2216                               bool ForVirtualBase, bool Delegating,
2217                               Address This, const CXXConstructExpr *E);
2218
2219   void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2220                               bool ForVirtualBase, bool Delegating,
2221                               Address This, CallArgList &Args);
2222
2223   /// Emit assumption load for all bases. Requires to be be called only on
2224   /// most-derived class and not under construction of the object.
2225   void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2226
2227   /// Emit assumption that vptr load == global vtable.
2228   void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2229
2230   void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2231                                       Address This, Address Src,
2232                                       const CXXConstructExpr *E);
2233
2234   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2235                                   const ArrayType *ArrayTy,
2236                                   Address ArrayPtr,
2237                                   const CXXConstructExpr *E,
2238                                   bool ZeroInitialization = false);
2239
2240   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2241                                   llvm::Value *NumElements,
2242                                   Address ArrayPtr,
2243                                   const CXXConstructExpr *E,
2244                                   bool ZeroInitialization = false);
2245
2246   static Destroyer destroyCXXObject;
2247
2248   void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
2249                              bool ForVirtualBase, bool Delegating,
2250                              Address This);
2251
2252   void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2253                                llvm::Type *ElementTy, Address NewPtr,
2254                                llvm::Value *NumElements,
2255                                llvm::Value *AllocSizeWithoutCookie);
2256
2257   void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2258                         Address Ptr);
2259
2260   llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
2261   void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2262
2263   llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
2264   void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
2265
2266   void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
2267                       QualType DeleteTy, llvm::Value *NumElements = nullptr,
2268                       CharUnits CookieSize = CharUnits());
2269
2270   RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
2271                                   const Expr *Arg, bool IsDelete);
2272
2273   llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2274   llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2275   Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
2276
2277   /// \brief Situations in which we might emit a check for the suitability of a
2278   ///        pointer or glvalue.
2279   enum TypeCheckKind {
2280     /// Checking the operand of a load. Must be suitably sized and aligned.
2281     TCK_Load,
2282     /// Checking the destination of a store. Must be suitably sized and aligned.
2283     TCK_Store,
2284     /// Checking the bound value in a reference binding. Must be suitably sized
2285     /// and aligned, but is not required to refer to an object (until the
2286     /// reference is used), per core issue 453.
2287     TCK_ReferenceBinding,
2288     /// Checking the object expression in a non-static data member access. Must
2289     /// be an object within its lifetime.
2290     TCK_MemberAccess,
2291     /// Checking the 'this' pointer for a call to a non-static member function.
2292     /// Must be an object within its lifetime.
2293     TCK_MemberCall,
2294     /// Checking the 'this' pointer for a constructor call.
2295     TCK_ConstructorCall,
2296     /// Checking the operand of a static_cast to a derived pointer type. Must be
2297     /// null or an object within its lifetime.
2298     TCK_DowncastPointer,
2299     /// Checking the operand of a static_cast to a derived reference type. Must
2300     /// be an object within its lifetime.
2301     TCK_DowncastReference,
2302     /// Checking the operand of a cast to a base object. Must be suitably sized
2303     /// and aligned.
2304     TCK_Upcast,
2305     /// Checking the operand of a cast to a virtual base object. Must be an
2306     /// object within its lifetime.
2307     TCK_UpcastToVirtualBase,
2308     /// Checking the value assigned to a _Nonnull pointer. Must not be null.
2309     TCK_NonnullAssign
2310   };
2311
2312   /// \brief Whether any type-checking sanitizers are enabled. If \c false,
2313   /// calls to EmitTypeCheck can be skipped.
2314   bool sanitizePerformTypeCheck() const;
2315
2316   /// \brief Emit a check that \p V is the address of storage of the
2317   /// appropriate size and alignment for an object of type \p Type.
2318   void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
2319                      QualType Type, CharUnits Alignment = CharUnits::Zero(),
2320                      SanitizerSet SkippedChecks = SanitizerSet());
2321
2322   /// \brief Emit a check that \p Base points into an array object, which
2323   /// we can access at index \p Index. \p Accessed should be \c false if we
2324   /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
2325   void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
2326                        QualType IndexType, bool Accessed);
2327
2328   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2329                                        bool isInc, bool isPre);
2330   ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
2331                                          bool isInc, bool isPre);
2332
2333   void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
2334                                llvm::Value *OffsetValue = nullptr) {
2335     Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2336                                       OffsetValue);
2337   }
2338
2339   /// Converts Location to a DebugLoc, if debug information is enabled.
2340   llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
2341
2342
2343   //===--------------------------------------------------------------------===//
2344   //                            Declaration Emission
2345   //===--------------------------------------------------------------------===//
2346
2347   /// EmitDecl - Emit a declaration.
2348   ///
2349   /// This function can be called with a null (unreachable) insert point.
2350   void EmitDecl(const Decl &D);
2351
2352   /// EmitVarDecl - Emit a local variable declaration.
2353   ///
2354   /// This function can be called with a null (unreachable) insert point.
2355   void EmitVarDecl(const VarDecl &D);
2356
2357   void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2358                       bool capturedByInit);
2359
2360   typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
2361                              llvm::Value *Address);
2362
2363   /// \brief Determine whether the given initializer is trivial in the sense
2364   /// that it requires no code to be generated.
2365   bool isTrivialInitializer(const Expr *Init);
2366
2367   /// EmitAutoVarDecl - Emit an auto variable declaration.
2368   ///
2369   /// This function can be called with a null (unreachable) insert point.
2370   void EmitAutoVarDecl(const VarDecl &D);
2371
2372   class AutoVarEmission {
2373     friend class CodeGenFunction;
2374
2375     const VarDecl *Variable;
2376
2377     /// The address of the alloca.  Invalid if the variable was emitted
2378     /// as a global constant.
2379     Address Addr;
2380
2381     llvm::Value *NRVOFlag;
2382
2383     /// True if the variable is a __block variable.
2384     bool IsByRef;
2385
2386     /// True if the variable is of aggregate type and has a constant
2387     /// initializer.
2388     bool IsConstantAggregate;
2389
2390     /// Non-null if we should use lifetime annotations.
2391     llvm::Value *SizeForLifetimeMarkers;
2392
2393     struct Invalid {};
2394     AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {}
2395
2396     AutoVarEmission(const VarDecl &variable)
2397       : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
2398         IsByRef(false), IsConstantAggregate(false),
2399         SizeForLifetimeMarkers(nullptr) {}
2400
2401     bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
2402
2403   public:
2404     static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
2405
2406     bool useLifetimeMarkers() const {
2407       return SizeForLifetimeMarkers != nullptr;
2408     }
2409     llvm::Value *getSizeForLifetimeMarkers() const {
2410       assert(useLifetimeMarkers());
2411       return SizeForLifetimeMarkers;
2412     }
2413
2414     /// Returns the raw, allocated address, which is not necessarily
2415     /// the address of the object itself.
2416     Address getAllocatedAddress() const {
2417       return Addr;
2418     }
2419
2420     /// Returns the address of the object within this declaration.
2421     /// Note that this does not chase the forwarding pointer for
2422     /// __block decls.
2423     Address getObjectAddress(CodeGenFunction &CGF) const {
2424       if (!IsByRef) return Addr;
2425
2426       return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
2427     }
2428   };
2429   AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
2430   void EmitAutoVarInit(const AutoVarEmission &emission);
2431   void EmitAutoVarCleanups(const AutoVarEmission &emission);  
2432   void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
2433                               QualType::DestructionKind dtorKind);
2434
2435   void EmitStaticVarDecl(const VarDecl &D,
2436                          llvm::GlobalValue::LinkageTypes Linkage);
2437
2438   class ParamValue {
2439     llvm::Value *Value;
2440     unsigned Alignment;
2441     ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
2442   public:
2443     static ParamValue forDirect(llvm::Value *value) {
2444       return ParamValue(value, 0);
2445     }
2446     static ParamValue forIndirect(Address addr) {
2447       assert(!addr.getAlignment().isZero());
2448       return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
2449     }
2450
2451     bool isIndirect() const { return Alignment != 0; }
2452     llvm::Value *getAnyValue() const { return Value; }
2453     
2454     llvm::Value *getDirectValue() const {
2455       assert(!isIndirect());
2456       return Value;
2457     }
2458
2459     Address getIndirectAddress() const {
2460       assert(isIndirect());
2461       return Address(Value, CharUnits::fromQuantity(Alignment));
2462     }
2463   };
2464
2465   /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
2466   void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
2467
2468   /// protectFromPeepholes - Protect a value that we're intending to
2469   /// store to the side, but which will probably be used later, from
2470   /// aggressive peepholing optimizations that might delete it.
2471   ///
2472   /// Pass the result to unprotectFromPeepholes to declare that
2473   /// protection is no longer required.
2474   ///
2475   /// There's no particular reason why this shouldn't apply to
2476   /// l-values, it's just that no existing peepholes work on pointers.
2477   PeepholeProtection protectFromPeepholes(RValue rvalue);
2478   void unprotectFromPeepholes(PeepholeProtection protection);
2479
2480   void EmitAlignmentAssumption(llvm::Value *PtrValue, llvm::Value *Alignment,
2481                                llvm::Value *OffsetValue = nullptr) {
2482     Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2483                                       OffsetValue);
2484   }
2485
2486   //===--------------------------------------------------------------------===//
2487   //                             Statement Emission
2488   //===--------------------------------------------------------------------===//
2489
2490   /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
2491   void EmitStopPoint(const Stmt *S);
2492
2493   /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
2494   /// this function even if there is no current insertion point.
2495   ///
2496   /// This function may clear the current insertion point; callers should use
2497   /// EnsureInsertPoint if they wish to subsequently generate code without first
2498   /// calling EmitBlock, EmitBranch, or EmitStmt.
2499   void EmitStmt(const Stmt *S);
2500
2501   /// EmitSimpleStmt - Try to emit a "simple" statement which does not
2502   /// necessarily require an insertion point or debug information; typically
2503   /// because the statement amounts to a jump or a container of other
2504   /// statements.
2505   ///
2506   /// \return True if the statement was handled.
2507   bool EmitSimpleStmt(const Stmt *S);
2508
2509   Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
2510                            AggValueSlot AVS = AggValueSlot::ignored());
2511   Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
2512                                        bool GetLast = false,
2513                                        AggValueSlot AVS =
2514                                                 AggValueSlot::ignored());
2515
2516   /// EmitLabel - Emit the block for the given label. It is legal to call this
2517   /// function even if there is no current insertion point.
2518   void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
2519
2520   void EmitLabelStmt(const LabelStmt &S);
2521   void EmitAttributedStmt(const AttributedStmt &S);
2522   void EmitGotoStmt(const GotoStmt &S);
2523   void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
2524   void EmitIfStmt(const IfStmt &S);
2525
2526   void EmitWhileStmt(const WhileStmt &S,
2527                      ArrayRef<const Attr *> Attrs = None);
2528   void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
2529   void EmitForStmt(const ForStmt &S,
2530                    ArrayRef<const Attr *> Attrs = None);
2531   void EmitReturnStmt(const ReturnStmt &S);
2532   void EmitDeclStmt(const DeclStmt &S);
2533   void EmitBreakStmt(const BreakStmt &S);
2534   void EmitContinueStmt(const ContinueStmt &S);
2535   void EmitSwitchStmt(const SwitchStmt &S);
2536   void EmitDefaultStmt(const DefaultStmt &S);
2537   void EmitCaseStmt(const CaseStmt &S);
2538   void EmitCaseStmtRange(const CaseStmt &S);
2539   void EmitAsmStmt(const AsmStmt &S);
2540
2541   void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
2542   void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
2543   void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
2544   void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
2545   void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
2546
2547   void EmitCoroutineBody(const CoroutineBodyStmt &S);
2548   void EmitCoreturnStmt(const CoreturnStmt &S);
2549   RValue EmitCoawaitExpr(const CoawaitExpr &E,
2550                          AggValueSlot aggSlot = AggValueSlot::ignored(),
2551                          bool ignoreResult = false);
2552   RValue EmitCoyieldExpr(const CoyieldExpr &E,
2553                          AggValueSlot aggSlot = AggValueSlot::ignored(),
2554                          bool ignoreResult = false);
2555   RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
2556
2557   void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2558   void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2559
2560   void EmitCXXTryStmt(const CXXTryStmt &S);
2561   void EmitSEHTryStmt(const SEHTryStmt &S);
2562   void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
2563   void EnterSEHTryStmt(const SEHTryStmt &S);
2564   void ExitSEHTryStmt(const SEHTryStmt &S);
2565
2566   void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
2567                               const Stmt *OutlinedStmt);
2568
2569   llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2570                                             const SEHExceptStmt &Except);
2571
2572   llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2573                                              const SEHFinallyStmt &Finally);
2574
2575   void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
2576                                 llvm::Value *ParentFP,
2577                                 llvm::Value *EntryEBP);
2578   llvm::Value *EmitSEHExceptionCode();
2579   llvm::Value *EmitSEHExceptionInfo();
2580   llvm::Value *EmitSEHAbnormalTermination();
2581
2582   /// Scan the outlined statement for captures from the parent function. For
2583   /// each capture, mark the capture as escaped and emit a call to
2584   /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
2585   void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
2586                           bool IsFilter);
2587
2588   /// Recovers the address of a local in a parent function. ParentVar is the
2589   /// address of the variable used in the immediate parent function. It can
2590   /// either be an alloca or a call to llvm.localrecover if there are nested
2591   /// outlined functions. ParentFP is the frame pointer of the outermost parent
2592   /// frame.
2593   Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
2594                                     Address ParentVar,
2595                                     llvm::Value *ParentFP);
2596
2597   void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
2598                            ArrayRef<const Attr *> Attrs = None);
2599
2600   /// Returns calculated size of the specified type.
2601   llvm::Value *getTypeSize(QualType Ty);
2602   LValue InitCapturedStruct(const CapturedStmt &S);
2603   llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
2604   llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
2605   Address GenerateCapturedStmtArgument(const CapturedStmt &S);
2606   llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
2607   void GenerateOpenMPCapturedVars(const CapturedStmt &S,
2608                                   SmallVectorImpl<llvm::Value *> &CapturedVars);
2609   void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
2610                           SourceLocation Loc);
2611   /// \brief Perform element by element copying of arrays with type \a
2612   /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
2613   /// generated by \a CopyGen.
2614   ///
2615   /// \param DestAddr Address of the destination array.
2616   /// \param SrcAddr Address of the source array.
2617   /// \param OriginalType Type of destination and source arrays.
2618   /// \param CopyGen Copying procedure that copies value of single array element
2619   /// to another single array element.
2620   void EmitOMPAggregateAssign(
2621       Address DestAddr, Address SrcAddr, QualType OriginalType,
2622       const llvm::function_ref<void(Address, Address)> &CopyGen);
2623   /// \brief Emit proper copying of data from one variable to another.
2624   ///
2625   /// \param OriginalType Original type of the copied variables.
2626   /// \param DestAddr Destination address.
2627   /// \param SrcAddr Source address.
2628   /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
2629   /// type of the base array element).
2630   /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
2631   /// the base array element).
2632   /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
2633   /// DestVD.
2634   void EmitOMPCopy(QualType OriginalType,
2635                    Address DestAddr, Address SrcAddr,
2636                    const VarDecl *DestVD, const VarDecl *SrcVD,
2637                    const Expr *Copy);
2638   /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
2639   /// \a X = \a E \a BO \a E.
2640   ///
2641   /// \param X Value to be updated.
2642   /// \param E Update value.
2643   /// \param BO Binary operation for update operation.
2644   /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
2645   /// expression, false otherwise.
2646   /// \param AO Atomic ordering of the generated atomic instructions.
2647   /// \param CommonGen Code generator for complex expressions that cannot be
2648   /// expressed through atomicrmw instruction.
2649   /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
2650   /// generated, <false, RValue::get(nullptr)> otherwise.
2651   std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
2652       LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2653       llvm::AtomicOrdering AO, SourceLocation Loc,
2654       const llvm::function_ref<RValue(RValue)> &CommonGen);
2655   bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
2656                                  OMPPrivateScope &PrivateScope);
2657   void EmitOMPPrivateClause(const OMPExecutableDirective &D,
2658                             OMPPrivateScope &PrivateScope);
2659   void EmitOMPUseDevicePtrClause(
2660       const OMPClause &C, OMPPrivateScope &PrivateScope,
2661       const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
2662   /// \brief Emit code for copyin clause in \a D directive. The next code is
2663   /// generated at the start of outlined functions for directives:
2664   /// \code
2665   /// threadprivate_var1 = master_threadprivate_var1;
2666   /// operator=(threadprivate_var2, master_threadprivate_var2);
2667   /// ...
2668   /// __kmpc_barrier(&loc, global_tid);
2669   /// \endcode
2670   ///
2671   /// \param D OpenMP directive possibly with 'copyin' clause(s).
2672   /// \returns true if at least one copyin variable is found, false otherwise.
2673   bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
2674   /// \brief Emit initial code for lastprivate variables. If some variable is
2675   /// not also firstprivate, then the default initialization is used. Otherwise
2676   /// initialization of this variable is performed by EmitOMPFirstprivateClause
2677   /// method.
2678   ///
2679   /// \param D Directive that may have 'lastprivate' directives.
2680   /// \param PrivateScope Private scope for capturing lastprivate variables for
2681   /// proper codegen in internal captured statement.
2682   ///
2683   /// \returns true if there is at least one lastprivate variable, false
2684   /// otherwise.
2685   bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
2686                                     OMPPrivateScope &PrivateScope);
2687   /// \brief Emit final copying of lastprivate values to original variables at
2688   /// the end of the worksharing or simd directive.
2689   ///
2690   /// \param D Directive that has at least one 'lastprivate' directives.
2691   /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
2692   /// it is the last iteration of the loop code in associated directive, or to
2693   /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
2694   void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
2695                                      bool NoFinals,
2696                                      llvm::Value *IsLastIterCond = nullptr);
2697   /// Emit initial code for linear clauses.
2698   void EmitOMPLinearClause(const OMPLoopDirective &D,
2699                            CodeGenFunction::OMPPrivateScope &PrivateScope);
2700   /// Emit final code for linear clauses.
2701   /// \param CondGen Optional conditional code for final part of codegen for
2702   /// linear clause.
2703   void EmitOMPLinearClauseFinal(
2704       const OMPLoopDirective &D,
2705       const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2706   /// \brief Emit initial code for reduction variables. Creates reduction copies
2707   /// and initializes them with the values according to OpenMP standard.
2708   ///
2709   /// \param D Directive (possibly) with the 'reduction' clause.
2710   /// \param PrivateScope Private scope for capturing reduction variables for
2711   /// proper codegen in internal captured statement.
2712   ///
2713   void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
2714                                   OMPPrivateScope &PrivateScope);
2715   /// \brief Emit final update of reduction values to original variables at
2716   /// the end of the directive.
2717   ///
2718   /// \param D Directive that has at least one 'reduction' directives.
2719   /// \param ReductionKind The kind of reduction to perform.
2720   void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
2721                                    const OpenMPDirectiveKind ReductionKind);
2722   /// \brief Emit initial code for linear variables. Creates private copies
2723   /// and initializes them with the values according to OpenMP standard.
2724   ///
2725   /// \param D Directive (possibly) with the 'linear' clause.
2726   void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
2727
2728   typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
2729                                         llvm::Value * /*OutlinedFn*/,
2730                                         const OMPTaskDataTy & /*Data*/)>
2731       TaskGenTy;
2732   void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2733                                  const RegionCodeGenTy &BodyGen,
2734                                  const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
2735
2736   void EmitOMPParallelDirective(const OMPParallelDirective &S);
2737   void EmitOMPSimdDirective(const OMPSimdDirective &S);
2738   void EmitOMPForDirective(const OMPForDirective &S);
2739   void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
2740   void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
2741   void EmitOMPSectionDirective(const OMPSectionDirective &S);
2742   void EmitOMPSingleDirective(const OMPSingleDirective &S);
2743   void EmitOMPMasterDirective(const OMPMasterDirective &S);
2744   void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
2745   void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
2746   void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
2747   void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
2748   void EmitOMPTaskDirective(const OMPTaskDirective &S);
2749   void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
2750   void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
2751   void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
2752   void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
2753   void EmitOMPFlushDirective(const OMPFlushDirective &S);
2754   void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
2755   void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
2756   void EmitOMPTargetDirective(const OMPTargetDirective &S);
2757   void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
2758   void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
2759   void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
2760   void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
2761   void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
2762   void
2763   EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
2764   void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
2765   void
2766   EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
2767   void EmitOMPCancelDirective(const OMPCancelDirective &S);
2768   void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
2769   void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
2770   void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
2771   void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
2772   void EmitOMPDistributeParallelForDirective(
2773       const OMPDistributeParallelForDirective &S);
2774   void EmitOMPDistributeParallelForSimdDirective(
2775       const OMPDistributeParallelForSimdDirective &S);
2776   void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
2777   void EmitOMPTargetParallelForSimdDirective(
2778       const OMPTargetParallelForSimdDirective &S);
2779   void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
2780   void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
2781   void
2782   EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
2783   void EmitOMPTeamsDistributeParallelForSimdDirective(
2784       const OMPTeamsDistributeParallelForSimdDirective &S);
2785   void EmitOMPTeamsDistributeParallelForDirective(
2786       const OMPTeamsDistributeParallelForDirective &S);
2787   void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
2788   void EmitOMPTargetTeamsDistributeDirective(
2789       const OMPTargetTeamsDistributeDirective &S);
2790   void EmitOMPTargetTeamsDistributeParallelForDirective(
2791       const OMPTargetTeamsDistributeParallelForDirective &S);
2792   void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2793       const OMPTargetTeamsDistributeParallelForSimdDirective &S);
2794   void EmitOMPTargetTeamsDistributeSimdDirective(
2795       const OMPTargetTeamsDistributeSimdDirective &S);
2796
2797   /// Emit device code for the target directive.
2798   static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
2799                                           StringRef ParentName,
2800                                           const OMPTargetDirective &S);
2801   static void
2802   EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
2803                                       const OMPTargetParallelDirective &S);
2804   static void
2805   EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
2806                                    const OMPTargetTeamsDirective &S);
2807   /// \brief Emit inner loop of the worksharing/simd construct.
2808   ///
2809   /// \param S Directive, for which the inner loop must be emitted.
2810   /// \param RequiresCleanup true, if directive has some associated private
2811   /// variables.
2812   /// \param LoopCond Bollean condition for loop continuation.
2813   /// \param IncExpr Increment expression for loop control variable.
2814   /// \param BodyGen Generator for the inner body of the inner loop.
2815   /// \param PostIncGen Genrator for post-increment code (required for ordered
2816   /// loop directvies).
2817   void EmitOMPInnerLoop(
2818       const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
2819       const Expr *IncExpr,
2820       const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
2821       const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
2822
2823   JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
2824   /// Emit initial code for loop counters of loop-based directives.
2825   void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
2826                                   OMPPrivateScope &LoopScope);
2827
2828   /// Helper for the OpenMP loop directives.
2829   void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
2830
2831   /// \brief Emit code for the worksharing loop-based directive.
2832   /// \return true, if this construct has any lastprivate clause, false -
2833   /// otherwise.
2834   bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB,
2835                               const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2836                               const CodeGenDispatchBoundsTy &CGDispatchBounds);
2837
2838 private:
2839   /// Helpers for blocks
2840   llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
2841
2842   /// Helpers for the OpenMP loop directives.
2843   void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
2844   void EmitOMPSimdFinal(
2845       const OMPLoopDirective &D,
2846       const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2847
2848   void EmitOMPDistributeLoop(const OMPLoopDirective &S,
2849                              const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
2850
2851   /// struct with the values to be passed to the OpenMP loop-related functions
2852   struct OMPLoopArguments {
2853     /// loop lower bound
2854     Address LB = Address::invalid();
2855     /// loop upper bound
2856     Address UB = Address::invalid();
2857     /// loop stride
2858     Address ST = Address::invalid();
2859     /// isLastIteration argument for runtime functions
2860     Address IL = Address::invalid();
2861     /// Chunk value generated by sema
2862     llvm::Value *Chunk = nullptr;
2863     /// EnsureUpperBound
2864     Expr *EUB = nullptr;
2865     /// IncrementExpression
2866     Expr *IncExpr = nullptr;
2867     /// Loop initialization
2868     Expr *Init = nullptr;
2869     /// Loop exit condition
2870     Expr *Cond = nullptr;
2871     /// Update of LB after a whole chunk has been executed
2872     Expr *NextLB = nullptr;
2873     /// Update of UB after a whole chunk has been executed
2874     Expr *NextUB = nullptr;
2875     OMPLoopArguments() = default;
2876     OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
2877                      llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
2878                      Expr *IncExpr = nullptr, Expr *Init = nullptr,
2879                      Expr *Cond = nullptr, Expr *NextLB = nullptr,
2880                      Expr *NextUB = nullptr)
2881         : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
2882           IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
2883           NextUB(NextUB) {}
2884   };
2885   void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
2886                         const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
2887                         const OMPLoopArguments &LoopArgs,
2888                         const CodeGenLoopTy &CodeGenLoop,
2889                         const CodeGenOrderedTy &CodeGenOrdered);
2890   void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
2891                            bool IsMonotonic, const OMPLoopDirective &S,
2892                            OMPPrivateScope &LoopScope, bool Ordered,
2893                            const OMPLoopArguments &LoopArgs,
2894                            const CodeGenDispatchBoundsTy &CGDispatchBounds);
2895   void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
2896                                   const OMPLoopDirective &S,
2897                                   OMPPrivateScope &LoopScope,
2898                                   const OMPLoopArguments &LoopArgs,
2899                                   const CodeGenLoopTy &CodeGenLoopContent);
2900   /// \brief Emit code for sections directive.
2901   void EmitSections(const OMPExecutableDirective &S);
2902
2903 public:
2904
2905   //===--------------------------------------------------------------------===//
2906   //                         LValue Expression Emission
2907   //===--------------------------------------------------------------------===//
2908
2909   /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
2910   RValue GetUndefRValue(QualType Ty);
2911
2912   /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
2913   /// and issue an ErrorUnsupported style diagnostic (using the
2914   /// provided Name).
2915   RValue EmitUnsupportedRValue(const Expr *E,
2916                                const char *Name);
2917
2918   /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
2919   /// an ErrorUnsupported style diagnostic (using the provided Name).
2920   LValue EmitUnsupportedLValue(const Expr *E,
2921                                const char *Name);
2922
2923   /// EmitLValue - Emit code to compute a designator that specifies the location
2924   /// of the expression.
2925   ///
2926   /// This can return one of two things: a simple address or a bitfield
2927   /// reference.  In either case, the LLVM Value* in the LValue structure is
2928   /// guaranteed to be an LLVM pointer type.
2929   ///
2930   /// If this returns a bitfield reference, nothing about the pointee type of
2931   /// the LLVM value is known: For example, it may not be a pointer to an
2932   /// integer.
2933   ///
2934   /// If this returns a normal address, and if the lvalue's C type is fixed
2935   /// size, this method guarantees that the returned pointer type will point to
2936   /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
2937   /// variable length type, this is not possible.
2938   ///
2939   LValue EmitLValue(const Expr *E);
2940
2941   /// \brief Same as EmitLValue but additionally we generate checking code to
2942   /// guard against undefined behavior.  This is only suitable when we know
2943   /// that the address will be used to access the object.
2944   LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
2945
2946   RValue convertTempToRValue(Address addr, QualType type,
2947                              SourceLocation Loc);
2948
2949   void EmitAtomicInit(Expr *E, LValue lvalue);
2950
2951   bool LValueIsSuitableForInlineAtomic(LValue Src);
2952
2953   RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
2954                         AggValueSlot Slot = AggValueSlot::ignored());
2955
2956   RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
2957                         llvm::AtomicOrdering AO, bool IsVolatile = false,
2958                         AggValueSlot slot = AggValueSlot::ignored());
2959
2960   void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
2961
2962   void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
2963                        bool IsVolatile, bool isInit);
2964
2965   std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
2966       LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2967       llvm::AtomicOrdering Success =
2968           llvm::AtomicOrdering::SequentiallyConsistent,
2969       llvm::AtomicOrdering Failure =
2970           llvm::AtomicOrdering::SequentiallyConsistent,
2971       bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
2972
2973   void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
2974                         const llvm::function_ref<RValue(RValue)> &UpdateOp,
2975                         bool IsVolatile);
2976
2977   /// EmitToMemory - Change a scalar value from its value
2978   /// representation to its in-memory representation.
2979   llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
2980
2981   /// EmitFromMemory - Change a scalar value from its memory
2982   /// representation to its value representation.
2983   llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
2984
2985   /// Check if the scalar \p Value is within the valid range for the given
2986   /// type \p Ty.
2987   ///
2988   /// Returns true if a check is needed (even if the range is unknown).
2989   bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
2990                             SourceLocation Loc);
2991
2992   /// EmitLoadOfScalar - Load a scalar value from an address, taking
2993   /// care to appropriately convert from the memory representation to
2994   /// the LLVM value representation.
2995   llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
2996                                 SourceLocation Loc,
2997                                 LValueBaseInfo BaseInfo =
2998                                     LValueBaseInfo(AlignmentSource::Type),
2999                                 llvm::MDNode *TBAAInfo = nullptr,
3000                                 QualType TBAABaseTy = QualType(),
3001                                 uint64_t TBAAOffset = 0,
3002                                 bool isNontemporal = false);
3003
3004   /// EmitLoadOfScalar - Load a scalar value from an address, taking
3005   /// care to appropriately convert from the memory representation to
3006   /// the LLVM value representation.  The l-value must be a simple
3007   /// l-value.
3008   llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
3009
3010   /// EmitStoreOfScalar - Store a scalar value to an address, taking
3011   /// care to appropriately convert from the memory representation to
3012   /// the LLVM value representation.
3013   void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3014                          bool Volatile, QualType Ty,
3015                          LValueBaseInfo BaseInfo =
3016                              LValueBaseInfo(AlignmentSource::Type),
3017                          llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
3018                          QualType TBAABaseTy = QualType(),
3019                          uint64_t TBAAOffset = 0, bool isNontemporal = false);
3020
3021   /// EmitStoreOfScalar - Store a scalar value to an address, taking
3022   /// care to appropriately convert from the memory representation to
3023   /// the LLVM value representation.  The l-value must be a simple
3024   /// l-value.  The isInit flag indicates whether this is an initialization.
3025   /// If so, atomic qualifiers are ignored and the store is always non-atomic.
3026   void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
3027
3028   /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
3029   /// this method emits the address of the lvalue, then loads the result as an
3030   /// rvalue, returning the rvalue.
3031   RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
3032   RValue EmitLoadOfExtVectorElementLValue(LValue V);
3033   RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc);
3034   RValue EmitLoadOfGlobalRegLValue(LValue LV);
3035
3036   /// EmitStoreThroughLValue - Store the specified rvalue into the specified
3037   /// lvalue, where both are guaranteed to the have the same type, and that type
3038   /// is 'Ty'.
3039   void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
3040   void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
3041   void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
3042
3043   /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
3044   /// as EmitStoreThroughLValue.
3045   ///
3046   /// \param Result [out] - If non-null, this will be set to a Value* for the
3047   /// bit-field contents after the store, appropriate for use as the result of
3048   /// an assignment to the bit-field.
3049   void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
3050                                       llvm::Value **Result=nullptr);
3051
3052   /// Emit an l-value for an assignment (simple or compound) of complex type.
3053   LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
3054   LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
3055   LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
3056                                              llvm::Value *&Result);
3057
3058   // Note: only available for agg return types
3059   LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
3060   LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
3061   // Note: only available for agg return types
3062   LValue EmitCallExprLValue(const CallExpr *E);
3063   // Note: only available for agg return types
3064   LValue EmitVAArgExprLValue(const VAArgExpr *E);
3065   LValue EmitDeclRefLValue(const DeclRefExpr *E);
3066   LValue EmitStringLiteralLValue(const StringLiteral *E);
3067   LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
3068   LValue EmitPredefinedLValue(const PredefinedExpr *E);
3069   LValue EmitUnaryOpLValue(const UnaryOperator *E);
3070   LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3071                                 bool Accessed = false);
3072   LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3073                                  bool IsLowerBound = true);
3074   LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
3075   LValue EmitMemberExpr(const MemberExpr *E);
3076   LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
3077   LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
3078   LValue EmitInitListLValue(const InitListExpr *E);
3079   LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
3080   LValue EmitCastLValue(const CastExpr *E);
3081   LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
3082   LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
3083   
3084   Address EmitExtVectorElementLValue(LValue V);
3085
3086   RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
3087
3088   Address EmitArrayToPointerDecay(const Expr *Array,
3089                                   LValueBaseInfo *BaseInfo = nullptr);
3090
3091   class ConstantEmission {
3092     llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
3093     ConstantEmission(llvm::Constant *C, bool isReference)
3094       : ValueAndIsReference(C, isReference) {}
3095   public:
3096     ConstantEmission() {}
3097     static ConstantEmission forReference(llvm::Constant *C) {
3098       return ConstantEmission(C, true);
3099     }
3100     static ConstantEmission forValue(llvm::Constant *C) {
3101       return ConstantEmission(C, false);
3102     }
3103
3104     explicit operator bool() const {
3105       return ValueAndIsReference.getOpaqueValue() != nullptr;
3106     }
3107
3108     bool isReference() const { return ValueAndIsReference.getInt(); }
3109     LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
3110       assert(isReference());
3111       return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
3112                                             refExpr->getType());
3113     }
3114
3115     llvm::Constant *getValue() const {
3116       assert(!isReference());
3117       return ValueAndIsReference.getPointer();
3118     }
3119   };
3120
3121   ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
3122
3123   RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
3124                                 AggValueSlot slot = AggValueSlot::ignored());
3125   LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
3126
3127   llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
3128                               const ObjCIvarDecl *Ivar);
3129   LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
3130   LValue EmitLValueForLambdaField(const FieldDecl *Field);
3131
3132   /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
3133   /// if the Field is a reference, this will return the address of the reference
3134   /// and not the address of the value stored in the reference.
3135   LValue EmitLValueForFieldInitialization(LValue Base,
3136                                           const FieldDecl* Field);
3137
3138   LValue EmitLValueForIvar(QualType ObjectTy,
3139                            llvm::Value* Base, const ObjCIvarDecl *Ivar,
3140                            unsigned CVRQualifiers);
3141
3142   LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
3143   LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
3144   LValue EmitLambdaLValue(const LambdaExpr *E);
3145   LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
3146   LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
3147
3148   LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
3149   LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
3150   LValue EmitStmtExprLValue(const StmtExpr *E);
3151   LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
3152   LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
3153   void   EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
3154
3155   //===--------------------------------------------------------------------===//
3156   //                         Scalar Expression Emission
3157   //===--------------------------------------------------------------------===//
3158
3159   /// EmitCall - Generate a call of the given function, expecting the given
3160   /// result type, and using the given argument list which specifies both the
3161   /// LLVM arguments and the types they were derived from.
3162   RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
3163                   ReturnValueSlot ReturnValue, const CallArgList &Args,
3164                   llvm::Instruction **callOrInvoke = nullptr);
3165
3166   RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
3167                   ReturnValueSlot ReturnValue,
3168                   llvm::Value *Chain = nullptr);
3169   RValue EmitCallExpr(const CallExpr *E,
3170                       ReturnValueSlot ReturnValue = ReturnValueSlot());
3171   RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3172   CGCallee EmitCallee(const Expr *E);
3173
3174   void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
3175
3176   llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3177                                   const Twine &name = "");
3178   llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3179                                   ArrayRef<llvm::Value*> args,
3180                                   const Twine &name = "");
3181   llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3182                                           const Twine &name = "");
3183   llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3184                                           ArrayRef<llvm::Value*> args,
3185                                           const Twine &name = "");
3186
3187   llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
3188                                   ArrayRef<llvm::Value *> Args,
3189                                   const Twine &Name = "");
3190   llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3191                                          ArrayRef<llvm::Value*> args,
3192                                          const Twine &name = "");
3193   llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3194                                          const Twine &name = "");
3195   void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3196                                        ArrayRef<llvm::Value*> args);
3197
3198   CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 
3199                                      NestedNameSpecifier *Qual,
3200                                      llvm::Type *Ty);
3201   
3202   CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
3203                                                CXXDtorType Type, 
3204                                                const CXXRecordDecl *RD);
3205
3206   RValue
3207   EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
3208                               const CGCallee &Callee,
3209                               ReturnValueSlot ReturnValue, llvm::Value *This,
3210                               llvm::Value *ImplicitParam,
3211                               QualType ImplicitParamTy, const CallExpr *E,
3212                               CallArgList *RtlArgs);
3213   RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD,
3214                                const CGCallee &Callee,
3215                                llvm::Value *This, llvm::Value *ImplicitParam,
3216                                QualType ImplicitParamTy, const CallExpr *E,
3217                                StructorType Type);
3218   RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
3219                                ReturnValueSlot ReturnValue);
3220   RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
3221                                                const CXXMethodDecl *MD,
3222                                                ReturnValueSlot ReturnValue,
3223                                                bool HasQualifier,
3224                                                NestedNameSpecifier *Qualifier,
3225                                                bool IsArrow, const Expr *Base);
3226   // Compute the object pointer.
3227   Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
3228                                           llvm::Value *memberPtr,
3229                                           const MemberPointerType *memberPtrType,
3230                                           LValueBaseInfo *BaseInfo = nullptr);
3231   RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
3232                                       ReturnValueSlot ReturnValue);
3233
3234   RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
3235                                        const CXXMethodDecl *MD,
3236                                        ReturnValueSlot ReturnValue);
3237   RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
3238
3239   RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
3240                                 ReturnValueSlot ReturnValue);
3241
3242   RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E,
3243                                        ReturnValueSlot ReturnValue);
3244
3245   RValue EmitBuiltinExpr(const FunctionDecl *FD,
3246                          unsigned BuiltinID, const CallExpr *E,
3247                          ReturnValueSlot ReturnValue);
3248
3249   RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3250
3251   /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
3252   /// is unhandled by the current target.
3253   llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3254
3255   llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
3256                                              const llvm::CmpInst::Predicate Fp,
3257                                              const llvm::CmpInst::Predicate Ip,
3258                                              const llvm::Twine &Name = "");
3259   llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3260
3261   llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
3262                                          unsigned LLVMIntrinsic,
3263                                          unsigned AltLLVMIntrinsic,
3264                                          const char *NameHint,
3265                                          unsigned Modifier,
3266                                          const CallExpr *E,
3267                                          SmallVectorImpl<llvm::Value *> &Ops,
3268                                          Address PtrOp0, Address PtrOp1);
3269   llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
3270                                           unsigned Modifier, llvm::Type *ArgTy,
3271                                           const CallExpr *E);
3272   llvm::Value *EmitNeonCall(llvm::Function *F,
3273                             SmallVectorImpl<llvm::Value*> &O,
3274                             const char *name,
3275                             unsigned shift = 0, bool rightshift = false);
3276   llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
3277   llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
3278                                    bool negateForRightShift);
3279   llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
3280                                  llvm::Type *Ty, bool usgn, const char *name);
3281   llvm::Value *vectorWrapScalar16(llvm::Value *Op);
3282   llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3283
3284   llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
3285   llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3286   llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3287   llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3288   llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3289   llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3290   llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
3291                                           const CallExpr *E);
3292
3293 private:
3294   enum class MSVCIntrin;
3295
3296 public:
3297   llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
3298
3299   llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args);
3300
3301   llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
3302   llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
3303   llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
3304   llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
3305   llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
3306   llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
3307                                 const ObjCMethodDecl *MethodWithObjects);
3308   llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
3309   RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
3310                              ReturnValueSlot Return = ReturnValueSlot());
3311
3312   /// Retrieves the default cleanup kind for an ARC cleanup.
3313   /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
3314   CleanupKind getARCCleanupKind() {
3315     return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
3316              ? NormalAndEHCleanup : NormalCleanup;
3317   }
3318
3319   // ARC primitives.
3320   void EmitARCInitWeak(Address addr, llvm::Value *value);
3321   void EmitARCDestroyWeak(Address addr);
3322   llvm::Value *EmitARCLoadWeak(Address addr);
3323   llvm::Value *EmitARCLoadWeakRetained(Address addr);
3324   llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
3325   void EmitARCCopyWeak(Address dst, Address src);
3326   void EmitARCMoveWeak(Address dst, Address src);
3327   llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
3328   llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
3329   llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
3330                                   bool resultIgnored);
3331   llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
3332                                       bool resultIgnored);
3333   llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
3334   llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
3335   llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
3336   void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
3337   void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
3338   llvm::Value *EmitARCAutorelease(llvm::Value *value);
3339   llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
3340   llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
3341   llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
3342   llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
3343
3344   std::pair<LValue,llvm::Value*>
3345   EmitARCStoreAutoreleasing(const BinaryOperator *e);
3346   std::pair<LValue,llvm::Value*>
3347   EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
3348   std::pair<LValue,llvm::Value*>
3349   EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
3350
3351   llvm::Value *EmitObjCThrowOperand(const Expr *expr);
3352   llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
3353   llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
3354
3355   llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
3356   llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
3357                                             bool allowUnsafeClaim);
3358   llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
3359   llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
3360   llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
3361
3362   void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
3363
3364   static Destroyer destroyARCStrongImprecise;
3365   static Destroyer destroyARCStrongPrecise;
3366   static Destroyer destroyARCWeak;
3367   static Destroyer emitARCIntrinsicUse;
3368
3369   void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 
3370   llvm::Value *EmitObjCAutoreleasePoolPush();
3371   llvm::Value *EmitObjCMRRAutoreleasePoolPush();
3372   void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
3373   void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 
3374
3375   /// \brief Emits a reference binding to the passed in expression.
3376   RValue EmitReferenceBindingToExpr(const Expr *E);
3377
3378   //===--------------------------------------------------------------------===//
3379   //                           Expression Emission
3380   //===--------------------------------------------------------------------===//
3381
3382   // Expressions are broken into three classes: scalar, complex, aggregate.
3383
3384   /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
3385   /// scalar type, returning the result.
3386   llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
3387
3388   /// Emit a conversion from the specified type to the specified destination
3389   /// type, both of which are LLVM scalar types.
3390   llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
3391                                     QualType DstTy, SourceLocation Loc);
3392
3393   /// Emit a conversion from the specified complex type to the specified
3394   /// destination type, where the destination type is an LLVM scalar type.
3395   llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
3396                                              QualType DstTy,
3397                                              SourceLocation Loc);
3398
3399   /// EmitAggExpr - Emit the computation of the specified expression
3400   /// of aggregate type.  The result is computed into the given slot,
3401   /// which may be null to indicate that the value is not needed.
3402   void EmitAggExpr(const Expr *E, AggValueSlot AS);
3403
3404   /// EmitAggExprToLValue - Emit the computation of the specified expression of
3405   /// aggregate type into a temporary LValue.
3406   LValue EmitAggExprToLValue(const Expr *E);
3407
3408   /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3409   /// make sure it survives garbage collection until this point.
3410   void EmitExtendGCLifetime(llvm::Value *object);
3411
3412   /// EmitComplexExpr - Emit the computation of the specified expression of
3413   /// complex type, returning the result.
3414   ComplexPairTy EmitComplexExpr(const Expr *E,
3415                                 bool IgnoreReal = false,
3416                                 bool IgnoreImag = false);
3417
3418   /// EmitComplexExprIntoLValue - Emit the given expression of complex
3419   /// type and place its result into the specified l-value.
3420   void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
3421
3422   /// EmitStoreOfComplex - Store a complex number into the specified l-value.
3423   void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
3424
3425   /// EmitLoadOfComplex - Load a complex number from the specified l-value.
3426   ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
3427
3428   Address emitAddrOfRealComponent(Address complex, QualType complexType);
3429   Address emitAddrOfImagComponent(Address complex, QualType complexType);
3430
3431   /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
3432   /// global variable that has already been created for it.  If the initializer
3433   /// has a different type than GV does, this may free GV and return a different
3434   /// one.  Otherwise it just returns GV.
3435   llvm::GlobalVariable *
3436   AddInitializerToStaticVarDecl(const VarDecl &D,
3437                                 llvm::GlobalVariable *GV);
3438
3439
3440   /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
3441   /// variable with global storage.
3442   void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
3443                                 bool PerformInit);
3444
3445   llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
3446                                    llvm::Constant *Addr);
3447
3448   /// Call atexit() with a function that passes the given argument to
3449   /// the given function.
3450   void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
3451                                     llvm::Constant *addr);
3452
3453   /// Emit code in this function to perform a guarded variable
3454   /// initialization.  Guarded initializations are used when it's not
3455   /// possible to prove that an initialization will be done exactly
3456   /// once, e.g. with a static local variable or a static data member
3457   /// of a class template.
3458   void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
3459                           bool PerformInit);
3460
3461   /// GenerateCXXGlobalInitFunc - Generates code for initializing global
3462   /// variables.
3463   void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
3464                                  ArrayRef<llvm::Function *> CXXThreadLocals,
3465                                  Address Guard = Address::invalid());
3466
3467   /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
3468   /// variables.
3469   void GenerateCXXGlobalDtorsFunc(
3470       llvm::Function *Fn,
3471       const std::vector<std::pair<llvm::WeakTrackingVH, llvm::Constant *>>
3472           &DtorsAndObjects);
3473
3474   void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
3475                                         const VarDecl *D,
3476                                         llvm::GlobalVariable *Addr,
3477                                         bool PerformInit);
3478
3479   void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
3480   
3481   void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
3482
3483   void enterFullExpression(const ExprWithCleanups *E) {
3484     if (E->getNumObjects() == 0) return;
3485     enterNonTrivialFullExpression(E);
3486   }
3487   void enterNonTrivialFullExpression(const ExprWithCleanups *E);
3488
3489   void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
3490
3491   void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
3492
3493   RValue EmitAtomicExpr(AtomicExpr *E);
3494
3495   //===--------------------------------------------------------------------===//
3496   //                         Annotations Emission
3497   //===--------------------------------------------------------------------===//
3498
3499   /// Emit an annotation call (intrinsic or builtin).
3500   llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
3501                                   llvm::Value *AnnotatedVal,
3502                                   StringRef AnnotationStr,
3503                                   SourceLocation Location);
3504
3505   /// Emit local annotations for the local variable V, declared by D.
3506   void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
3507
3508   /// Emit field annotations for the given field & value. Returns the
3509   /// annotation result.
3510   Address EmitFieldAnnotations(const FieldDecl *D, Address V);
3511
3512   //===--------------------------------------------------------------------===//
3513   //                             Internal Helpers
3514   //===--------------------------------------------------------------------===//
3515
3516   /// ContainsLabel - Return true if the statement contains a label in it.  If
3517   /// this statement is not executed normally, it not containing a label means
3518   /// that we can just remove the code.
3519   static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
3520
3521   /// containsBreak - Return true if the statement contains a break out of it.
3522   /// If the statement (recursively) contains a switch or loop with a break
3523   /// inside of it, this is fine.
3524   static bool containsBreak(const Stmt *S);
3525
3526   /// Determine if the given statement might introduce a declaration into the
3527   /// current scope, by being a (possibly-labelled) DeclStmt.
3528   static bool mightAddDeclToScope(const Stmt *S);
3529   
3530   /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3531   /// to a constant, or if it does but contains a label, return false.  If it
3532   /// constant folds return true and set the boolean result in Result.
3533   bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
3534                                     bool AllowLabels = false);
3535
3536   /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3537   /// to a constant, or if it does but contains a label, return false.  If it
3538   /// constant folds return true and set the folded value.
3539   bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
3540                                     bool AllowLabels = false);
3541
3542   /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
3543   /// if statement) to the specified blocks.  Based on the condition, this might
3544   /// try to simplify the codegen of the conditional based on the branch.
3545   /// TrueCount should be the number of times we expect the condition to
3546   /// evaluate to true based on PGO data.
3547   void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
3548                             llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
3549
3550   /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is
3551   /// nonnull, if \p LHS is marked _Nonnull.
3552   void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc);
3553
3554   /// \brief Emit a description of a type in a format suitable for passing to
3555   /// a runtime sanitizer handler.
3556   llvm::Constant *EmitCheckTypeDescriptor(QualType T);
3557
3558   /// \brief Convert a value into a format suitable for passing to a runtime
3559   /// sanitizer handler.
3560   llvm::Value *EmitCheckValue(llvm::Value *V);
3561
3562   /// \brief Emit a description of a source location in a format suitable for
3563   /// passing to a runtime sanitizer handler.
3564   llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
3565
3566   /// \brief Create a basic block that will call a handler function in a
3567   /// sanitizer runtime with the provided arguments, and create a conditional
3568   /// branch to it.
3569   void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3570                  SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
3571                  ArrayRef<llvm::Value *> DynamicArgs);
3572
3573   /// \brief Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
3574   /// if Cond if false.
3575   void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
3576                             llvm::ConstantInt *TypeId, llvm::Value *Ptr,
3577                             ArrayRef<llvm::Constant *> StaticArgs);
3578
3579   /// \brief Create a basic block that will call the trap intrinsic, and emit a
3580   /// conditional branch to it, for the -ftrapv checks.
3581   void EmitTrapCheck(llvm::Value *Checked);
3582
3583   /// \brief Emit a call to trap or debugtrap and attach function attribute
3584   /// "trap-func-name" if specified.
3585   llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
3586
3587   /// \brief Emit a stub for the cross-DSO CFI check function.
3588   void EmitCfiCheckStub();
3589
3590   /// \brief Emit a cross-DSO CFI failure handling function.
3591   void EmitCfiCheckFail();
3592
3593   /// \brief Create a check for a function parameter that may potentially be
3594   /// declared as non-null.
3595   void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
3596                            AbstractCallee AC, unsigned ParmNum);
3597
3598   /// EmitCallArg - Emit a single call argument.
3599   void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
3600
3601   /// EmitDelegateCallArg - We are performing a delegate call; that
3602   /// is, the current function is delegating to another one.  Produce
3603   /// a r-value suitable for passing the given parameter.
3604   void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
3605                            SourceLocation loc);
3606
3607   /// SetFPAccuracy - Set the minimum required accuracy of the given floating
3608   /// point operation, expressed as the maximum relative error in ulp.
3609   void SetFPAccuracy(llvm::Value *Val, float Accuracy);
3610
3611 private:
3612   llvm::MDNode *getRangeForLoadFromType(QualType Ty);
3613   void EmitReturnOfRValue(RValue RV, QualType Ty);
3614
3615   void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
3616
3617   llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
3618   DeferredReplacements;
3619
3620   /// Set the address of a local variable.
3621   void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
3622     assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
3623     LocalDeclMap.insert({VD, Addr});
3624   }
3625
3626   /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
3627   /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
3628   ///
3629   /// \param AI - The first function argument of the expansion.
3630   void ExpandTypeFromArgs(QualType Ty, LValue Dst,
3631                           SmallVectorImpl<llvm::Value *>::iterator &AI);
3632
3633   /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
3634   /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
3635   /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
3636   void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
3637                         SmallVectorImpl<llvm::Value *> &IRCallArgs,
3638                         unsigned &IRCallArgPos);
3639
3640   llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
3641                             const Expr *InputExpr, std::string &ConstraintStr);
3642
3643   llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
3644                                   LValue InputValue, QualType InputType,
3645                                   std::string &ConstraintStr,
3646                                   SourceLocation Loc);
3647
3648   /// \brief Attempts to statically evaluate the object size of E. If that
3649   /// fails, emits code to figure the size of E out for us. This is
3650   /// pass_object_size aware.
3651   ///
3652   /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
3653   llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
3654                                                llvm::IntegerType *ResType,
3655                                                llvm::Value *EmittedE);
3656
3657   /// \brief Emits the size of E, as required by __builtin_object_size. This
3658   /// function is aware of pass_object_size parameters, and will act accordingly
3659   /// if E is a parameter with the pass_object_size attribute.
3660   llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
3661                                      llvm::IntegerType *ResType,
3662                                      llvm::Value *EmittedE);
3663
3664 public:
3665 #ifndef NDEBUG
3666   // Determine whether the given argument is an Objective-C method
3667   // that may have type parameters in its signature.
3668   static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
3669     const DeclContext *dc = method->getDeclContext();
3670     if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
3671       return classDecl->getTypeParamListAsWritten();
3672     }
3673
3674     if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
3675       return catDecl->getTypeParamList();
3676     }
3677
3678     return false;
3679   }
3680
3681   template<typename T>
3682   static bool isObjCMethodWithTypeParams(const T *) { return false; }
3683 #endif
3684
3685   enum class EvaluationOrder {
3686     ///! No language constraints on evaluation order.
3687     Default,
3688     ///! Language semantics require left-to-right evaluation.
3689     ForceLeftToRight,
3690     ///! Language semantics require right-to-left evaluation.
3691     ForceRightToLeft
3692   };
3693
3694   /// EmitCallArgs - Emit call arguments for a function.
3695   template <typename T>
3696   void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
3697                     llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3698                     AbstractCallee AC = AbstractCallee(),
3699                     unsigned ParamsToSkip = 0,
3700                     EvaluationOrder Order = EvaluationOrder::Default) {
3701     SmallVector<QualType, 16> ArgTypes;
3702     CallExpr::const_arg_iterator Arg = ArgRange.begin();
3703
3704     assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
3705            "Can't skip parameters if type info is not provided");
3706     if (CallArgTypeInfo) {
3707 #ifndef NDEBUG
3708       bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
3709 #endif
3710
3711       // First, use the argument types that the type info knows about
3712       for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
3713                 E = CallArgTypeInfo->param_type_end();
3714            I != E; ++I, ++Arg) {
3715         assert(Arg != ArgRange.end() && "Running over edge of argument list!");
3716         assert((isGenericMethod ||
3717                 ((*I)->isVariablyModifiedType() ||
3718                  (*I).getNonReferenceType()->isObjCRetainableType() ||
3719                  getContext()
3720                          .getCanonicalType((*I).getNonReferenceType())
3721                          .getTypePtr() ==
3722                      getContext()
3723                          .getCanonicalType((*Arg)->getType())
3724                          .getTypePtr())) &&
3725                "type mismatch in call argument!");
3726         ArgTypes.push_back(*I);
3727       }
3728     }
3729
3730     // Either we've emitted all the call args, or we have a call to variadic
3731     // function.
3732     assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
3733             CallArgTypeInfo->isVariadic()) &&
3734            "Extra arguments in non-variadic function!");
3735
3736     // If we still have any arguments, emit them using the type of the argument.
3737     for (auto *A : llvm::make_range(Arg, ArgRange.end()))
3738       ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType());
3739
3740     EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order);
3741   }
3742
3743   void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
3744                     llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3745                     AbstractCallee AC = AbstractCallee(),
3746                     unsigned ParamsToSkip = 0,
3747                     EvaluationOrder Order = EvaluationOrder::Default);
3748
3749   /// EmitPointerWithAlignment - Given an expression with a pointer type,
3750   /// emit the value and compute our best estimate of the alignment of the
3751   /// pointee.
3752   ///
3753   /// \param BaseInfo - If non-null, this will be initialized with
3754   /// information about the source of the alignment and the may-alias
3755   /// attribute.  Note that this function will conservatively fall back on
3756   /// the type when it doesn't recognize the expression and may-alias will
3757   /// be set to false.
3758   ///
3759   /// One reasonable way to use this information is when there's a language
3760   /// guarantee that the pointer must be aligned to some stricter value, and
3761   /// we're simply trying to ensure that sufficiently obvious uses of under-
3762   /// aligned objects don't get miscompiled; for example, a placement new
3763   /// into the address of a local variable.  In such a case, it's quite
3764   /// reasonable to just ignore the returned alignment when it isn't from an
3765   /// explicit source.
3766   Address EmitPointerWithAlignment(const Expr *Addr,
3767                                    LValueBaseInfo *BaseInfo = nullptr);
3768
3769   void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
3770
3771 private:
3772   QualType getVarArgType(const Expr *Arg);
3773
3774   const TargetCodeGenInfo &getTargetHooks() const {
3775     return CGM.getTargetCodeGenInfo();
3776   }
3777
3778   void EmitDeclMetadata();
3779
3780   BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
3781                                   const AutoVarEmission &emission);
3782
3783   void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
3784
3785   llvm::Value *GetValueForARMHint(unsigned BuiltinID);
3786 };
3787
3788 /// Helper class with most of the code for saving a value for a
3789 /// conditional expression cleanup.
3790 struct DominatingLLVMValue {
3791   typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
3792
3793   /// Answer whether the given value needs extra work to be saved.
3794   static bool needsSaving(llvm::Value *value) {
3795     // If it's not an instruction, we don't need to save.
3796     if (!isa<llvm::Instruction>(value)) return false;
3797
3798     // If it's an instruction in the entry block, we don't need to save.
3799     llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
3800     return (block != &block->getParent()->getEntryBlock());
3801   }
3802
3803   /// Try to save the given value.
3804   static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
3805     if (!needsSaving(value)) return saved_type(value, false);
3806
3807     // Otherwise, we need an alloca.
3808     auto align = CharUnits::fromQuantity(
3809               CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
3810     Address alloca =
3811       CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
3812     CGF.Builder.CreateStore(value, alloca);
3813
3814     return saved_type(alloca.getPointer(), true);
3815   }
3816
3817   static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
3818     // If the value says it wasn't saved, trust that it's still dominating.
3819     if (!value.getInt()) return value.getPointer();
3820
3821     // Otherwise, it should be an alloca instruction, as set up in save().
3822     auto alloca = cast<llvm::AllocaInst>(value.getPointer());
3823     return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
3824   }
3825 };
3826
3827 /// A partial specialization of DominatingValue for llvm::Values that
3828 /// might be llvm::Instructions.
3829 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
3830   typedef T *type;
3831   static type restore(CodeGenFunction &CGF, saved_type value) {
3832     return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
3833   }
3834 };
3835
3836 /// A specialization of DominatingValue for Address.
3837 template <> struct DominatingValue<Address> {
3838   typedef Address type;
3839
3840   struct saved_type {
3841     DominatingLLVMValue::saved_type SavedValue;
3842     CharUnits Alignment;
3843   };
3844
3845   static bool needsSaving(type value) {
3846     return DominatingLLVMValue::needsSaving(value.getPointer());
3847   }
3848   static saved_type save(CodeGenFunction &CGF, type value) {
3849     return { DominatingLLVMValue::save(CGF, value.getPointer()),
3850              value.getAlignment() };
3851   }
3852   static type restore(CodeGenFunction &CGF, saved_type value) {
3853     return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
3854                    value.Alignment);
3855   }
3856 };
3857
3858 /// A specialization of DominatingValue for RValue.
3859 template <> struct DominatingValue<RValue> {
3860   typedef RValue type;
3861   class saved_type {
3862     enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
3863                 AggregateAddress, ComplexAddress };
3864
3865     llvm::Value *Value;
3866     unsigned K : 3;
3867     unsigned Align : 29;
3868     saved_type(llvm::Value *v, Kind k, unsigned a = 0)
3869       : Value(v), K(k), Align(a) {}
3870
3871   public:
3872     static bool needsSaving(RValue value);
3873     static saved_type save(CodeGenFunction &CGF, RValue value);
3874     RValue restore(CodeGenFunction &CGF);
3875
3876     // implementations in CGCleanup.cpp
3877   };
3878
3879   static bool needsSaving(type value) {
3880     return saved_type::needsSaving(value);
3881   }
3882   static saved_type save(CodeGenFunction &CGF, type value) {
3883     return saved_type::save(CGF, value);
3884   }
3885   static type restore(CodeGenFunction &CGF, saved_type value) {
3886     return value.restore(CGF);
3887   }
3888 };
3889
3890 }  // end namespace CodeGen
3891 }  // end namespace clang
3892
3893 #endif