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