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