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