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