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