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