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