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