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