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