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