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