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