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