clang  16.0.0git
CodeGenFunction.h
Go to the documentation of this file.
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"
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"
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?
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 
140 #define SANITIZER_CHECK(Enum, Name, Version) Enum,
142 #undef SANITIZER_CHECK
143 };
144 
145 /// Helper class with most of the code for saving a value for a
146 /// conditional expression cleanup.
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 {
179  llvm::Type *ElementType;
181  };
182 
183  static bool needsSaving(type value) {
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  llvm::Type *ElementType;
205  unsigned K : 3;
206  unsigned Align : 29;
207  saved_type(llvm::Value *v, llvm::Type *e, Kind k, unsigned a = 0)
208  : Value(v), ElementType(e), K(k), Align(a) {}
209 
210  public:
211  static bool needsSaving(RValue value);
212  static saved_type save(CodeGenFunction &CGF, RValue value);
214 
215  // implementations in CGCleanup.cpp
216  };
217 
218  static bool needsSaving(type value) {
219  return saved_type::needsSaving(value);
220  }
221  static saved_type save(CodeGenFunction &CGF, type value) {
222  return saved_type::save(CGF, value);
223  }
224  static type restore(CodeGenFunction &CGF, saved_type value) {
225  return value.restore(CGF);
226  }
227 };
228 
229 /// CodeGenFunction - This class organizes the per-function state that is used
230 /// while generating LLVM code.
232  CodeGenFunction(const CodeGenFunction &) = delete;
233  void operator=(const CodeGenFunction &) = delete;
234 
235  friend class CGCXXABI;
236 public:
237  /// A jump destination is an abstract label, branching to which may
238  /// require a jump out through normal cleanups.
239  struct JumpDest {
240  JumpDest() : Block(nullptr), Index(0) {}
241  JumpDest(llvm::BasicBlock *Block, EHScopeStack::stable_iterator Depth,
242  unsigned Index)
243  : Block(Block), ScopeDepth(Depth), Index(Index) {}
244 
245  bool isValid() const { return Block != nullptr; }
246  llvm::BasicBlock *getBlock() const { return Block; }
247  EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
248  unsigned getDestIndex() const { return Index; }
249 
250  // This should be used cautiously.
252  ScopeDepth = depth;
253  }
254 
255  private:
256  llvm::BasicBlock *Block;
258  unsigned Index;
259  };
260 
261  CodeGenModule &CGM; // Per-module state.
263 
264  // For EH/SEH outlined funclets, this field points to parent's CGF
266 
267  typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
270 
271  // Stores variables for which we can't generate correct lifetime markers
272  // because of jumps.
274 
275  /// List of recently emitted OMPCanonicalLoops.
276  ///
277  /// Since OMPCanonicalLoops are nested inside other statements (in particular
278  /// CapturedStmt generated by OMPExecutableDirective and non-perfectly nested
279  /// loops), we cannot directly call OMPEmitOMPCanonicalLoop and receive its
280  /// llvm::CanonicalLoopInfo. Instead, we call EmitStmt and any
281  /// OMPEmitOMPCanonicalLoop called by it will add its CanonicalLoopInfo to
282  /// this stack when done. Entering a new loop requires clearing this list; it
283  /// either means we start parsing a new loop nest (in which case the previous
284  /// loop nest goes out of scope) or a second loop in the same level in which
285  /// case it would be ambiguous into which of the two (or more) loops the loop
286  /// nest would extend.
288 
289  /// Number of nested loop to be consumed by the last surrounding
290  /// loop-associated directive.
292 
293  // CodeGen lambda for loops and support for ordered clause
294  typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
295  JumpDest)>
297  typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
298  const unsigned, const bool)>
300 
301  // Codegen lambda for loop bounds in worksharing loop constructs
302  typedef llvm::function_ref<std::pair<LValue, LValue>(
305 
306  // Codegen lambda for loop bounds in dispatch-based loop implementation
307  typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
309  Address UB)>
311 
312  /// CGBuilder insert helper. This function is called after an
313  /// instruction is created using Builder.
314  void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
315  llvm::BasicBlock *BB,
316  llvm::BasicBlock::iterator InsertPt) const;
317 
318  /// CurFuncDecl - Holds the Decl for the current outermost
319  /// non-closure context.
321  /// CurCodeDecl - This is the inner-most code context, which includes blocks.
325  llvm::Function *CurFn = nullptr;
326 
327  /// Save Parameter Decl for coroutine.
329 
330  // Holds coroutine data if the current function is a coroutine. We use a
331  // wrapper to manage its lifetime, so that we don't have to define CGCoroData
332  // in this header.
333  struct CGCoroInfo {
334  std::unique_ptr<CGCoroData> Data;
335  CGCoroInfo();
336  ~CGCoroInfo();
337  };
339 
340  bool isCoroutine() const {
341  return CurCoro.Data != nullptr;
342  }
343 
344  /// CurGD - The GlobalDecl for the current function being compiled.
346 
347  /// PrologueCleanupDepth - The cleanup depth enclosing all the
348  /// cleanups associated with the parameters.
350 
351  /// ReturnBlock - Unified return block.
353 
354  /// ReturnValue - The temporary alloca to hold the return
355  /// value. This is invalid iff the function has no return value.
357 
358  /// ReturnValuePointer - The temporary alloca to hold a pointer to sret.
359  /// This is invalid if sret is not in use.
361 
362  /// If a return statement is being visited, this holds the return statment's
363  /// result expression.
364  const Expr *RetExpr = nullptr;
365 
366  /// Return true if a label was seen in the current scope.
368  if (CurLexicalScope)
369  return CurLexicalScope->hasLabels();
370  return !LabelMap.empty();
371  }
372 
373  /// AllocaInsertPoint - This is an instruction in the entry block before which
374  /// we prefer to insert allocas.
375  llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
376 
377 private:
378  /// PostAllocaInsertPt - This is a place in the prologue where code can be
379  /// inserted that will be dominated by all the static allocas. This helps
380  /// achieve two things:
381  /// 1. Contiguity of all static allocas (within the prologue) is maintained.
382  /// 2. All other prologue code (which are dominated by static allocas) do
383  /// appear in the source order immediately after all static allocas.
384  ///
385  /// PostAllocaInsertPt will be lazily created when it is *really* required.
386  llvm::AssertingVH<llvm::Instruction> PostAllocaInsertPt = nullptr;
387 
388 public:
389  /// Return PostAllocaInsertPt. If it is not yet created, then insert it
390  /// immediately after AllocaInsertPt.
391  llvm::Instruction *getPostAllocaInsertPoint() {
392  if (!PostAllocaInsertPt) {
393  assert(AllocaInsertPt &&
394  "Expected static alloca insertion point at function prologue");
395  assert(AllocaInsertPt->getParent()->isEntryBlock() &&
396  "EBB should be entry block of the current code gen function");
397  PostAllocaInsertPt = AllocaInsertPt->clone();
398  PostAllocaInsertPt->setName("postallocapt");
399  PostAllocaInsertPt->insertAfter(AllocaInsertPt);
400  }
401 
402  return PostAllocaInsertPt;
403  }
404 
405  /// API for captured statement code generation.
407  public:
409  : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
410  explicit CGCapturedStmtInfo(const CapturedStmt &S,
412  : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
413 
415  S.getCapturedRecordDecl()->field_begin();
416  for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
417  E = S.capture_end();
418  I != E; ++I, ++Field) {
419  if (I->capturesThis())
420  CXXThisFieldDecl = *Field;
421  else if (I->capturesVariable())
422  CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
423  else if (I->capturesVariableByCopy())
424  CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
425  }
426  }
427 
428  virtual ~CGCapturedStmtInfo();
429 
430  CapturedRegionKind getKind() const { return Kind; }
431 
432  virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
433  // Retrieve the value of the context parameter.
434  virtual llvm::Value *getContextValue() const { return ThisValue; }
435 
436  /// Lookup the captured field decl for a variable.
437  virtual const FieldDecl *lookup(const VarDecl *VD) const {
438  return CaptureFields.lookup(VD->getCanonicalDecl());
439  }
440 
441  bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
442  virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
443 
444  static bool classof(const CGCapturedStmtInfo *) {
445  return true;
446  }
447 
448  /// Emit the captured statement body.
449  virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
451  CGF.EmitStmt(S);
452  }
453 
454  /// Get the name of the capture helper.
455  virtual StringRef getHelperName() const { return "__captured_stmt"; }
456 
457  /// Get the CaptureFields
458  llvm::SmallDenseMap<const VarDecl *, FieldDecl *> getCaptureFields() {
459  return CaptureFields;
460  }
461 
462  private:
463  /// The kind of captured statement being generated.
464  CapturedRegionKind Kind;
465 
466  /// Keep the map between VarDecl and FieldDecl.
467  llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
468 
469  /// The base address of the captured record, passed in as the first
470  /// argument of the parallel region function.
471  llvm::Value *ThisValue;
472 
473  /// Captured 'this' type.
474  FieldDecl *CXXThisFieldDecl;
475  };
477 
478  /// RAII for correct setting/restoring of CapturedStmtInfo.
480  private:
481  CodeGenFunction &CGF;
482  CGCapturedStmtInfo *PrevCapturedStmtInfo;
483  public:
485  CGCapturedStmtInfo *NewCapturedStmtInfo)
486  : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
487  CGF.CapturedStmtInfo = NewCapturedStmtInfo;
488  }
489  ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
490  };
491 
492  /// An abstract representation of regular/ObjC call/message targets.
494  /// The function declaration of the callee.
495  const Decl *CalleeDecl;
496 
497  public:
498  AbstractCallee() : CalleeDecl(nullptr) {}
499  AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
500  AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
501  bool hasFunctionDecl() const {
502  return isa_and_nonnull<FunctionDecl>(CalleeDecl);
503  }
504  const Decl *getDecl() const { return CalleeDecl; }
505  unsigned getNumParams() const {
506  if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
507  return FD->getNumParams();
508  return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
509  }
510  const ParmVarDecl *getParamDecl(unsigned I) const {
511  if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
512  return FD->getParamDecl(I);
513  return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
514  }
515  };
516 
517  /// Sanitizers enabled for this function.
519 
520  /// True if CodeGen currently emits code implementing sanitizer checks.
521  bool IsSanitizerScope = false;
522 
523  /// RAII object to set/unset CodeGenFunction::IsSanitizerScope.
525  CodeGenFunction *CGF;
526  public:
528  ~SanitizerScope();
529  };
530 
531  /// In C++, whether we are code generating a thunk. This controls whether we
532  /// should emit cleanups.
533  bool CurFuncIsThunk = false;
534 
535  /// In ARC, whether we should autorelease the return value.
536  bool AutoreleaseResult = false;
537 
538  /// Whether we processed a Microsoft-style asm block during CodeGen. These can
539  /// potentially set the return value.
540  bool SawAsmBlock = false;
541 
542  const NamedDecl *CurSEHParent = nullptr;
543 
544  /// True if the current function is an outlined SEH helper. This can be a
545  /// finally block or filter expression.
546  bool IsOutlinedSEHHelper = false;
547 
548  /// True if CodeGen currently emits code inside presereved access index
549  /// region.
550  bool IsInPreservedAIRegion = false;
551 
552  /// True if the current statement has nomerge attribute.
554 
555  /// True if the current statement has noinline attribute.
557 
558  /// True if the current statement has always_inline attribute.
560 
561  // The CallExpr within the current statement that the musttail attribute
562  // applies to. nullptr if there is no 'musttail' on the current statement.
563  const CallExpr *MustTailCall = nullptr;
564 
565  /// Returns true if a function must make progress, which means the
566  /// mustprogress attribute can be added.
568  if (CGM.getCodeGenOpts().getFiniteLoops() ==
569  CodeGenOptions::FiniteLoopsKind::Never)
570  return false;
571 
572  // C++11 and later guarantees that a thread eventually will do one of the
573  // following (6.9.2.3.1 in C++11):
574  // - terminate,
575  // - make a call to a library I/O function,
576  // - perform an access through a volatile glvalue, or
577  // - perform a synchronization operation or an atomic operation.
578  //
579  // Hence each function is 'mustprogress' in C++11 or later.
580  return getLangOpts().CPlusPlus11;
581  }
582 
583  /// Returns true if a loop must make progress, which means the mustprogress
584  /// attribute can be added. \p HasConstantCond indicates whether the branch
585  /// condition is a known constant.
586  bool checkIfLoopMustProgress(bool HasConstantCond) {
587  if (CGM.getCodeGenOpts().getFiniteLoops() ==
588  CodeGenOptions::FiniteLoopsKind::Always)
589  return true;
590  if (CGM.getCodeGenOpts().getFiniteLoops() ==
591  CodeGenOptions::FiniteLoopsKind::Never)
592  return false;
593 
594  // If the containing function must make progress, loops also must make
595  // progress (as in C++11 and later).
597  return true;
598 
599  // Now apply rules for plain C (see 6.8.5.6 in C11).
600  // Loops with constant conditions do not have to make progress in any C
601  // version.
602  if (HasConstantCond)
603  return false;
604 
605  // Loops with non-constant conditions must make progress in C11 and later.
606  return getLangOpts().C11;
607  }
608 
609  const CodeGen::CGBlockInfo *BlockInfo = nullptr;
610  llvm::Value *BlockPointer = nullptr;
611 
612  llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
614 
615  /// A mapping from NRVO variables to the flags used to indicate
616  /// when the NRVO has been applied to this variable.
617  llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
618 
622 
623  llvm::Instruction *CurrentFuncletPad = nullptr;
624 
625  class CallLifetimeEnd final : public EHScopeStack::Cleanup {
626  bool isRedundantBeforeReturn() override { return true; }
627 
628  llvm::Value *Addr;
629  llvm::Value *Size;
630 
631  public:
632  CallLifetimeEnd(Address addr, llvm::Value *size)
633  : Addr(addr.getPointer()), Size(size) {}
634 
635  void Emit(CodeGenFunction &CGF, Flags flags) override {
636  CGF.EmitLifetimeEnd(Size, Addr);
637  }
638  };
639 
640  /// Header for data within LifetimeExtendedCleanupStack.
642  /// The size of the following cleanup object.
643  unsigned Size;
644  /// The kind of cleanup to push: a value from the CleanupKind enumeration.
645  unsigned Kind : 31;
646  /// Whether this is a conditional cleanup.
647  unsigned IsConditional : 1;
648 
649  size_t getSize() const { return Size; }
650  CleanupKind getKind() const { return (CleanupKind)Kind; }
651  bool isConditional() const { return IsConditional; }
652  };
653 
654  /// i32s containing the indexes of the cleanup destinations.
656 
657  unsigned NextCleanupDestIndex = 1;
658 
659  /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
660  llvm::BasicBlock *EHResumeBlock = nullptr;
661 
662  /// The exception slot. All landing pads write the current exception pointer
663  /// into this alloca.
664  llvm::Value *ExceptionSlot = nullptr;
665 
666  /// The selector slot. Under the MandatoryCleanup model, all landing pads
667  /// write the current selector value into this alloca.
668  llvm::AllocaInst *EHSelectorSlot = nullptr;
669 
670  /// A stack of exception code slots. Entering an __except block pushes a slot
671  /// on the stack and leaving pops one. The __exception_code() intrinsic loads
672  /// a value from the top of the stack.
674 
675  /// Value returned by __exception_info intrinsic.
676  llvm::Value *SEHInfo = nullptr;
677 
678  /// Emits a landing pad for the current EH stack.
679  llvm::BasicBlock *EmitLandingPad();
680 
681  llvm::BasicBlock *getInvokeDestImpl();
682 
683  /// Parent loop-based directive for scan directive.
685  llvm::BasicBlock *OMPBeforeScanBlock = nullptr;
686  llvm::BasicBlock *OMPAfterScanBlock = nullptr;
687  llvm::BasicBlock *OMPScanExitBlock = nullptr;
688  llvm::BasicBlock *OMPScanDispatch = nullptr;
689  bool OMPFirstScanLoop = false;
690 
691  /// Manages parent directive for scan directives.
693  CodeGenFunction &CGF;
694  const OMPExecutableDirective *ParentLoopDirectiveForScan;
695 
696  public:
698  CodeGenFunction &CGF,
699  const OMPExecutableDirective &ParentLoopDirectiveForScan)
700  : CGF(CGF),
701  ParentLoopDirectiveForScan(CGF.OMPParentLoopDirectiveForScan) {
702  CGF.OMPParentLoopDirectiveForScan = &ParentLoopDirectiveForScan;
703  }
705  CGF.OMPParentLoopDirectiveForScan = ParentLoopDirectiveForScan;
706  }
707  };
708 
709  template <class T>
711  return DominatingValue<T>::save(*this, value);
712  }
713 
715  public:
716  CGFPOptionsRAII(CodeGenFunction &CGF, FPOptions FPFeatures);
717  CGFPOptionsRAII(CodeGenFunction &CGF, const Expr *E);
719 
720  private:
721  void ConstructorHelper(FPOptions FPFeatures);
722  CodeGenFunction &CGF;
723  FPOptions OldFPFeatures;
724  llvm::fp::ExceptionBehavior OldExcept;
725  llvm::RoundingMode OldRounding;
727  };
729 
730 public:
731  /// ObjCEHValueStack - Stack of Objective-C exception values, used for
732  /// rethrows.
734 
735  /// A class controlling the emission of a finally block.
736  class FinallyInfo {
737  /// Where the catchall's edge through the cleanup should go.
738  JumpDest RethrowDest;
739 
740  /// A function to call to enter the catch.
741  llvm::FunctionCallee BeginCatchFn;
742 
743  /// An i1 variable indicating whether or not the @finally is
744  /// running for an exception.
745  llvm::AllocaInst *ForEHVar;
746 
747  /// An i8* variable into which the exception pointer to rethrow
748  /// has been saved.
749  llvm::AllocaInst *SavedExnVar;
750 
751  public:
752  void enter(CodeGenFunction &CGF, const Stmt *Finally,
753  llvm::FunctionCallee beginCatchFn,
754  llvm::FunctionCallee endCatchFn, llvm::FunctionCallee rethrowFn);
755  void exit(CodeGenFunction &CGF);
756  };
757 
758  /// Returns true inside SEH __try blocks.
759  bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
760 
761  /// Returns true while emitting a cleanuppad.
762  bool isCleanupPadScope() const {
763  return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
764  }
765 
766  /// pushFullExprCleanup - Push a cleanup to be run at the end of the
767  /// current full-expression. Safe against the possibility that
768  /// we're currently inside a conditionally-evaluated expression.
769  template <class T, class... As>
771  // If we're not in a conditional branch, or if none of the
772  // arguments requires saving, then use the unconditional cleanup.
773  if (!isInConditionalBranch())
774  return EHStack.pushCleanup<T>(kind, A...);
775 
776  // Stash values in a tuple so we can guarantee the order of saves.
777  typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
778  SavedTuple Saved{saveValueInCond(A)...};
779 
780  typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
781  EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
783  }
784 
785  /// Queue a cleanup to be pushed after finishing the current full-expression,
786  /// potentially with an active flag.
787  template <class T, class... As>
789  if (!isInConditionalBranch())
790  return pushCleanupAfterFullExprWithActiveFlag<T>(Kind, Address::invalid(),
791  A...);
792 
793  Address ActiveFlag = createCleanupActiveFlag();
794  assert(!DominatingValue<Address>::needsSaving(ActiveFlag) &&
795  "cleanup active flag should never need saving");
796 
797  typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
798  SavedTuple Saved{saveValueInCond(A)...};
799 
800  typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
801  pushCleanupAfterFullExprWithActiveFlag<CleanupType>(Kind, ActiveFlag, Saved);
802  }
803 
804  template <class T, class... As>
806  Address ActiveFlag, As... A) {
807  LifetimeExtendedCleanupHeader Header = {sizeof(T), Kind,
808  ActiveFlag.isValid()};
809 
810  size_t OldSize = LifetimeExtendedCleanupStack.size();
812  LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size +
813  (Header.IsConditional ? sizeof(ActiveFlag) : 0));
814 
815  static_assert(sizeof(Header) % alignof(T) == 0,
816  "Cleanup will be allocated on misaligned address");
817  char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
818  new (Buffer) LifetimeExtendedCleanupHeader(Header);
819  new (Buffer + sizeof(Header)) T(A...);
820  if (Header.IsConditional)
821  new (Buffer + sizeof(Header) + sizeof(T)) Address(ActiveFlag);
822  }
823 
824  /// Set up the last cleanup that was pushed as a conditional
825  /// full-expression cleanup.
828  }
829 
830  void initFullExprCleanupWithFlag(Address ActiveFlag);
832 
833  /// PushDestructorCleanup - Push a cleanup to call the
834  /// complete-object destructor of an object of the given type at the
835  /// given address. Does nothing if T is not a C++ class type with a
836  /// non-trivial destructor.
837  void PushDestructorCleanup(QualType T, Address Addr);
838 
839  /// PushDestructorCleanup - Push a cleanup to call the
840  /// complete-object variant of the given destructor on the object at
841  /// the given address.
843  Address Addr);
844 
845  /// PopCleanupBlock - Will pop the cleanup entry on the stack and
846  /// process all branch fixups.
847  void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
848 
849  /// DeactivateCleanupBlock - Deactivates the given cleanup block.
850  /// The block cannot be reactivated. Pops it if it's the top of the
851  /// stack.
852  ///
853  /// \param DominatingIP - An instruction which is known to
854  /// dominate the current IP (if set) and which lies along
855  /// all paths of execution between the current IP and the
856  /// the point at which the cleanup comes into scope.
858  llvm::Instruction *DominatingIP);
859 
860  /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
861  /// Cannot be used to resurrect a deactivated cleanup.
862  ///
863  /// \param DominatingIP - An instruction which is known to
864  /// dominate the current IP (if set) and which lies along
865  /// all paths of execution between the current IP and the
866  /// the point at which the cleanup comes into scope.
868  llvm::Instruction *DominatingIP);
869 
870  /// Enters a new scope for capturing cleanups, all of which
871  /// will be executed once the scope is exited.
873  EHScopeStack::stable_iterator CleanupStackDepth, OldCleanupScopeDepth;
874  size_t LifetimeExtendedCleanupStackSize;
875  bool OldDidCallStackSave;
876  protected:
878  private:
879 
880  RunCleanupsScope(const RunCleanupsScope &) = delete;
881  void operator=(const RunCleanupsScope &) = delete;
882 
883  protected:
885 
886  public:
887  /// Enter a new cleanup scope.
890  {
891  CleanupStackDepth = CGF.EHStack.stable_begin();
892  LifetimeExtendedCleanupStackSize =
894  OldDidCallStackSave = CGF.DidCallStackSave;
895  CGF.DidCallStackSave = false;
896  OldCleanupScopeDepth = CGF.CurrentCleanupScopeDepth;
897  CGF.CurrentCleanupScopeDepth = CleanupStackDepth;
898  }
899 
900  /// Exit this cleanup scope, emitting any accumulated cleanups.
902  if (PerformCleanup)
903  ForceCleanup();
904  }
905 
906  /// Determine whether this scope requires any cleanups.
907  bool requiresCleanups() const {
908  return CGF.EHStack.stable_begin() != CleanupStackDepth;
909  }
910 
911  /// Force the emission of cleanups now, instead of waiting
912  /// until this object is destroyed.
913  /// \param ValuesToReload - A list of values that need to be available at
914  /// the insertion point after cleanup emission. If cleanup emission created
915  /// a shared cleanup block, these value pointers will be rewritten.
916  /// Otherwise, they not will be modified.
917  void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) {
918  assert(PerformCleanup && "Already forced cleanup");
919  CGF.DidCallStackSave = OldDidCallStackSave;
920  CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize,
921  ValuesToReload);
922  PerformCleanup = false;
923  CGF.CurrentCleanupScopeDepth = OldCleanupScopeDepth;
924  }
925  };
926 
927  // Cleanup stack depth of the RunCleanupsScope that was pushed most recently.
930 
932  SourceRange Range;
934  LexicalScope *ParentScope;
935 
936  LexicalScope(const LexicalScope &) = delete;
937  void operator=(const LexicalScope &) = delete;
938 
939  public:
940  /// Enter a new cleanup scope.
942  : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
943  CGF.CurLexicalScope = this;
944  if (CGDebugInfo *DI = CGF.getDebugInfo())
945  DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
946  }
947 
948  void addLabel(const LabelDecl *label) {
949  assert(PerformCleanup && "adding label to dead scope?");
950  Labels.push_back(label);
951  }
952 
953  /// Exit this cleanup scope, emitting any accumulated
954  /// cleanups.
956  if (CGDebugInfo *DI = CGF.getDebugInfo())
957  DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
958 
959  // If we should perform a cleanup, force them now. Note that
960  // this ends the cleanup scope before rescoping any labels.
961  if (PerformCleanup) {
962  ApplyDebugLocation DL(CGF, Range.getEnd());
963  ForceCleanup();
964  }
965  }
966 
967  /// Force the emission of cleanups now, instead of waiting
968  /// until this object is destroyed.
969  void ForceCleanup() {
970  CGF.CurLexicalScope = ParentScope;
972 
973  if (!Labels.empty())
974  rescopeLabels();
975  }
976 
977  bool hasLabels() const {
978  return !Labels.empty();
979  }
980 
981  void rescopeLabels();
982  };
983 
984  typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
985 
986  /// The class used to assign some variables some temporarily addresses.
987  class OMPMapVars {
988  DeclMapTy SavedLocals;
989  DeclMapTy SavedTempAddresses;
990  OMPMapVars(const OMPMapVars &) = delete;
991  void operator=(const OMPMapVars &) = delete;
992 
993  public:
994  explicit OMPMapVars() = default;
996  assert(SavedLocals.empty() && "Did not restored original addresses.");
997  };
998 
999  /// Sets the address of the variable \p LocalVD to be \p TempAddr in
1000  /// function \p CGF.
1001  /// \return true if at least one variable was set already, false otherwise.
1002  bool setVarAddr(CodeGenFunction &CGF, const VarDecl *LocalVD,
1003  Address TempAddr) {
1004  LocalVD = LocalVD->getCanonicalDecl();
1005  // Only save it once.
1006  if (SavedLocals.count(LocalVD)) return false;
1007 
1008  // Copy the existing local entry to SavedLocals.
1009  auto it = CGF.LocalDeclMap.find(LocalVD);
1010  if (it != CGF.LocalDeclMap.end())
1011  SavedLocals.try_emplace(LocalVD, it->second);
1012  else
1013  SavedLocals.try_emplace(LocalVD, Address::invalid());
1014 
1015  // Generate the private entry.
1016  QualType VarTy = LocalVD->getType();
1017  if (VarTy->isReferenceType()) {
1018  Address Temp = CGF.CreateMemTemp(VarTy);
1019  CGF.Builder.CreateStore(TempAddr.getPointer(), Temp);
1020  TempAddr = Temp;
1021  }
1022  SavedTempAddresses.try_emplace(LocalVD, TempAddr);
1023 
1024  return true;
1025  }
1026 
1027  /// Applies new addresses to the list of the variables.
1028  /// \return true if at least one variable is using new address, false
1029  /// otherwise.
1030  bool apply(CodeGenFunction &CGF) {
1031  copyInto(SavedTempAddresses, CGF.LocalDeclMap);
1032  SavedTempAddresses.clear();
1033  return !SavedLocals.empty();
1034  }
1035 
1036  /// Restores original addresses of the variables.
1038  if (!SavedLocals.empty()) {
1039  copyInto(SavedLocals, CGF.LocalDeclMap);
1040  SavedLocals.clear();
1041  }
1042  }
1043 
1044  private:
1045  /// Copy all the entries in the source map over the corresponding
1046  /// entries in the destination, which must exist.
1047  static void copyInto(const DeclMapTy &Src, DeclMapTy &Dest) {
1048  for (auto &Pair : Src) {
1049  if (!Pair.second.isValid()) {
1050  Dest.erase(Pair.first);
1051  continue;
1052  }
1053 
1054  auto I = Dest.find(Pair.first);
1055  if (I != Dest.end())
1056  I->second = Pair.second;
1057  else
1058  Dest.insert(Pair);
1059  }
1060  }
1061  };
1062 
1063  /// The scope used to remap some variables as private in the OpenMP loop body
1064  /// (or other captured region emitted without outlining), and to restore old
1065  /// vars back on exit.
1067  OMPMapVars MappedVars;
1068  OMPPrivateScope(const OMPPrivateScope &) = delete;
1069  void operator=(const OMPPrivateScope &) = delete;
1070 
1071  public:
1072  /// Enter a new OpenMP private scope.
1074 
1075  /// Registers \p LocalVD variable as a private with \p Addr as the address
1076  /// of the corresponding private variable. \p
1077  /// PrivateGen is the address of the generated private variable.
1078  /// \return true if the variable is registered as private, false if it has
1079  /// been privatized already.
1080  bool addPrivate(const VarDecl *LocalVD, Address Addr) {
1081  assert(PerformCleanup && "adding private to dead scope");
1082  return MappedVars.setVarAddr(CGF, LocalVD, Addr);
1083  }
1084 
1085  /// Privatizes local variables previously registered as private.
1086  /// Registration is separate from the actual privatization to allow
1087  /// initializers use values of the original variables, not the private one.
1088  /// This is important, for example, if the private variable is a class
1089  /// variable initialized by a constructor that references other private
1090  /// variables. But at initialization original variables must be used, not
1091  /// private copies.
1092  /// \return true if at least one variable was privatized, false otherwise.
1093  bool Privatize() { return MappedVars.apply(CGF); }
1094 
1095  void ForceCleanup() {
1097  restoreMap();
1098  }
1099 
1100  /// Exit scope - all the mapped variables are restored.
1102  if (PerformCleanup)
1103  ForceCleanup();
1104  }
1105 
1106  /// Checks if the global variable is captured in current function.
1107  bool isGlobalVarCaptured(const VarDecl *VD) const {
1108  VD = VD->getCanonicalDecl();
1109  return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
1110  }
1111 
1112  /// Restore all mapped variables w/o clean up. This is usefully when we want
1113  /// to reference the original variables but don't want the clean up because
1114  /// that could emit lifetime end too early, causing backend issue #56913.
1115  void restoreMap() { MappedVars.restore(CGF); }
1116  };
1117 
1118  /// Save/restore original map of previously emitted local vars in case when we
1119  /// need to duplicate emission of the same code several times in the same
1120  /// function for OpenMP code.
1122  CodeGenFunction &CGF;
1123  DeclMapTy SavedMap;
1124 
1125  public:
1127  : CGF(CGF), SavedMap(CGF.LocalDeclMap) {}
1128  ~OMPLocalDeclMapRAII() { SavedMap.swap(CGF.LocalDeclMap); }
1129  };
1130 
1131  /// Takes the old cleanup stack size and emits the cleanup blocks
1132  /// that have been added.
1133  void
1134  PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
1135  std::initializer_list<llvm::Value **> ValuesToReload = {});
1136 
1137  /// Takes the old cleanup stack size and emits the cleanup blocks
1138  /// that have been added, then adds all lifetime-extended cleanups from
1139  /// the given position to the stack.
1140  void
1141  PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
1142  size_t OldLifetimeExtendedStackSize,
1143  std::initializer_list<llvm::Value **> ValuesToReload = {});
1144 
1145  void ResolveBranchFixups(llvm::BasicBlock *Target);
1146 
1147  /// The given basic block lies in the current EH scope, but may be a
1148  /// target of a potentially scope-crossing jump; get a stable handle
1149  /// to which we can perform this jump later.
1151  return JumpDest(Target,
1154  }
1155 
1156  /// The given basic block lies in the current EH scope, but may be a
1157  /// target of a potentially scope-crossing jump; get a stable handle
1158  /// to which we can perform this jump later.
1159  JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
1161  }
1162 
1163  /// EmitBranchThroughCleanup - Emit a branch from the current insert
1164  /// block through the normal cleanup handling code (if any) and then
1165  /// on to \arg Dest.
1166  void EmitBranchThroughCleanup(JumpDest Dest);
1167 
1168  /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
1169  /// specified destination obviously has no cleanups to run. 'false' is always
1170  /// a conservatively correct answer for this method.
1171  bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
1172 
1173  /// popCatchScope - Pops the catch scope at the top of the EHScope
1174  /// stack, emitting any required code (other than the catch handlers
1175  /// themselves).
1176  void popCatchScope();
1177 
1178  llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
1179  llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
1180  llvm::BasicBlock *
1182 
1183  /// An object to manage conditionally-evaluated expressions.
1185  llvm::BasicBlock *StartBB;
1186 
1187  public:
1189  : StartBB(CGF.Builder.GetInsertBlock()) {}
1190 
1191  void begin(CodeGenFunction &CGF) {
1192  assert(CGF.OutermostConditional != this);
1193  if (!CGF.OutermostConditional)
1194  CGF.OutermostConditional = this;
1195  }
1196 
1197  void end(CodeGenFunction &CGF) {
1198  assert(CGF.OutermostConditional != nullptr);
1199  if (CGF.OutermostConditional == this)
1200  CGF.OutermostConditional = nullptr;
1201  }
1202 
1203  /// Returns a block which will be executed prior to each
1204  /// evaluation of the conditional code.
1205  llvm::BasicBlock *getStartingBlock() const {
1206  return StartBB;
1207  }
1208  };
1209 
1210  /// isInConditionalBranch - Return true if we're currently emitting
1211  /// one branch or the other of a conditional expression.
1212  bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
1213 
1214  void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
1215  assert(isInConditionalBranch());
1216  llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
1217  auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
1218  store->setAlignment(addr.getAlignment().getAsAlign());
1219  }
1220 
1221  /// An RAII object to record that we're evaluating a statement
1222  /// expression.
1224  CodeGenFunction &CGF;
1225 
1226  /// We have to save the outermost conditional: cleanups in a
1227  /// statement expression aren't conditional just because the
1228  /// StmtExpr is.
1229  ConditionalEvaluation *SavedOutermostConditional;
1230 
1231  public:
1233  : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
1234  CGF.OutermostConditional = nullptr;
1235  }
1236 
1238  CGF.OutermostConditional = SavedOutermostConditional;
1239  CGF.EnsureInsertPoint();
1240  }
1241  };
1242 
1243  /// An object which temporarily prevents a value from being
1244  /// destroyed by aggressive peephole optimizations that assume that
1245  /// all uses of a value have been realized in the IR.
1247  llvm::Instruction *Inst;
1248  friend class CodeGenFunction;
1249 
1250  public:
1251  PeepholeProtection() : Inst(nullptr) {}
1252  };
1253 
1254  /// A non-RAII class containing all the information about a bound
1255  /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
1256  /// this which makes individual mappings very simple; using this
1257  /// class directly is useful when you have a variable number of
1258  /// opaque values or don't want the RAII functionality for some
1259  /// reason.
1261  const OpaqueValueExpr *OpaqueValue;
1262  bool BoundLValue;
1264 
1266  bool boundLValue)
1267  : OpaqueValue(ov), BoundLValue(boundLValue) {}
1268  public:
1269  OpaqueValueMappingData() : OpaqueValue(nullptr) {}
1270 
1271  static bool shouldBindAsLValue(const Expr *expr) {
1272  // gl-values should be bound as l-values for obvious reasons.
1273  // Records should be bound as l-values because IR generation
1274  // always keeps them in memory. Expressions of function type
1275  // act exactly like l-values but are formally required to be
1276  // r-values in C.
1277  return expr->isGLValue() ||
1278  expr->getType()->isFunctionType() ||
1279  hasAggregateEvaluationKind(expr->getType());
1280  }
1281 
1283  const OpaqueValueExpr *ov,
1284  const Expr *e) {
1285  if (shouldBindAsLValue(ov))
1286  return bind(CGF, ov, CGF.EmitLValue(e));
1287  return bind(CGF, ov, CGF.EmitAnyExpr(e));
1288  }
1289 
1291  const OpaqueValueExpr *ov,
1292  const LValue &lv) {
1293  assert(shouldBindAsLValue(ov));
1294  CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
1295  return OpaqueValueMappingData(ov, true);
1296  }
1297 
1299  const OpaqueValueExpr *ov,
1300  const RValue &rv) {
1301  assert(!shouldBindAsLValue(ov));
1302  CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
1303 
1304  OpaqueValueMappingData data(ov, false);
1305 
1306  // Work around an extremely aggressive peephole optimization in
1307  // EmitScalarConversion which assumes that all other uses of a
1308  // value are extant.
1309  data.Protection = CGF.protectFromPeepholes(rv);
1310 
1311  return data;
1312  }
1313 
1314  bool isValid() const { return OpaqueValue != nullptr; }
1315  void clear() { OpaqueValue = nullptr; }
1316 
1318  assert(OpaqueValue && "no data to unbind!");
1319 
1320  if (BoundLValue) {
1321  CGF.OpaqueLValues.erase(OpaqueValue);
1322  } else {
1323  CGF.OpaqueRValues.erase(OpaqueValue);
1324  CGF.unprotectFromPeepholes(Protection);
1325  }
1326  }
1327  };
1328 
1329  /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
1331  CodeGenFunction &CGF;
1333 
1334  public:
1335  static bool shouldBindAsLValue(const Expr *expr) {
1337  }
1338 
1339  /// Build the opaque value mapping for the given conditional
1340  /// operator if it's the GNU ?: extension. This is a common
1341  /// enough pattern that the convenience operator is really
1342  /// helpful.
1343  ///
1345  const AbstractConditionalOperator *op) : CGF(CGF) {
1346  if (isa<ConditionalOperator>(op))
1347  // Leave Data empty.
1348  return;
1349 
1350  const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
1352  e->getCommon());
1353  }
1354 
1355  /// Build the opaque value mapping for an OpaqueValueExpr whose source
1356  /// expression is set to the expression the OVE represents.
1358  : CGF(CGF) {
1359  if (OV) {
1360  assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
1361  "for OVE with no source expression");
1362  Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
1363  }
1364  }
1365 
1367  const OpaqueValueExpr *opaqueValue,
1368  LValue lvalue)
1369  : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
1370  }
1371 
1373  const OpaqueValueExpr *opaqueValue,
1374  RValue rvalue)
1375  : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
1376  }
1377 
1378  void pop() {
1379  Data.unbind(CGF);
1380  Data.clear();
1381  }
1382 
1384  if (Data.isValid()) Data.unbind(CGF);
1385  }
1386  };
1387 
1388 private:
1389  CGDebugInfo *DebugInfo;
1390  /// Used to create unique names for artificial VLA size debug info variables.
1391  unsigned VLAExprCounter = 0;
1392  bool DisableDebugInfo = false;
1393 
1394  /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
1395  /// calling llvm.stacksave for multiple VLAs in the same scope.
1396  bool DidCallStackSave = false;
1397 
1398  /// IndirectBranch - The first time an indirect goto is seen we create a block
1399  /// with an indirect branch. Every time we see the address of a label taken,
1400  /// we add the label to the indirect goto. Every subsequent indirect goto is
1401  /// codegen'd as a jump to the IndirectBranch's basic block.
1402  llvm::IndirectBrInst *IndirectBranch = nullptr;
1403 
1404  /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
1405  /// decls.
1406  DeclMapTy LocalDeclMap;
1407 
1408  // Keep track of the cleanups for callee-destructed parameters pushed to the
1409  // cleanup stack so that they can be deactivated later.
1410  llvm::DenseMap<const ParmVarDecl *, EHScopeStack::stable_iterator>
1411  CalleeDestructedParamCleanups;
1412 
1413  /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
1414  /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
1415  /// parameter.
1416  llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
1417  SizeArguments;
1418 
1419  /// Track escaped local variables with auto storage. Used during SEH
1420  /// outlining to produce a call to llvm.localescape.
1421  llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
1422 
1423  /// LabelMap - This keeps track of the LLVM basic block for each C label.
1424  llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
1425 
1426  // BreakContinueStack - This keeps track of where break and continue
1427  // statements should jump to.
1428  struct BreakContinue {
1429  BreakContinue(JumpDest Break, JumpDest Continue)
1430  : BreakBlock(Break), ContinueBlock(Continue) {}
1431 
1432  JumpDest BreakBlock;
1433  JumpDest ContinueBlock;
1434  };
1435  SmallVector<BreakContinue, 8> BreakContinueStack;
1436 
1437  /// Handles cancellation exit points in OpenMP-related constructs.
1438  class OpenMPCancelExitStack {
1439  /// Tracks cancellation exit point and join point for cancel-related exit
1440  /// and normal exit.
1441  struct CancelExit {
1442  CancelExit() = default;
1443  CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
1444  JumpDest ContBlock)
1445  : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
1446  OpenMPDirectiveKind Kind = llvm::omp::OMPD_unknown;
1447  /// true if the exit block has been emitted already by the special
1448  /// emitExit() call, false if the default codegen is used.
1449  bool HasBeenEmitted = false;
1450  JumpDest ExitBlock;
1451  JumpDest ContBlock;
1452  };
1453 
1454  SmallVector<CancelExit, 8> Stack;
1455 
1456  public:
1457  OpenMPCancelExitStack() : Stack(1) {}
1458  ~OpenMPCancelExitStack() = default;
1459  /// Fetches the exit block for the current OpenMP construct.
1460  JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
1461  /// Emits exit block with special codegen procedure specific for the related
1462  /// OpenMP construct + emits code for normal construct cleanup.
1463  void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1464  const llvm::function_ref<void(CodeGenFunction &)> CodeGen) {
1465  if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
1466  assert(CGF.getOMPCancelDestination(Kind).isValid());
1467  assert(CGF.HaveInsertPoint());
1468  assert(!Stack.back().HasBeenEmitted);
1469  auto IP = CGF.Builder.saveAndClearIP();
1470  CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1471  CodeGen(CGF);
1472  CGF.EmitBranch(Stack.back().ContBlock.getBlock());
1473  CGF.Builder.restoreIP(IP);
1474  Stack.back().HasBeenEmitted = true;
1475  }
1476  CodeGen(CGF);
1477  }
1478  /// Enter the cancel supporting \a Kind construct.
1479  /// \param Kind OpenMP directive that supports cancel constructs.
1480  /// \param HasCancel true, if the construct has inner cancel directive,
1481  /// false otherwise.
1482  void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
1483  Stack.push_back({Kind,
1484  HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
1485  : JumpDest(),
1486  HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
1487  : JumpDest()});
1488  }
1489  /// Emits default exit point for the cancel construct (if the special one
1490  /// has not be used) + join point for cancel/normal exits.
1491  void exit(CodeGenFunction &CGF) {
1492  if (getExitBlock().isValid()) {
1493  assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
1494  bool HaveIP = CGF.HaveInsertPoint();
1495  if (!Stack.back().HasBeenEmitted) {
1496  if (HaveIP)
1497  CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1498  CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1499  CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1500  }
1501  CGF.EmitBlock(Stack.back().ContBlock.getBlock());
1502  if (!HaveIP) {
1503  CGF.Builder.CreateUnreachable();
1504  CGF.Builder.ClearInsertionPoint();
1505  }
1506  }
1507  Stack.pop_back();
1508  }
1509  };
1510  OpenMPCancelExitStack OMPCancelStack;
1511 
1512  /// Lower the Likelihood knowledge about the \p Cond via llvm.expect intrin.
1513  llvm::Value *emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
1514  Stmt::Likelihood LH);
1515 
1516  CodeGenPGO PGO;
1517 
1518  /// Calculate branch weights appropriate for PGO data
1519  llvm::MDNode *createProfileWeights(uint64_t TrueCount,
1520  uint64_t FalseCount) const;
1521  llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights) const;
1522  llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1523  uint64_t LoopCount) const;
1524 
1525 public:
1526  /// Increment the profiler's counter for the given statement by \p StepV.
1527  /// If \p StepV is null, the default increment is 1.
1528  void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
1530  !CurFn->hasFnAttribute(llvm::Attribute::NoProfile) &&
1531  !CurFn->hasFnAttribute(llvm::Attribute::SkipProfile))
1532  PGO.emitCounterIncrement(Builder, S, StepV);
1533  PGO.setCurrentStmt(S);
1534  }
1535 
1536  /// Get the profiler's count for the given statement.
1538  return PGO.getStmtCount(S).value_or(0);
1539  }
1540 
1541  /// Set the profiler's current count.
1543  PGO.setCurrentRegionCount(Count);
1544  }
1545 
1546  /// Get the profiler's current count. This is generally the count for the most
1547  /// recently incremented counter.
1549  return PGO.getCurrentRegionCount();
1550  }
1551 
1552 private:
1553 
1554  /// SwitchInsn - This is nearest current switch instruction. It is null if
1555  /// current context is not in a switch.
1556  llvm::SwitchInst *SwitchInsn = nullptr;
1557  /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1558  SmallVector<uint64_t, 16> *SwitchWeights = nullptr;
1559 
1560  /// The likelihood attributes of the SwitchCase.
1561  SmallVector<Stmt::Likelihood, 16> *SwitchLikelihood = nullptr;
1562 
1563  /// CaseRangeBlock - This block holds if condition check for last case
1564  /// statement range in current switch instruction.
1565  llvm::BasicBlock *CaseRangeBlock = nullptr;
1566 
1567  /// OpaqueLValues - Keeps track of the current set of opaque value
1568  /// expressions.
1569  llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1570  llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1571 
1572  // VLASizeMap - This keeps track of the associated size for each VLA type.
1573  // We track this by the size expression rather than the type itself because
1574  // in certain situations, like a const qualifier applied to an VLA typedef,
1575  // multiple VLA types can share the same size expression.
1576  // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1577  // enter/leave scopes.
1578  llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
1579 
1580  /// A block containing a single 'unreachable' instruction. Created
1581  /// lazily by getUnreachableBlock().
1582  llvm::BasicBlock *UnreachableBlock = nullptr;
1583 
1584  /// Counts of the number return expressions in the function.
1585  unsigned NumReturnExprs = 0;
1586 
1587  /// Count the number of simple (constant) return expressions in the function.
1588  unsigned NumSimpleReturnExprs = 0;
1589 
1590  /// The last regular (non-return) debug location (breakpoint) in the function.
1591  SourceLocation LastStopPoint;
1592 
1593 public:
1594  /// Source location information about the default argument or member
1595  /// initializer expression we're evaluating, if any.
1597  using SourceLocExprScopeGuard =
1599 
1600  /// A scope within which we are constructing the fields of an object which
1601  /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1602  /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1604  public:
1606  : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1607  CGF.CXXDefaultInitExprThis = This;
1608  }
1610  CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1611  }
1612 
1613  private:
1614  CodeGenFunction &CGF;
1615  Address OldCXXDefaultInitExprThis;
1616  };
1617 
1618  /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1619  /// is overridden to be the object under construction.
1621  public:
1623  : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1624  OldCXXThisAlignment(CGF.CXXThisAlignment),
1626  CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
1627  CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
1628  }
1630  CGF.CXXThisValue = OldCXXThisValue;
1631  CGF.CXXThisAlignment = OldCXXThisAlignment;
1632  }
1633 
1634  public:
1636  llvm::Value *OldCXXThisValue;
1639  };
1640 
1644  };
1645 
1646  /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1647  /// current loop index is overridden.
1649  public:
1650  ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
1651  : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
1652  CGF.ArrayInitIndex = Index;
1653  }
1655  CGF.ArrayInitIndex = OldArrayInitIndex;
1656  }
1657 
1658  private:
1659  CodeGenFunction &CGF;
1660  llvm::Value *OldArrayInitIndex;
1661  };
1662 
1664  public:
1666  : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1667  OldCurCodeDecl(CGF.CurCodeDecl),
1668  OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1669  OldCXXABIThisValue(CGF.CXXABIThisValue),
1670  OldCXXThisValue(CGF.CXXThisValue),
1671  OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1672  OldCXXThisAlignment(CGF.CXXThisAlignment),
1673  OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1674  OldCXXInheritedCtorInitExprArgs(
1675  std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1676  CGF.CurGD = GD;
1677  CGF.CurFuncDecl = CGF.CurCodeDecl =
1678  cast<CXXConstructorDecl>(GD.getDecl());
1679  CGF.CXXABIThisDecl = nullptr;
1680  CGF.CXXABIThisValue = nullptr;
1681  CGF.CXXThisValue = nullptr;
1682  CGF.CXXABIThisAlignment = CharUnits();
1683  CGF.CXXThisAlignment = CharUnits();
1684  CGF.ReturnValue = Address::invalid();
1685  CGF.FnRetTy = QualType();
1686  CGF.CXXInheritedCtorInitExprArgs.clear();
1687  }
1689  CGF.CurGD = OldCurGD;
1690  CGF.CurFuncDecl = OldCurFuncDecl;
1691  CGF.CurCodeDecl = OldCurCodeDecl;
1692  CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1693  CGF.CXXABIThisValue = OldCXXABIThisValue;
1694  CGF.CXXThisValue = OldCXXThisValue;
1695  CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1696  CGF.CXXThisAlignment = OldCXXThisAlignment;
1697  CGF.ReturnValue = OldReturnValue;
1698  CGF.FnRetTy = OldFnRetTy;
1699  CGF.CXXInheritedCtorInitExprArgs =
1700  std::move(OldCXXInheritedCtorInitExprArgs);
1701  }
1702 
1703  private:
1704  CodeGenFunction &CGF;
1705  GlobalDecl OldCurGD;
1706  const Decl *OldCurFuncDecl;
1707  const Decl *OldCurCodeDecl;
1708  ImplicitParamDecl *OldCXXABIThisDecl;
1709  llvm::Value *OldCXXABIThisValue;
1710  llvm::Value *OldCXXThisValue;
1711  CharUnits OldCXXABIThisAlignment;
1712  CharUnits OldCXXThisAlignment;
1713  Address OldReturnValue;
1714  QualType OldFnRetTy;
1715  CallArgList OldCXXInheritedCtorInitExprArgs;
1716  };
1717 
1718  // Helper class for the OpenMP IR Builder. Allows reusability of code used for
1719  // region body, and finalization codegen callbacks. This will class will also
1720  // contain privatization functions used by the privatization call backs
1721  //
1722  // TODO: this is temporary class for things that are being moved out of
1723  // CGOpenMPRuntime, new versions of current CodeGenFunction methods, or
1724  // utility function for use with the OMPBuilder. Once that move to use the
1725  // OMPBuilder is done, everything here will either become part of CodeGenFunc.
1726  // directly, or a new helper class that will contain functions used by both
1727  // this and the OMPBuilder
1728 
1730 
1731  OMPBuilderCBHelpers() = delete;
1732  OMPBuilderCBHelpers(const OMPBuilderCBHelpers &) = delete;
1734 
1735  using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1736 
1737  /// Cleanup action for allocate support.
1739 
1740  private:
1741  llvm::CallInst *RTLFnCI;
1742 
1743  public:
1744  OMPAllocateCleanupTy(llvm::CallInst *RLFnCI) : RTLFnCI(RLFnCI) {
1745  RLFnCI->removeFromParent();
1746  }
1747 
1748  void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
1749  if (!CGF.HaveInsertPoint())
1750  return;
1751  CGF.Builder.Insert(RTLFnCI);
1752  }
1753  };
1754 
1755  /// Returns address of the threadprivate variable for the current
1756  /// thread. This Also create any necessary OMP runtime calls.
1757  ///
1758  /// \param VD VarDecl for Threadprivate variable.
1759  /// \param VDAddr Address of the Vardecl
1760  /// \param Loc The location where the barrier directive was encountered
1762  const VarDecl *VD, Address VDAddr,
1763  SourceLocation Loc);
1764 
1765  /// Gets the OpenMP-specific address of the local variable /p VD.
1767  const VarDecl *VD);
1768  /// Get the platform-specific name separator.
1769  /// \param Parts different parts of the final name that needs separation
1770  /// \param FirstSeparator First separator used between the initial two
1771  /// parts of the name.
1772  /// \param Separator separator used between all of the rest consecutinve
1773  /// parts of the name
1775  StringRef FirstSeparator = ".",
1776  StringRef Separator = ".");
1777  /// Emit the Finalization for an OMP region
1778  /// \param CGF The Codegen function this belongs to
1779  /// \param IP Insertion point for generating the finalization code.
1781  CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1782  assert(IP.getBlock()->end() != IP.getPoint() &&
1783  "OpenMP IR Builder should cause terminated block!");
1784 
1785  llvm::BasicBlock *IPBB = IP.getBlock();
1786  llvm::BasicBlock *DestBB = IPBB->getUniqueSuccessor();
1787  assert(DestBB && "Finalization block should have one successor!");
1788 
1789  // erase and replace with cleanup branch.
1790  IPBB->getTerminator()->eraseFromParent();
1791  CGF.Builder.SetInsertPoint(IPBB);
1793  CGF.EmitBranchThroughCleanup(Dest);
1794  }
1795 
1796  /// Emit the body of an OMP region
1797  /// \param CGF The Codegen function this belongs to
1798  /// \param RegionBodyStmt The body statement for the OpenMP region being
1799  /// generated
1800  /// \param AllocaIP Where to insert alloca instructions
1801  /// \param CodeGenIP Where to insert the region code
1802  /// \param RegionName Name to be used for new blocks
1803  static void EmitOMPInlinedRegionBody(CodeGenFunction &CGF,
1804  const Stmt *RegionBodyStmt,
1805  InsertPointTy AllocaIP,
1806  InsertPointTy CodeGenIP,
1807  Twine RegionName);
1808 
1809  static void EmitCaptureStmt(CodeGenFunction &CGF, InsertPointTy CodeGenIP,
1810  llvm::BasicBlock &FiniBB, llvm::Function *Fn,
1811  ArrayRef<llvm::Value *> Args) {
1812  llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
1813  if (llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator())
1814  CodeGenIPBBTI->eraseFromParent();
1815 
1816  CGF.Builder.SetInsertPoint(CodeGenIPBB);
1817 
1818  if (Fn->doesNotThrow())
1819  CGF.EmitNounwindRuntimeCall(Fn, Args);
1820  else
1821  CGF.EmitRuntimeCall(Fn, Args);
1822 
1823  if (CGF.Builder.saveIP().isSet())
1824  CGF.Builder.CreateBr(&FiniBB);
1825  }
1826 
1827  /// Emit the body of an OMP region that will be outlined in
1828  /// OpenMPIRBuilder::finalize().
1829  /// \param CGF The Codegen function this belongs to
1830  /// \param RegionBodyStmt The body statement for the OpenMP region being
1831  /// generated
1832  /// \param AllocaIP Where to insert alloca instructions
1833  /// \param CodeGenIP Where to insert the region code
1834  /// \param RegionName Name to be used for new blocks
1835  static void EmitOMPOutlinedRegionBody(CodeGenFunction &CGF,
1836  const Stmt *RegionBodyStmt,
1837  InsertPointTy AllocaIP,
1838  InsertPointTy CodeGenIP,
1839  Twine RegionName);
1840 
1841  /// RAII for preserving necessary info during Outlined region body codegen.
1843 
1844  llvm::AssertingVH<llvm::Instruction> OldAllocaIP;
1845  CodeGenFunction::JumpDest OldReturnBlock;
1846  CodeGenFunction &CGF;
1847 
1848  public:
1850  llvm::BasicBlock &RetBB)
1851  : CGF(cgf) {
1852  assert(AllocaIP.isSet() &&
1853  "Must specify Insertion point for allocas of outlined function");
1854  OldAllocaIP = CGF.AllocaInsertPt;
1855  CGF.AllocaInsertPt = &*AllocaIP.getPoint();
1856 
1857  OldReturnBlock = CGF.ReturnBlock;
1858  CGF.ReturnBlock = CGF.getJumpDestInCurrentScope(&RetBB);
1859  }
1860 
1862  CGF.AllocaInsertPt = OldAllocaIP;
1863  CGF.ReturnBlock = OldReturnBlock;
1864  }
1865  };
1866 
1867  /// RAII for preserving necessary info during inlined region body codegen.
1869 
1870  llvm::AssertingVH<llvm::Instruction> OldAllocaIP;
1871  CodeGenFunction &CGF;
1872 
1873  public:
1875  llvm::BasicBlock &FiniBB)
1876  : CGF(cgf) {
1877  // Alloca insertion block should be in the entry block of the containing
1878  // function so it expects an empty AllocaIP in which case will reuse the
1879  // old alloca insertion point, or a new AllocaIP in the same block as
1880  // the old one
1881  assert((!AllocaIP.isSet() ||
1882  CGF.AllocaInsertPt->getParent() == AllocaIP.getBlock()) &&
1883  "Insertion point should be in the entry block of containing "
1884  "function!");
1885  OldAllocaIP = CGF.AllocaInsertPt;
1886  if (AllocaIP.isSet())
1887  CGF.AllocaInsertPt = &*AllocaIP.getPoint();
1888 
1889  // TODO: Remove the call, after making sure the counter is not used by
1890  // the EHStack.
1891  // Since this is an inlined region, it should not modify the
1892  // ReturnBlock, and should reuse the one for the enclosing outlined
1893  // region. So, the JumpDest being return by the function is discarded
1894  (void)CGF.getJumpDestInCurrentScope(&FiniBB);
1895  }
1896 
1897  ~InlinedRegionBodyRAII() { CGF.AllocaInsertPt = OldAllocaIP; }
1898  };
1899  };
1900 
1901 private:
1902  /// CXXThisDecl - When generating code for a C++ member function,
1903  /// this will hold the implicit 'this' declaration.
1904  ImplicitParamDecl *CXXABIThisDecl = nullptr;
1905  llvm::Value *CXXABIThisValue = nullptr;
1906  llvm::Value *CXXThisValue = nullptr;
1907  CharUnits CXXABIThisAlignment;
1908  CharUnits CXXThisAlignment;
1909 
1910  /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1911  /// this expression.
1912  Address CXXDefaultInitExprThis = Address::invalid();
1913 
1914  /// The current array initialization index when evaluating an
1915  /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
1916  llvm::Value *ArrayInitIndex = nullptr;
1917 
1918  /// The values of function arguments to use when evaluating
1919  /// CXXInheritedCtorInitExprs within this context.
1920  CallArgList CXXInheritedCtorInitExprArgs;
1921 
1922  /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1923  /// destructor, this will hold the implicit argument (e.g. VTT).
1924  ImplicitParamDecl *CXXStructorImplicitParamDecl = nullptr;
1925  llvm::Value *CXXStructorImplicitParamValue = nullptr;
1926 
1927  /// OutermostConditional - Points to the outermost active
1928  /// conditional control. This is used so that we know if a
1929  /// temporary should be destroyed conditionally.
1930  ConditionalEvaluation *OutermostConditional = nullptr;
1931 
1932  /// The current lexical scope.
1933  LexicalScope *CurLexicalScope = nullptr;
1934 
1935  /// The current source location that should be used for exception
1936  /// handling code.
1937  SourceLocation CurEHLocation;
1938 
1939  /// BlockByrefInfos - For each __block variable, contains
1940  /// information about the layout of the variable.
1941  llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
1942 
1943  /// Used by -fsanitize=nullability-return to determine whether the return
1944  /// value can be checked.
1945  llvm::Value *RetValNullabilityPrecondition = nullptr;
1946 
1947  /// Check if -fsanitize=nullability-return instrumentation is required for
1948  /// this function.
1949  bool requiresReturnValueNullabilityCheck() const {
1950  return RetValNullabilityPrecondition;
1951  }
1952 
1953  /// Used to store precise source locations for return statements by the
1954  /// runtime return value checks.
1955  Address ReturnLocation = Address::invalid();
1956 
1957  /// Check if the return value of this function requires sanitization.
1958  bool requiresReturnValueCheck() const;
1959 
1960  llvm::BasicBlock *TerminateLandingPad = nullptr;
1961  llvm::BasicBlock *TerminateHandler = nullptr;
1963 
1964  /// Terminate funclets keyed by parent funclet pad.
1965  llvm::MapVector<llvm::Value *, llvm::BasicBlock *> TerminateFunclets;
1966 
1967  /// Largest vector width used in ths function. Will be used to create a
1968  /// function attribute.
1969  unsigned LargestVectorWidth = 0;
1970 
1971  /// True if we need emit the life-time markers. This is initially set in
1972  /// the constructor, but could be overwritten to true if this is a coroutine.
1973  bool ShouldEmitLifetimeMarkers;
1974 
1975  /// Add OpenCL kernel arg metadata and the kernel attribute metadata to
1976  /// the function metadata.
1977  void EmitKernelMetadata(const FunctionDecl *FD, llvm::Function *Fn);
1978 
1979 public:
1980  CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
1981  ~CodeGenFunction();
1982 
1983  CodeGenTypes &getTypes() const { return CGM.getTypes(); }
1984  ASTContext &getContext() const { return CGM.getContext(); }
1986  if (DisableDebugInfo)
1987  return nullptr;
1988  return DebugInfo;
1989  }
1990  void disableDebugInfo() { DisableDebugInfo = true; }
1991  void enableDebugInfo() { DisableDebugInfo = false; }
1992 
1994  return CGM.getCodeGenOpts().OptimizationLevel == 0;
1995  }
1996 
1997  const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
1998 
1999  /// Returns a pointer to the function's exception object and selector slot,
2000  /// which is assigned in every landing pad.
2003 
2004  /// Returns the contents of the function's exception object and selector
2005  /// slots.
2006  llvm::Value *getExceptionFromSlot();
2007  llvm::Value *getSelectorFromSlot();
2008 
2010 
2011  llvm::BasicBlock *getUnreachableBlock() {
2012  if (!UnreachableBlock) {
2013  UnreachableBlock = createBasicBlock("unreachable");
2014  new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
2015  }
2016  return UnreachableBlock;
2017  }
2018 
2019  llvm::BasicBlock *getInvokeDest() {
2020  if (!EHStack.requiresLandingPad()) return nullptr;
2021  return getInvokeDestImpl();
2022  }
2023 
2024  bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
2025 
2026  const TargetInfo &getTarget() const { return Target; }
2027  llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
2029  return CGM.getTargetCodeGenInfo();
2030  }
2031 
2032  //===--------------------------------------------------------------------===//
2033  // Cleanups
2034  //===--------------------------------------------------------------------===//
2035 
2036  typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
2037 
2038  void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2039  Address arrayEndPointer,
2040  QualType elementType,
2041  CharUnits elementAlignment,
2042  Destroyer *destroyer);
2043  void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2044  llvm::Value *arrayEnd,
2045  QualType elementType,
2046  CharUnits elementAlignment,
2047  Destroyer *destroyer);
2048 
2049  void pushDestroy(QualType::DestructionKind dtorKind,
2050  Address addr, QualType type);
2052  Address addr, QualType type);
2054  Destroyer *destroyer, bool useEHCleanupForArray);
2056  QualType type, Destroyer *destroyer,
2057  bool useEHCleanupForArray);
2058  void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
2059  llvm::Value *CompletePtr,
2060  QualType ElementType);
2062  void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
2063  bool useEHCleanupForArray);
2064  llvm::Function *generateDestroyHelper(Address addr, QualType type,
2065  Destroyer *destroyer,
2066  bool useEHCleanupForArray,
2067  const VarDecl *VD);
2068  void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
2069  QualType elementType, CharUnits elementAlign,
2070  Destroyer *destroyer,
2071  bool checkZeroLength, bool useEHCleanup);
2072 
2074 
2075  /// Determines whether an EH cleanup is required to destroy a type
2076  /// with the given destruction kind.
2078  switch (kind) {
2079  case QualType::DK_none:
2080  return false;
2084  return getLangOpts().Exceptions;
2086  return getLangOpts().Exceptions &&
2087  CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
2088  }
2089  llvm_unreachable("bad destruction kind");
2090  }
2091 
2094  }
2095 
2096  //===--------------------------------------------------------------------===//
2097  // Objective-C
2098  //===--------------------------------------------------------------------===//
2099 
2100  void GenerateObjCMethod(const ObjCMethodDecl *OMD);
2101 
2102  void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
2103 
2104  /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
2106  const ObjCPropertyImplDecl *PID);
2107  void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
2108  const ObjCPropertyImplDecl *propImpl,
2109  const ObjCMethodDecl *GetterMothodDecl,
2110  llvm::Constant *AtomicHelperFn);
2111 
2113  ObjCMethodDecl *MD, bool ctor);
2114 
2115  /// GenerateObjCSetter - Synthesize an Objective-C property setter function
2116  /// for the given property.
2118  const ObjCPropertyImplDecl *PID);
2119  void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
2120  const ObjCPropertyImplDecl *propImpl,
2121  llvm::Constant *AtomicHelperFn);
2122 
2123  //===--------------------------------------------------------------------===//
2124  // Block Bits
2125  //===--------------------------------------------------------------------===//
2126 
2127  /// Emit block literal.
2128  /// \return an LLVM value which is a pointer to a struct which contains
2129  /// information about the block, including the block invoke function, the
2130  /// captured variables, etc.
2131  llvm::Value *EmitBlockLiteral(const BlockExpr *);
2132 
2133  llvm::Function *GenerateBlockFunction(GlobalDecl GD,
2134  const CGBlockInfo &Info,
2135  const DeclMapTy &ldm,
2136  bool IsLambdaConversionToBlock,
2137  bool BuildGlobalBlock);
2138 
2139  /// Check if \p T is a C++ class that has a destructor that can throw.
2140  static bool cxxDestructorCanThrow(QualType T);
2141 
2142  llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
2143  llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
2145  const ObjCPropertyImplDecl *PID);
2147  const ObjCPropertyImplDecl *PID);
2148  llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
2149 
2150  void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags,
2151  bool CanThrow);
2152 
2153  class AutoVarEmission;
2154 
2155  void emitByrefStructureInit(const AutoVarEmission &emission);
2156 
2157  /// Enter a cleanup to destroy a __block variable. Note that this
2158  /// cleanup should be a no-op if the variable hasn't left the stack
2159  /// yet; if a cleanup is required for the variable itself, that needs
2160  /// to be done externally.
2161  ///
2162  /// \param Kind Cleanup kind.
2163  ///
2164  /// \param Addr When \p LoadBlockVarAddr is false, the address of the __block
2165  /// structure that will be passed to _Block_object_dispose. When
2166  /// \p LoadBlockVarAddr is true, the address of the field of the block
2167  /// structure that holds the address of the __block structure.
2168  ///
2169  /// \param Flags The flag that will be passed to _Block_object_dispose.
2170  ///
2171  /// \param LoadBlockVarAddr Indicates whether we need to emit a load from
2172  /// \p Addr to get the address of the __block structure.
2174  bool LoadBlockVarAddr, bool CanThrow);
2175 
2176  void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
2177  llvm::Value *ptr);
2178 
2181 
2182  /// BuildBlockByrefAddress - Computes the location of the
2183  /// data in a variable which is declared as __block.
2184  Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
2185  bool followForward = true);
2187  const BlockByrefInfo &info,
2188  bool followForward,
2189  const llvm::Twine &name);
2190 
2192 
2194 
2195  void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
2196  const CGFunctionInfo &FnInfo);
2197 
2198  /// Annotate the function with an attribute that disables TSan checking at
2199  /// runtime.
2200  void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn);
2201 
2202  /// Emit code for the start of a function.
2203  /// \param Loc The location to be associated with the function.
2204  /// \param StartLoc The location of the function body.
2205  void StartFunction(GlobalDecl GD,
2206  QualType RetTy,
2207  llvm::Function *Fn,
2208  const CGFunctionInfo &FnInfo,
2209  const FunctionArgList &Args,
2211  SourceLocation StartLoc = SourceLocation());
2212 
2213  static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
2214 
2216  void EmitDestructorBody(FunctionArgList &Args);
2218  void EmitFunctionBody(const Stmt *Body);
2219  void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
2220 
2221  void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
2222  CallArgList &CallArgs);
2225  void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD);
2227  EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2228  }
2229  void EmitAsanPrologueOrEpilogue(bool Prologue);
2230 
2231  /// Emit the unified return block, trying to avoid its emission when
2232  /// possible.
2233  /// \return The debug location of the user written return statement if the
2234  /// return block is is avoided.
2235  llvm::DebugLoc EmitReturnBlock();
2236 
2237  /// FinishFunction - Complete IR generation of the current function. It is
2238  /// legal to call this function even if there is no current insertion point.
2240 
2241  void StartThunk(llvm::Function *Fn, GlobalDecl GD,
2242  const CGFunctionInfo &FnInfo, bool IsUnprototyped);
2243 
2244  void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
2245  const ThunkInfo *Thunk, bool IsUnprototyped);
2246 
2247  void FinishThunk();
2248 
2249  /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
2250  void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr,
2251  llvm::FunctionCallee Callee);
2252 
2253  /// Generate a thunk for the given method.
2254  void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
2255  GlobalDecl GD, const ThunkInfo &Thunk,
2256  bool IsUnprototyped);
2257 
2258  llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
2259  const CGFunctionInfo &FnInfo,
2260  GlobalDecl GD, const ThunkInfo &Thunk);
2261 
2263  FunctionArgList &Args);
2264 
2265  void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
2266 
2267  /// Struct with all information about dynamic [sub]class needed to set vptr.
2268  struct VPtr {
2273  };
2274 
2275  /// Initialize the vtable pointer of the given subobject.
2276  void InitializeVTablePointer(const VPtr &vptr);
2277 
2279 
2281  VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
2282 
2283  void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
2284  CharUnits OffsetFromNearestVBase,
2285  bool BaseIsNonVirtualPrimaryBase,
2286  const CXXRecordDecl *VTableClass,
2287  VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
2288 
2289  void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
2290 
2291  /// GetVTablePtr - Return the Value of the vtable pointer member pointed
2292  /// to by This.
2293  llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
2294  const CXXRecordDecl *VTableClass);
2295 
2304  };
2305 
2306  /// Derived is the presumed address of an object of type T after a
2307  /// cast. If T is a polymorphic class type, emit a check that the virtual
2308  /// table for Derived belongs to a class derived from T.
2309  void EmitVTablePtrCheckForCast(QualType T, Address Derived, bool MayBeNull,
2310  CFITypeCheckKind TCK, SourceLocation Loc);
2311 
2312  /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
2313  /// If vptr CFI is enabled, emit a check that VTable is valid.
2314  void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
2315  CFITypeCheckKind TCK, SourceLocation Loc);
2316 
2317  /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
2318  /// RD using llvm.type.test.
2319  void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
2320  CFITypeCheckKind TCK, SourceLocation Loc);
2321 
2322  /// If whole-program virtual table optimization is enabled, emit an assumption
2323  /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
2324  /// enabled, emit a check that VTable is a member of RD's type identifier.
2326  llvm::Value *VTable, SourceLocation Loc);
2327 
2328  /// Returns whether we should perform a type checked load when loading a
2329  /// virtual function for virtual calls to members of RD. This is generally
2330  /// true when both vcall CFI and whole-program-vtables are enabled.
2332 
2333  /// Emit a type checked load from the given vtable.
2334  llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD,
2335  llvm::Value *VTable,
2336  llvm::Type *VTableTy,
2337  uint64_t VTableByteOffset);
2338 
2339  /// EnterDtorCleanups - Enter the cleanups necessary to complete the
2340  /// given phase of destruction for a destructor. The end result
2341  /// should call destructors on members and base classes in reverse
2342  /// order of their construction.
2344 
2345  /// ShouldInstrumentFunction - Return true if the current function should be
2346  /// instrumented with __cyg_profile_func_* calls
2347  bool ShouldInstrumentFunction();
2348 
2349  /// ShouldSkipSanitizerInstrumentation - Return true if the current function
2350  /// should not be instrumented with sanitizers.
2352 
2353  /// ShouldXRayInstrument - Return true if the current function should be
2354  /// instrumented with XRay nop sleds.
2355  bool ShouldXRayInstrumentFunction() const;
2356 
2357  /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit
2358  /// XRay custom event handling calls.
2359  bool AlwaysEmitXRayCustomEvents() const;
2360 
2361  /// AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit
2362  /// XRay typed event handling calls.
2363  bool AlwaysEmitXRayTypedEvents() const;
2364 
2365  /// Decode an address used in a function prologue, encoded by \c
2366  /// EncodeAddrForUseInPrologue.
2367  llvm::Value *DecodeAddrUsedInPrologue(llvm::Value *F,
2368  llvm::Value *EncodedAddr);
2369 
2370  /// EmitFunctionProlog - Emit the target specific LLVM code to load the
2371  /// arguments for the given function. This is also responsible for naming the
2372  /// LLVM function arguments.
2373  void EmitFunctionProlog(const CGFunctionInfo &FI,
2374  llvm::Function *Fn,
2375  const FunctionArgList &Args);
2376 
2377  /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
2378  /// given temporary.
2379  void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
2380  SourceLocation EndLoc);
2381 
2382  /// Emit a test that checks if the return value \p RV is nonnull.
2383  void EmitReturnValueCheck(llvm::Value *RV);
2384 
2385  /// EmitStartEHSpec - Emit the start of the exception spec.
2386  void EmitStartEHSpec(const Decl *D);
2387 
2388  /// EmitEndEHSpec - Emit the end of the exception spec.
2389  void EmitEndEHSpec(const Decl *D);
2390 
2391  /// getTerminateLandingPad - Return a landing pad that just calls terminate.
2392  llvm::BasicBlock *getTerminateLandingPad();
2393 
2394  /// getTerminateLandingPad - Return a cleanup funclet that just calls
2395  /// terminate.
2396  llvm::BasicBlock *getTerminateFunclet();
2397 
2398  /// getTerminateHandler - Return a handler (not a landing pad, just
2399  /// a catch handler) that just calls terminate. This is used when
2400  /// a terminate scope encloses a try.
2401  llvm::BasicBlock *getTerminateHandler();
2402 
2403  llvm::Type *ConvertTypeForMem(QualType T);
2404  llvm::Type *ConvertType(QualType T);
2405  llvm::Type *ConvertType(const TypeDecl *T) {
2406  return ConvertType(getContext().getTypeDeclType(T));
2407  }
2408 
2409  /// LoadObjCSelf - Load the value of self. This function is only valid while
2410  /// generating code for an Objective-C method.
2411  llvm::Value *LoadObjCSelf();
2412 
2413  /// TypeOfSelfObject - Return type of object that this self represents.
2415 
2416  /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T.
2418 
2420  return getEvaluationKind(T) == TEK_Scalar;
2421  }
2422 
2424  return getEvaluationKind(T) == TEK_Aggregate;
2425  }
2426 
2427  /// createBasicBlock - Create an LLVM basic block.
2428  llvm::BasicBlock *createBasicBlock(const Twine &name = "",
2429  llvm::Function *parent = nullptr,
2430  llvm::BasicBlock *before = nullptr) {
2431  return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
2432  }
2433 
2434  /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
2435  /// label maps to.
2436  JumpDest getJumpDestForLabel(const LabelDecl *S);
2437 
2438  /// SimplifyForwardingBlocks - If the given basic block is only a branch to
2439  /// another basic block, simplify it. This assumes that no other code could
2440  /// potentially reference the basic block.
2441  void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
2442 
2443  /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
2444  /// adding a fall-through branch from the current insert block if
2445  /// necessary. It is legal to call this function even if there is no current
2446  /// insertion point.
2447  ///
2448  /// IsFinished - If true, indicates that the caller has finished emitting
2449  /// branches to the given block and does not expect to emit code into it. This
2450  /// means the block can be ignored if it is unreachable.
2451  void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
2452 
2453  /// EmitBlockAfterUses - Emit the given block somewhere hopefully
2454  /// near its uses, and leave the insertion point in it.
2455  void EmitBlockAfterUses(llvm::BasicBlock *BB);
2456 
2457  /// EmitBranch - Emit a branch to the specified basic block from the current
2458  /// insert block, taking care to avoid creation of branches from dummy
2459  /// blocks. It is legal to call this function even if there is no current
2460  /// insertion point.
2461  ///
2462  /// This function clears the current insertion point. The caller should follow
2463  /// calls to this function with calls to Emit*Block prior to generation new
2464  /// code.
2465  void EmitBranch(llvm::BasicBlock *Block);
2466 
2467  /// HaveInsertPoint - True if an insertion point is defined. If not, this
2468  /// indicates that the current code being emitted is unreachable.
2469  bool HaveInsertPoint() const {
2470  return Builder.GetInsertBlock() != nullptr;
2471  }
2472 
2473  /// EnsureInsertPoint - Ensure that an insertion point is defined so that
2474  /// emitted IR has a place to go. Note that by definition, if this function
2475  /// creates a block then that block is unreachable; callers may do better to
2476  /// detect when no insertion point is defined and simply skip IR generation.
2478  if (!HaveInsertPoint())
2480  }
2481 
2482  /// ErrorUnsupported - Print out an error that codegen doesn't support the
2483  /// specified stmt yet.
2484  void ErrorUnsupported(const Stmt *S, const char *Type);
2485 
2486  //===--------------------------------------------------------------------===//
2487  // Helpers
2488  //===--------------------------------------------------------------------===//
2489 
2492  return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
2493  CGM.getTBAAAccessInfo(T));
2494  }
2495 
2497  TBAAAccessInfo TBAAInfo) {
2498  return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
2499  }
2500 
2501  LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
2503  Address Addr(V, ConvertTypeForMem(T), Alignment);
2504  return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
2505  CGM.getTBAAAccessInfo(T));
2506  }
2507 
2508  LValue
2511  return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
2512  TBAAAccessInfo());
2513  }
2514 
2516  LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
2517 
2519  LValueBaseInfo *PointeeBaseInfo = nullptr,
2520  TBAAAccessInfo *PointeeTBAAInfo = nullptr);
2523  AlignmentSource Source =
2525  LValue RefLVal = MakeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source),
2526  CGM.getTBAAAccessInfo(RefTy));
2527  return EmitLoadOfReferenceLValue(RefLVal);
2528  }
2529 
2530  /// Load a pointer with type \p PtrTy stored at address \p Ptr.
2531  /// Note that \p PtrTy is the type of the loaded pointer, not the addresses
2532  /// it is loaded from.
2533  Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
2534  LValueBaseInfo *BaseInfo = nullptr,
2535  TBAAAccessInfo *TBAAInfo = nullptr);
2537 
2538  /// CreateTempAlloca - This creates an alloca and inserts it into the entry
2539  /// block if \p ArraySize is nullptr, otherwise inserts it at the current
2540  /// insertion point of the builder. The caller is responsible for setting an
2541  /// appropriate alignment on
2542  /// the alloca.
2543  ///
2544  /// \p ArraySize is the number of array elements to be allocated if it
2545  /// is not nullptr.
2546  ///
2547  /// LangAS::Default is the address space of pointers to local variables and
2548  /// temporaries, as exposed in the source language. In certain
2549  /// configurations, this is not the same as the alloca address space, and a
2550  /// cast is needed to lift the pointer from the alloca AS into
2551  /// LangAS::Default. This can happen when the target uses a restricted
2552  /// address space for the stack but the source language requires
2553  /// LangAS::Default to be a generic address space. The latter condition is
2554  /// common for most programming languages; OpenCL is an exception in that
2555  /// LangAS::Default is the private address space, which naturally maps
2556  /// to the stack.
2557  ///
2558  /// Because the address of a temporary is often exposed to the program in
2559  /// various ways, this function will perform the cast. The original alloca
2560  /// instruction is returned through \p Alloca if it is not nullptr.
2561  ///
2562  /// The cast is not performaed in CreateTempAllocaWithoutCast. This is
2563  /// more efficient if the caller knows that the address will not be exposed.
2564  llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp",
2565  llvm::Value *ArraySize = nullptr);
2566  Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
2567  const Twine &Name = "tmp",
2568  llvm::Value *ArraySize = nullptr,
2569  Address *Alloca = nullptr);
2571  const Twine &Name = "tmp",
2572  llvm::Value *ArraySize = nullptr);
2573 
2574  /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
2575  /// default ABI alignment of the given LLVM type.
2576  ///
2577  /// IMPORTANT NOTE: This is *not* generally the right alignment for
2578  /// any given AST type that happens to have been lowered to the
2579  /// given IR type. This should only ever be used for function-local,
2580  /// IR-driven manipulations like saving and restoring a value. Do
2581  /// not hand this address off to arbitrary IRGen routines, and especially
2582  /// do not pass it as an argument to a function that might expect a
2583  /// properly ABI-aligned value.
2584  Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
2585  const Twine &Name = "tmp");
2586 
2587  /// CreateIRTemp - Create a temporary IR object of the given type, with
2588  /// appropriate alignment. This routine should only be used when an temporary
2589  /// value needs to be stored into an alloca (for example, to avoid explicit
2590  /// PHI construction), but the type is the IR type, not the type appropriate
2591  /// for storing in memory.
2592  ///
2593  /// That is, this is exactly equivalent to CreateMemTemp, but calling
2594  /// ConvertType instead of ConvertTypeForMem.
2595  Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
2596 
2597  /// CreateMemTemp - Create a temporary memory object of the given type, with
2598  /// appropriate alignmen and cast it to the default address space. Returns
2599  /// the original alloca instruction by \p Alloca if it is not nullptr.
2600  Address CreateMemTemp(QualType T, const Twine &Name = "tmp",
2601  Address *Alloca = nullptr);
2602  Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp",
2603  Address *Alloca = nullptr);
2604 
2605  /// CreateMemTemp - Create a temporary memory object of the given type, with
2606  /// appropriate alignmen without casting it to the default address space.
2607  Address CreateMemTempWithoutCast(QualType T, const Twine &Name = "tmp");
2609  const Twine &Name = "tmp");
2610 
2611  /// CreateAggTemp - Create a temporary memory object for the given
2612  /// aggregate type.
2613  AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp",
2614  Address *Alloca = nullptr) {
2615  return AggValueSlot::forAddr(CreateMemTemp(T, Name, Alloca),
2616  T.getQualifiers(),
2621  }
2622 
2623  /// Emit a cast to void* in the appropriate address space.
2624  llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
2625 
2626  /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
2627  /// expression and compare the result against zero, returning an Int1Ty value.
2628  llvm::Value *EvaluateExprAsBool(const Expr *E);
2629 
2630  /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
2631  void EmitIgnoredExpr(const Expr *E);
2632 
2633  /// EmitAnyExpr - Emit code to compute the specified expression which can have
2634  /// any type. The result is returned as an RValue struct. If this is an
2635  /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
2636  /// the result should be returned.
2637  ///
2638  /// \param ignoreResult True if the resulting value isn't used.
2639  RValue EmitAnyExpr(const Expr *E,
2640  AggValueSlot aggSlot = AggValueSlot::ignored(),
2641  bool ignoreResult = false);
2642 
2643  // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
2644  // or the value of the expression, depending on how va_list is defined.
2645  Address EmitVAListRef(const Expr *E);
2646 
2647  /// Emit a "reference" to a __builtin_ms_va_list; this is
2648  /// always the value of the expression, because a __builtin_ms_va_list is a
2649  /// pointer to a char.
2650  Address EmitMSVAListRef(const Expr *E);
2651 
2652  /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
2653  /// always be accessible even if no aggregate location is provided.
2654  RValue EmitAnyExprToTemp(const Expr *E);
2655 
2656  /// EmitAnyExprToMem - Emits the code necessary to evaluate an
2657  /// arbitrary expression into the given memory location.
2658  void EmitAnyExprToMem(const Expr *E, Address Location,
2659  Qualifiers Quals, bool IsInitializer);
2660 
2661  void EmitAnyExprToExn(const Expr *E, Address Addr);
2662 
2663  /// EmitExprAsInit - Emits the code necessary to initialize a
2664  /// location in memory with the given initializer.
2665  void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2666  bool capturedByInit);
2667 
2668  /// hasVolatileMember - returns true if aggregate type has a volatile
2669  /// member.
2671  if (const RecordType *RT = T->getAs<RecordType>()) {
2672  const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2673  return RD->hasVolatileMember();
2674  }
2675  return false;
2676  }
2677 
2678  /// Determine whether a return value slot may overlap some other object.
2680  // FIXME: Assuming no overlap here breaks guaranteed copy elision for base
2681  // class subobjects. These cases may need to be revisited depending on the
2682  // resolution of the relevant core issue.
2684  }
2685 
2686  /// Determine whether a field initialization may overlap some other object.
2688 
2689  /// Determine whether a base class initialization may overlap some other
2690  /// object.
2692  const CXXRecordDecl *BaseRD,
2693  bool IsVirtual);
2694 
2695  /// Emit an aggregate assignment.
2696  void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy) {
2697  bool IsVolatile = hasVolatileMember(EltTy);
2698  EmitAggregateCopy(Dest, Src, EltTy, AggValueSlot::MayOverlap, IsVolatile);
2699  }
2700 
2702  AggValueSlot::Overlap_t MayOverlap) {
2703  EmitAggregateCopy(Dest, Src, Src.getType(), MayOverlap);
2704  }
2705 
2706  /// EmitAggregateCopy - Emit an aggregate copy.
2707  ///
2708  /// \param isVolatile \c true iff either the source or the destination is
2709  /// volatile.
2710  /// \param MayOverlap Whether the tail padding of the destination might be
2711  /// occupied by some other object. More efficient code can often be
2712  /// generated if not.
2713  void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy,
2714  AggValueSlot::Overlap_t MayOverlap,
2715  bool isVolatile = false);
2716 
2717  /// GetAddrOfLocalVar - Return the address of a local variable.
2719  auto it = LocalDeclMap.find(VD);
2720  assert(it != LocalDeclMap.end() &&
2721  "Invalid argument to GetAddrOfLocalVar(), no decl!");
2722  return it->second;
2723  }
2724 
2725  /// Given an opaque value expression, return its LValue mapping if it exists,
2726  /// otherwise create one.
2728 
2729  /// Given an opaque value expression, return its RValue mapping if it exists,
2730  /// otherwise create one.
2732 
2733  /// Get the index of the current ArrayInitLoopExpr, if any.
2734  llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2735 
2736  /// getAccessedFieldNo - Given an encoded value and a result number, return
2737  /// the input field number being accessed.
2738  static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2739 
2740  llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
2741  llvm::BasicBlock *GetIndirectGotoBlock();
2742 
2743  /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
2744  static bool IsWrappedCXXThis(const Expr *E);
2745 
2746  /// EmitNullInitialization - Generate code to set a value of the given type to
2747  /// null, If the type contains data member pointers, they will be initialized
2748  /// to -1 in accordance with the Itanium C++ ABI.
2749  void EmitNullInitialization(Address DestPtr, QualType Ty);
2750 
2751  /// Emits a call to an LLVM variable-argument intrinsic, either
2752  /// \c llvm.va_start or \c llvm.va_end.
2753  /// \param ArgValue A reference to the \c va_list as emitted by either
2754  /// \c EmitVAListRef or \c EmitMSVAListRef.
2755  /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2756  /// calls \c llvm.va_end.
2757  llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2758 
2759  /// Generate code to get an argument from the passed in pointer
2760  /// and update it accordingly.
2761  /// \param VE The \c VAArgExpr for which to generate code.
2762  /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2763  /// either \c EmitVAListRef or \c EmitMSVAListRef.
2764  /// \returns A pointer to the argument.
2765  // FIXME: We should be able to get rid of this method and use the va_arg
2766  // instruction in LLVM instead once it works well enough.
2767  Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
2768 
2769  /// emitArrayLength - Compute the length of an array, even if it's a
2770  /// VLA, and drill down to the base element type.
2771  llvm::Value *emitArrayLength(const ArrayType *arrayType,
2772  QualType &baseType,
2773  Address &addr);
2774 
2775  /// EmitVLASize - Capture all the sizes for the VLA expressions in
2776  /// the given variably-modified type and store them in the VLASizeMap.
2777  ///
2778  /// This function can be called with a null (unreachable) insert point.
2780 
2781  struct VlaSizePair {
2782  llvm::Value *NumElts;
2784 
2785  VlaSizePair(llvm::Value *NE, QualType T) : NumElts(NE), Type(T) {}
2786  };
2787 
2788  /// Return the number of elements for a single dimension
2789  /// for the given array type.
2790  VlaSizePair getVLAElements1D(const VariableArrayType *vla);
2791  VlaSizePair getVLAElements1D(QualType vla);
2792 
2793  /// Returns an LLVM value that corresponds to the size,
2794  /// in non-variably-sized elements, of a variable length array type,
2795  /// plus that largest non-variably-sized element type. Assumes that
2796  /// the type has already been emitted with EmitVariablyModifiedType.
2797  VlaSizePair getVLASize(const VariableArrayType *vla);
2798  VlaSizePair getVLASize(QualType vla);
2799 
2800  /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2801  /// generating code for an C++ member function.
2802  llvm::Value *LoadCXXThis() {
2803  assert(CXXThisValue && "no 'this' value for this function");
2804  return CXXThisValue;
2805  }
2807 
2808  /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2809  /// virtual bases.
2810  // FIXME: Every place that calls LoadCXXVTT is something
2811  // that needs to be abstracted properly.
2812  llvm::Value *LoadCXXVTT() {
2813  assert(CXXStructorImplicitParamValue && "no VTT value for this function");
2814  return CXXStructorImplicitParamValue;
2815  }
2816 
2817  /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
2818  /// complete class to the given direct base.
2819  Address
2821  const CXXRecordDecl *Derived,
2822  const CXXRecordDecl *Base,
2823  bool BaseIsVirtual);
2824 
2825  static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2826 
2827  /// GetAddressOfBaseClass - This function will add the necessary delta to the
2828  /// load of 'this' and returns address of the base class.
2830  const CXXRecordDecl *Derived,
2833  bool NullCheckValue, SourceLocation Loc);
2834 
2836  const CXXRecordDecl *Derived,
2839  bool NullCheckValue);
2840 
2841  /// GetVTTParameter - Return the VTT parameter that should be passed to a
2842  /// base constructor/destructor with virtual bases.
2843  /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2844  /// to ItaniumCXXABI.cpp together with all the references to VTT.
2845  llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2846  bool Delegating);
2847 
2849  CXXCtorType CtorType,
2850  const FunctionArgList &Args,
2851  SourceLocation Loc);
2852  // It's important not to confuse this and the previous function. Delegating
2853  // constructors are the C++0x feature. The constructor delegate optimization
2854  // is used to reduce duplication in the base and complete consturctors where
2855  // they are substantially the same.
2857  const FunctionArgList &Args);
2858 
2859  /// Emit a call to an inheriting constructor (that is, one that invokes a
2860  /// constructor inherited from a base class) by inlining its definition. This
2861  /// is necessary if the ABI does not support forwarding the arguments to the
2862  /// base class constructor (because they're variadic or similar).
2864  CXXCtorType CtorType,
2865  bool ForVirtualBase,
2866  bool Delegating,
2867  CallArgList &Args);
2868 
2869  /// Emit a call to a constructor inherited from a base class, passing the
2870  /// current constructor's arguments along unmodified (without even making
2871  /// a copy).
2873  bool ForVirtualBase, Address This,
2874  bool InheritedFromVBase,
2875  const CXXInheritedCtorInitExpr *E);
2876 
2878  bool ForVirtualBase, bool Delegating,
2879  AggValueSlot ThisAVS, const CXXConstructExpr *E);
2880 
2882  bool ForVirtualBase, bool Delegating,
2883  Address This, CallArgList &Args,
2884  AggValueSlot::Overlap_t Overlap,
2885  SourceLocation Loc, bool NewPointerIsChecked);
2886 
2887  /// Emit assumption load for all bases. Requires to be be called only on
2888  /// most-derived class and not under construction of the object.
2889  void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2890 
2891  /// Emit assumption that vptr load == global vtable.
2892  void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2893 
2895  Address This, Address Src,
2896  const CXXConstructExpr *E);
2897 
2899  const ArrayType *ArrayTy,
2900  Address ArrayPtr,
2901  const CXXConstructExpr *E,
2902  bool NewPointerIsChecked,
2903  bool ZeroInitialization = false);
2904 
2906  llvm::Value *NumElements,
2907  Address ArrayPtr,
2908  const CXXConstructExpr *E,
2909  bool NewPointerIsChecked,
2910  bool ZeroInitialization = false);
2911 
2913 
2915  bool ForVirtualBase, bool Delegating, Address This,
2916  QualType ThisTy);
2917 
2918  void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2919  llvm::Type *ElementTy, Address NewPtr,
2920  llvm::Value *NumElements,
2921  llvm::Value *AllocSizeWithoutCookie);
2922 
2923  void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2924  Address Ptr);
2925 
2926  void EmitSehCppScopeBegin();
2927  void EmitSehCppScopeEnd();
2928  void EmitSehTryScopeBegin();
2929  void EmitSehTryScopeEnd();
2930 
2931  llvm::Value *EmitLifetimeStart(llvm::TypeSize Size, llvm::Value *Addr);
2932  void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2933 
2934  llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
2935  void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
2936 
2937  void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
2938  QualType DeleteTy, llvm::Value *NumElements = nullptr,
2939  CharUnits CookieSize = CharUnits());
2940 
2942  const CallExpr *TheCallExpr, bool IsDelete);
2943 
2944  llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2945  llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2947 
2948  /// Situations in which we might emit a check for the suitability of a
2949  /// pointer or glvalue. Needs to be kept in sync with ubsan_handlers.cpp in
2950  /// compiler-rt.
2952  /// Checking the operand of a load. Must be suitably sized and aligned.
2954  /// Checking the destination of a store. Must be suitably sized and aligned.
2956  /// Checking the bound value in a reference binding. Must be suitably sized
2957  /// and aligned, but is not required to refer to an object (until the
2958  /// reference is used), per core issue 453.
2960  /// Checking the object expression in a non-static data member access. Must
2961  /// be an object within its lifetime.
2963  /// Checking the 'this' pointer for a call to a non-static member function.
2964  /// Must be an object within its lifetime.
2966  /// Checking the 'this' pointer for a constructor call.
2968  /// Checking the operand of a static_cast to a derived pointer type. Must be
2969  /// null or an object within its lifetime.
2971  /// Checking the operand of a static_cast to a derived reference type. Must
2972  /// be an object within its lifetime.
2974  /// Checking the operand of a cast to a base object. Must be suitably sized
2975  /// and aligned.
2977  /// Checking the operand of a cast to a virtual base object. Must be an
2978  /// object within its lifetime.
2980  /// Checking the value assigned to a _Nonnull pointer. Must not be null.
2982  /// Checking the operand of a dynamic_cast or a typeid expression. Must be
2983  /// null or an object within its lifetime.
2985  };
2986 
2987  /// Determine whether the pointer type check \p TCK permits null pointers.
2988  static bool isNullPointerAllowed(TypeCheckKind TCK);
2989 
2990  /// Determine whether the pointer type check \p TCK requires a vptr check.
2991  static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty);
2992 
2993  /// Whether any type-checking sanitizers are enabled. If \c false,
2994  /// calls to EmitTypeCheck can be skipped.
2995  bool sanitizePerformTypeCheck() const;
2996 
2997  /// Emit a check that \p V is the address of storage of the
2998  /// appropriate size and alignment for an object of type \p Type
2999  /// (or if ArraySize is provided, for an array of that bound).
3000  void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
3001  QualType Type, CharUnits Alignment = CharUnits::Zero(),
3002  SanitizerSet SkippedChecks = SanitizerSet(),
3003  llvm::Value *ArraySize = nullptr);
3004 
3005  /// Emit a check that \p Base points into an array object, which
3006  /// we can access at index \p Index. \p Accessed should be \c false if we
3007  /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
3008  void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
3009  QualType IndexType, bool Accessed);
3010 
3011  llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3012  bool isInc, bool isPre);
3014  bool isInc, bool isPre);
3015 
3016  /// Converts Location to a DebugLoc, if debug information is enabled.
3017  llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
3018 
3019  /// Get the record field index as represented in debug info.
3020  unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex);
3021 
3022 
3023  //===--------------------------------------------------------------------===//
3024  // Declaration Emission
3025  //===--------------------------------------------------------------------===//
3026 
3027  /// EmitDecl - Emit a declaration.
3028  ///
3029  /// This function can be called with a null (unreachable) insert point.
3030  void EmitDecl(const Decl &D);
3031 
3032  /// EmitVarDecl - Emit a local variable declaration.
3033  ///
3034  /// This function can be called with a null (unreachable) insert point.
3035  void EmitVarDecl(const VarDecl &D);
3036 
3037  void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
3038  bool capturedByInit);
3039 
3040  typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
3041  llvm::Value *Address);
3042 
3043  /// Determine whether the given initializer is trivial in the sense
3044  /// that it requires no code to be generated.
3045  bool isTrivialInitializer(const Expr *Init);
3046 
3047  /// EmitAutoVarDecl - Emit an auto variable declaration.
3048  ///
3049  /// This function can be called with a null (unreachable) insert point.
3050  void EmitAutoVarDecl(const VarDecl &D);
3051 
3053  friend class CodeGenFunction;
3054 
3055  const VarDecl *Variable;
3056 
3057  /// The address of the alloca for languages with explicit address space
3058  /// (e.g. OpenCL) or alloca casted to generic pointer for address space
3059  /// agnostic languages (e.g. C++). Invalid if the variable was emitted
3060  /// as a global constant.
3061  Address Addr;
3062 
3063  llvm::Value *NRVOFlag;
3064 
3065  /// True if the variable is a __block variable that is captured by an
3066  /// escaping block.
3067  bool IsEscapingByRef;
3068 
3069  /// True if the variable is of aggregate type and has a constant
3070  /// initializer.
3071  bool IsConstantAggregate;
3072 
3073  /// Non-null if we should use lifetime annotations.
3074  llvm::Value *SizeForLifetimeMarkers;
3075 
3076  /// Address with original alloca instruction. Invalid if the variable was
3077  /// emitted as a global constant.
3078  Address AllocaAddr;
3079 
3080  struct Invalid {};
3081  AutoVarEmission(Invalid)
3082  : Variable(nullptr), Addr(Address::invalid()),
3083  AllocaAddr(Address::invalid()) {}
3084 
3085  AutoVarEmission(const VarDecl &variable)
3086  : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
3087  IsEscapingByRef(false), IsConstantAggregate(false),
3088  SizeForLifetimeMarkers(nullptr), AllocaAddr(Address::invalid()) {}
3089 
3090  bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
3091 
3092  public:
3093  static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
3094 
3095  bool useLifetimeMarkers() const {
3096  return SizeForLifetimeMarkers != nullptr;
3097  }
3098  llvm::Value *getSizeForLifetimeMarkers() const {
3099  assert(useLifetimeMarkers());
3100  return SizeForLifetimeMarkers;
3101  }
3102 
3103  /// Returns the raw, allocated address, which is not necessarily
3104  /// the address of the object itself. It is casted to default
3105  /// address space for address space agnostic languages.
3107  return Addr;
3108  }
3109 
3110  /// Returns the address for the original alloca instruction.
3111  Address getOriginalAllocatedAddress() const { return AllocaAddr; }
3112 
3113  /// Returns the address of the object within this declaration.
3114  /// Note that this does not chase the forwarding pointer for
3115  /// __block decls.
3117  if (!IsEscapingByRef) return Addr;
3118 
3119  return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
3120  }
3121  };
3122  AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
3123  void EmitAutoVarInit(const AutoVarEmission &emission);
3124  void EmitAutoVarCleanups(const AutoVarEmission &emission);
3125  void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
3126  QualType::DestructionKind dtorKind);
3127 
3128  /// Emits the alloca and debug information for the size expressions for each
3129  /// dimension of an array. It registers the association of its (1-dimensional)
3130  /// QualTypes and size expression's debug node, so that CGDebugInfo can
3131  /// reference this node when creating the DISubrange object to describe the
3132  /// array types.
3134  const VarDecl &D,
3135  bool EmitDebugInfo);
3136 
3137  void EmitStaticVarDecl(const VarDecl &D,
3138  llvm::GlobalValue::LinkageTypes Linkage);
3139 
3140  class ParamValue {
3141  llvm::Value *Value;
3142  llvm::Type *ElementType;
3143  unsigned Alignment;
3144  ParamValue(llvm::Value *V, llvm::Type *T, unsigned A)
3145  : Value(V), ElementType(T), Alignment(A) {}
3146  public:
3147  static ParamValue forDirect(llvm::Value *value) {
3148  return ParamValue(value, nullptr, 0);
3149  }
3151  assert(!addr.getAlignment().isZero());
3152  return ParamValue(addr.getPointer(), addr.getElementType(),
3153  addr.getAlignment().getQuantity());
3154  }
3155 
3156  bool isIndirect() const { return Alignment != 0; }
3157  llvm::Value *getAnyValue() const { return Value; }
3158 
3159  llvm::Value *getDirectValue() const {
3160  assert(!isIndirect());
3161  return Value;
3162  }
3163 
3165  assert(isIndirect());
3166  return Address(Value, ElementType, CharUnits::fromQuantity(Alignment));
3167  }
3168  };
3169 
3170  /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
3171  void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
3172 
3173  /// protectFromPeepholes - Protect a value that we're intending to
3174  /// store to the side, but which will probably be used later, from
3175  /// aggressive peepholing optimizations that might delete it.
3176  ///
3177  /// Pass the result to unprotectFromPeepholes to declare that
3178  /// protection is no longer required.
3179  ///
3180  /// There's no particular reason why this shouldn't apply to
3181  /// l-values, it's just that no existing peepholes work on pointers.
3182  PeepholeProtection protectFromPeepholes(RValue rvalue);
3183  void unprotectFromPeepholes(PeepholeProtection protection);
3184 
3185  void emitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty,
3186  SourceLocation Loc,
3187  SourceLocation AssumptionLoc,
3188  llvm::Value *Alignment,
3189  llvm::Value *OffsetValue,
3190  llvm::Value *TheCheck,
3191  llvm::Instruction *Assumption);
3192 
3193  void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty,
3194  SourceLocation Loc, SourceLocation AssumptionLoc,
3195  llvm::Value *Alignment,
3196  llvm::Value *OffsetValue = nullptr);
3197 
3198  void emitAlignmentAssumption(llvm::Value *PtrValue, const Expr *E,
3199  SourceLocation AssumptionLoc,
3200  llvm::Value *Alignment,
3201  llvm::Value *OffsetValue = nullptr);
3202 
3203  //===--------------------------------------------------------------------===//
3204  // Statement Emission
3205  //===--------------------------------------------------------------------===//
3206 
3207  /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
3208  void EmitStopPoint(const Stmt *S);
3209 
3210  /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
3211  /// this function even if there is no current insertion point.
3212  ///
3213  /// This function may clear the current insertion point; callers should use
3214  /// EnsureInsertPoint if they wish to subsequently generate code without first
3215  /// calling EmitBlock, EmitBranch, or EmitStmt.
3216  void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = None);
3217 
3218  /// EmitSimpleStmt - Try to emit a "simple" statement which does not
3219  /// necessarily require an insertion point or debug information; typically
3220  /// because the statement amounts to a jump or a container of other
3221  /// statements.
3222  ///
3223  /// \return True if the statement was handled.
3224  bool EmitSimpleStmt(const Stmt *S, ArrayRef<const Attr *> Attrs);
3225 
3226  Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
3229  bool GetLast = false,
3230  AggValueSlot AVS =
3232 
3233  /// EmitLabel - Emit the block for the given label. It is legal to call this
3234  /// function even if there is no current insertion point.
3235  void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
3236 
3237  void EmitLabelStmt(const LabelStmt &S);
3238  void EmitAttributedStmt(const AttributedStmt &S);
3239  void EmitGotoStmt(const GotoStmt &S);
3240  void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
3241  void EmitIfStmt(const IfStmt &S);
3242 
3243  void EmitWhileStmt(const WhileStmt &S,
3244  ArrayRef<const Attr *> Attrs = None);
3245  void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
3246  void EmitForStmt(const ForStmt &S,
3247  ArrayRef<const Attr *> Attrs = None);
3248  void EmitReturnStmt(const ReturnStmt &S);
3249  void EmitDeclStmt(const DeclStmt &S);
3250  void EmitBreakStmt(const BreakStmt &S);
3251  void EmitContinueStmt(const ContinueStmt &S);
3252  void EmitSwitchStmt(const SwitchStmt &S);
3253  void EmitDefaultStmt(const DefaultStmt &S, ArrayRef<const Attr *> Attrs);
3254  void EmitCaseStmt(const CaseStmt &S, ArrayRef<const Attr *> Attrs);
3255  void EmitCaseStmtRange(const CaseStmt &S, ArrayRef<const Attr *> Attrs);
3256  void EmitAsmStmt(const AsmStmt &S);
3257 
3259  void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
3260  void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
3263 
3264  void EmitCoroutineBody(const CoroutineBodyStmt &S);
3265  void EmitCoreturnStmt(const CoreturnStmt &S);
3267  AggValueSlot aggSlot = AggValueSlot::ignored(),
3268  bool ignoreResult = false);
3271  AggValueSlot aggSlot = AggValueSlot::ignored(),
3272  bool ignoreResult = false);
3274  RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
3275 
3276  void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
3277  void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
3278 
3279  void EmitCXXTryStmt(const CXXTryStmt &S);
3280  void EmitSEHTryStmt(const SEHTryStmt &S);
3281  void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
3282  void EnterSEHTryStmt(const SEHTryStmt &S);
3283  void ExitSEHTryStmt(const SEHTryStmt &S);
3284  void VolatilizeTryBlocks(llvm::BasicBlock *BB,
3286 
3288  llvm::Function *FinallyFunc);
3289  void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
3290  const Stmt *OutlinedStmt);
3291 
3293  const SEHExceptStmt &Except);
3294 
3296  const SEHFinallyStmt &Finally);
3297 
3299  llvm::Value *ParentFP,
3300  llvm::Value *EntryEBP);
3301  llvm::Value *EmitSEHExceptionCode();
3302  llvm::Value *EmitSEHExceptionInfo();
3303  llvm::Value *EmitSEHAbnormalTermination();
3304 
3305  /// Emit simple code for OpenMP directives in Simd-only mode.
3307 
3308  /// Scan the outlined statement for captures from the parent function. For
3309  /// each capture, mark the capture as escaped and emit a call to
3310  /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
3311  void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
3312  bool IsFilter);
3313 
3314  /// Recovers the address of a local in a parent function. ParentVar is the
3315  /// address of the variable used in the immediate parent function. It can
3316  /// either be an alloca or a call to llvm.localrecover if there are nested
3317  /// outlined functions. ParentFP is the frame pointer of the outermost parent
3318  /// frame.
3320  Address ParentVar,
3321  llvm::Value *ParentFP);
3322 
3323  void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
3324  ArrayRef<const Attr *> Attrs = None);
3325 
3326  /// Controls insertion of cancellation exit blocks in worksharing constructs.
3328  CodeGenFunction &CGF;
3329 
3330  public:
3332  bool HasCancel)
3333  : CGF(CGF) {
3334  CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
3335  }
3336  ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
3337  };
3338 
3339  /// Returns calculated size of the specified type.
3340  llvm::Value *getTypeSize(QualType Ty);
3342  llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
3343  llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
3345  llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S,
3346  SourceLocation Loc);
3348  SmallVectorImpl<llvm::Value *> &CapturedVars);
3349  void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
3350  SourceLocation Loc);
3351  /// Perform element by element copying of arrays with type \a
3352  /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
3353  /// generated by \a CopyGen.
3354  ///
3355  /// \param DestAddr Address of the destination array.
3356  /// \param SrcAddr Address of the source array.
3357  /// \param OriginalType Type of destination and source arrays.
3358  /// \param CopyGen Copying procedure that copies value of single array element
3359  /// to another single array element.
3361  Address DestAddr, Address SrcAddr, QualType OriginalType,
3362  const llvm::function_ref<void(Address, Address)> CopyGen);
3363  /// Emit proper copying of data from one variable to another.
3364  ///
3365  /// \param OriginalType Original type of the copied variables.
3366  /// \param DestAddr Destination address.
3367  /// \param SrcAddr Source address.
3368  /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
3369  /// type of the base array element).
3370  /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
3371  /// the base array element).
3372  /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
3373  /// DestVD.
3374  void EmitOMPCopy(QualType OriginalType,
3375  Address DestAddr, Address SrcAddr,
3376  const VarDecl *DestVD, const VarDecl *SrcVD,
3377  const Expr *Copy);
3378  /// Emit atomic update code for constructs: \a X = \a X \a BO \a E or
3379  /// \a X = \a E \a BO \a E.
3380  ///
3381  /// \param X Value to be updated.
3382  /// \param E Update value.
3383  /// \param BO Binary operation for update operation.
3384  /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
3385  /// expression, false otherwise.
3386  /// \param AO Atomic ordering of the generated atomic instructions.
3387  /// \param CommonGen Code generator for complex expressions that cannot be
3388  /// expressed through atomicrmw instruction.
3389  /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
3390  /// generated, <false, RValue::get(nullptr)> otherwise.
3391  std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
3392  LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3393  llvm::AtomicOrdering AO, SourceLocation Loc,
3394  const llvm::function_ref<RValue(RValue)> CommonGen);
3396  OMPPrivateScope &PrivateScope);
3398  OMPPrivateScope &PrivateScope);
3400  const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope,
3401  const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
3403  const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope,
3404  const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
3405  /// Emit code for copyin clause in \a D directive. The next code is
3406  /// generated at the start of outlined functions for directives:
3407  /// \code
3408  /// threadprivate_var1 = master_threadprivate_var1;
3409  /// operator=(threadprivate_var2, master_threadprivate_var2);
3410  /// ...
3411  /// __kmpc_barrier(&loc, global_tid);
3412  /// \endcode
3413  ///
3414  /// \param D OpenMP directive possibly with 'copyin' clause(s).
3415  /// \returns true if at least one copyin variable is found, false otherwise.
3417  /// Emit initial code for lastprivate variables. If some variable is
3418  /// not also firstprivate, then the default initialization is used. Otherwise
3419  /// initialization of this variable is performed by EmitOMPFirstprivateClause
3420  /// method.
3421  ///
3422  /// \param D Directive that may have 'lastprivate' directives.
3423  /// \param PrivateScope Private scope for capturing lastprivate variables for
3424  /// proper codegen in internal captured statement.
3425  ///
3426  /// \returns true if there is at least one lastprivate variable, false
3427  /// otherwise.
3429  OMPPrivateScope &PrivateScope);
3430  /// Emit final copying of lastprivate values to original variables at
3431  /// the end of the worksharing or simd directive.
3432  ///
3433  /// \param D Directive that has at least one 'lastprivate' directives.
3434  /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
3435  /// it is the last iteration of the loop code in associated directive, or to
3436  /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
3438  bool NoFinals,
3439  llvm::Value *IsLastIterCond = nullptr);
3440  /// Emit initial code for linear clauses.
3441  void EmitOMPLinearClause(const OMPLoopDirective &D,
3442  CodeGenFunction::OMPPrivateScope &PrivateScope);
3443  /// Emit final code for linear clauses.
3444  /// \param CondGen Optional conditional code for final part of codegen for
3445  /// linear clause.
3447  const OMPLoopDirective &D,
3448  const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
3449  /// Emit initial code for reduction variables. Creates reduction copies
3450  /// and initializes them with the values according to OpenMP standard.
3451  ///
3452  /// \param D Directive (possibly) with the 'reduction' clause.
3453  /// \param PrivateScope Private scope for capturing reduction variables for
3454  /// proper codegen in internal captured statement.
3455  ///
3457  OMPPrivateScope &PrivateScope,
3458  bool ForInscan = false);
3459  /// Emit final update of reduction values to original variables at
3460  /// the end of the directive.
3461  ///
3462  /// \param D Directive that has at least one 'reduction' directives.
3463  /// \param ReductionKind The kind of reduction to perform.
3465  const OpenMPDirectiveKind ReductionKind);
3466  /// Emit initial code for linear variables. Creates private copies
3467  /// and initializes them with the values according to OpenMP standard.
3468  ///
3469  /// \param D Directive (possibly) with the 'linear' clause.
3470  /// \return true if at least one linear variable is found that should be
3471  /// initialized with the value of the original variable, false otherwise.
3473 
3474  typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
3475  llvm::Function * /*OutlinedFn*/,
3476  const OMPTaskDataTy & /*Data*/)>
3479  const OpenMPDirectiveKind CapturedRegion,
3480  const RegionCodeGenTy &BodyGen,
3481  const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
3487  unsigned NumberOfTargetItems = 0;
3488  explicit OMPTargetDataInfo() = default;
3491  unsigned NumberOfTargetItems)
3495  };
3497  const RegionCodeGenTy &BodyGen,
3498  OMPTargetDataInfo &InputInfo);
3500  OMPTaskDataTy &Data,
3501  CodeGenFunction &CGF,
3502  const CapturedStmt *CS,
3503  OMPPrivateScope &Scope);
3504  void EmitOMPMetaDirective(const OMPMetaDirective &S);
3506  void EmitOMPSimdDirective(const OMPSimdDirective &S);
3507  void EmitOMPTileDirective(const OMPTileDirective &S);
3509  void EmitOMPForDirective(const OMPForDirective &S);
3521  void EmitOMPTaskDirective(const OMPTaskDirective &S);
3528  void EmitOMPScanDirective(const OMPScanDirective &S);
3537  void
3540  void
3547  void
3563  void
3580 
3581  /// Emit device code for the target directive.
3583  StringRef ParentName,
3584  const OMPTargetDirective &S);
3585  static void
3586  EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
3587  const OMPTargetParallelDirective &S);
3588  /// Emit device code for the target parallel for directive.
3590  CodeGenModule &CGM, StringRef ParentName,
3592  /// Emit device code for the target parallel for simd directive.
3594  CodeGenModule &CGM, StringRef ParentName,
3596  /// Emit device code for the target teams directive.
3597  static void
3598  EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
3599  const OMPTargetTeamsDirective &S);
3600  /// Emit device code for the target teams distribute directive.
3602  CodeGenModule &CGM, StringRef ParentName,
3604  /// Emit device code for the target teams distribute simd directive.
3606  CodeGenModule &CGM, StringRef ParentName,
3608  /// Emit device code for the target simd directive.
3610  StringRef ParentName,
3611  const OMPTargetSimdDirective &S);
3612  /// Emit device code for the target teams distribute parallel for simd
3613  /// directive.
3615  CodeGenModule &CGM, StringRef ParentName,
3617 
3619  CodeGenModule &CGM, StringRef ParentName,
3621 
3622  /// Emit the Stmt \p S and return its topmost canonical loop, if any.
3623  /// TODO: The \p Depth paramter is not yet implemented and must be 1. In the
3624  /// future it is meant to be the number of loops expected in the loop nests
3625  /// (usually specified by the "collapse" clause) that are collapsed to a
3626  /// single loop by this function.
3627  llvm::CanonicalLoopInfo *EmitOMPCollapsedCanonicalLoopNest(const Stmt *S,
3628  int Depth);
3629 
3630  /// Emit an OMPCanonicalLoop using the OpenMPIRBuilder.
3631  void EmitOMPCanonicalLoop(const OMPCanonicalLoop *S);
3632 
3633  /// Emit inner loop of the worksharing/simd construct.
3634  ///
3635  /// \param S Directive, for which the inner loop must be emitted.
3636  /// \param RequiresCleanup true, if directive has some associated private
3637  /// variables.
3638  /// \param LoopCond Bollean condition for loop continuation.
3639  /// \param IncExpr Increment expression for loop control variable.
3640  /// \param BodyGen Generator for the inner body of the inner loop.
3641  /// \param PostIncGen Genrator for post-increment code (required for ordered
3642  /// loop directvies).
3643  void EmitOMPInnerLoop(
3644  const OMPExecutableDirective &S, bool RequiresCleanup,
3645  const Expr *LoopCond, const Expr *IncExpr,
3646  const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
3647  const llvm::function_ref<void(CodeGenFunction &)> PostIncGen);
3648 
3650  /// Emit initial code for loop counters of loop-based directives.
3652  OMPPrivateScope &LoopScope);
3653 
3654  /// Helper for the OpenMP loop directives.
3655  void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
3656 
3657  /// Emit code for the worksharing loop-based directive.
3658  /// \return true, if this construct has any lastprivate clause, false -
3659  /// otherwise.
3660  bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB,
3661  const CodeGenLoopBoundsTy &CodeGenLoopBounds,
3662  const CodeGenDispatchBoundsTy &CGDispatchBounds);
3663 
3664  /// Emit code for the distribute loop-based directive.
3666  const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
3667 
3668  /// Helpers for the OpenMP loop directives.
3669  void EmitOMPSimdInit(const OMPLoopDirective &D);
3670  void EmitOMPSimdFinal(
3671  const OMPLoopDirective &D,
3672  const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
3673 
3674  /// Emits the lvalue for the expression with possibly captured variable.
3675  LValue EmitOMPSharedLValue(const Expr *E);
3676 
3677 private:
3678  /// Helpers for blocks.
3679  llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
3680 
3681  /// struct with the values to be passed to the OpenMP loop-related functions
3682  struct OMPLoopArguments {
3683  /// loop lower bound
3684  Address LB = Address::invalid();
3685  /// loop upper bound
3686  Address UB = Address::invalid();
3687  /// loop stride
3688  Address ST = Address::invalid();
3689  /// isLastIteration argument for runtime functions
3690  Address IL = Address::invalid();
3691  /// Chunk value generated by sema
3692  llvm::Value *Chunk = nullptr;
3693  /// EnsureUpperBound
3694  Expr *EUB = nullptr;
3695  /// IncrementExpression
3696  Expr *IncExpr = nullptr;
3697  /// Loop initialization
3698  Expr *Init = nullptr;
3699  /// Loop exit condition
3700  Expr *Cond = nullptr;
3701  /// Update of LB after a whole chunk has been executed
3702  Expr *NextLB = nullptr;
3703  /// Update of UB after a whole chunk has been executed
3704  Expr *NextUB = nullptr;
3705  OMPLoopArguments() = default;
3706  OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
3707  llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
3708  Expr *IncExpr = nullptr, Expr *Init = nullptr,
3709  Expr *Cond = nullptr, Expr *NextLB = nullptr,
3710  Expr *NextUB = nullptr)
3711  : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
3712  IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
3713  NextUB(NextUB) {}
3714  };
3715  void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
3716  const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
3717  const OMPLoopArguments &LoopArgs,
3718  const CodeGenLoopTy &CodeGenLoop,
3719  const CodeGenOrderedTy &CodeGenOrdered);
3720  void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
3721  bool IsMonotonic, const OMPLoopDirective &S,
3722  OMPPrivateScope &LoopScope, bool Ordered,
3723  const OMPLoopArguments &LoopArgs,
3724  const CodeGenDispatchBoundsTy &CGDispatchBounds);
3725  void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
3726  const OMPLoopDirective &S,
3727  OMPPrivateScope &LoopScope,
3728  const OMPLoopArguments &LoopArgs,
3729  const CodeGenLoopTy &CodeGenLoopContent);
3730  /// Emit code for sections directive.
3731  void EmitSections(const OMPExecutableDirective &S);
3732 
3733 public:
3734 
3735  //===--------------------------------------------------------------------===//
3736  // LValue Expression Emission
3737  //===--------------------------------------------------------------------===//
3738 
3739  /// Create a check that a scalar RValue is non-null.
3740  llvm::Value *EmitNonNullRValueCheck(RValue RV, QualType T);
3741 
3742  /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
3743  RValue GetUndefRValue(QualType Ty);
3744 
3745  /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
3746  /// and issue an ErrorUnsupported style diagnostic (using the
3747  /// provided Name).
3748  RValue EmitUnsupportedRValue(const Expr *E,
3749  const char *Name);
3750 
3751  /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
3752  /// an ErrorUnsupported style diagnostic (using the provided Name).
3753  LValue EmitUnsupportedLValue(const Expr *E,
3754  const char *Name);
3755 
3756  /// EmitLValue - Emit code to compute a designator that specifies the location
3757  /// of the expression.
3758  ///
3759  /// This can return one of two things: a simple address or a bitfield
3760  /// reference. In either case, the LLVM Value* in the LValue structure is
3761  /// guaranteed to be an LLVM pointer type.
3762  ///
3763  /// If this returns a bitfield reference, nothing about the pointee type of
3764  /// the LLVM value is known: For example, it may not be a pointer to an
3765  /// integer.
3766  ///
3767  /// If this returns a normal address, and if the lvalue's C type is fixed
3768  /// size, this method guarantees that the returned pointer type will point to
3769  /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
3770  /// variable length type, this is not possible.
3771  ///
3772  LValue EmitLValue(const Expr *E);
3773 
3774  /// Same as EmitLValue but additionally we generate checking code to
3775  /// guard against undefined behavior. This is only suitable when we know
3776  /// that the address will be used to access the object.
3777  LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
3778 
3779  RValue convertTempToRValue(Address addr, QualType type,
3780  SourceLocation Loc);
3781 
3782  void EmitAtomicInit(Expr *E, LValue lvalue);
3783 
3784  bool LValueIsSuitableForInlineAtomic(LValue Src);
3785 
3786  RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
3787  AggValueSlot Slot = AggValueSlot::ignored());
3788 
3789  RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
3790  llvm::AtomicOrdering AO, bool IsVolatile = false,
3791  AggValueSlot slot = AggValueSlot::ignored());
3792 
3793  void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
3794 
3795  void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
3796  bool IsVolatile, bool isInit);
3797 
3798  std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
3799  LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
3800  llvm::AtomicOrdering Success =
3801  llvm::AtomicOrdering::SequentiallyConsistent,
3802  llvm::AtomicOrdering Failure =
3803  llvm::AtomicOrdering::SequentiallyConsistent,
3804  bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
3805 
3806  void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
3807  const llvm::function_ref<RValue(RValue)> &UpdateOp,
3808  bool IsVolatile);
3809 
3810  /// EmitToMemory - Change a scalar value from its value
3811  /// representation to its in-memory representation.
3812  llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
3813 
3814  /// EmitFromMemory - Change a scalar value from its memory
3815  /// representation to its value representation.
3816  llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
3817 
3818  /// Check if the scalar \p Value is within the valid range for the given
3819  /// type \p Ty.
3820  ///
3821  /// Returns true if a check is needed (even if the range is unknown).
3822  bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
3823  SourceLocation Loc);
3824 
3825  /// EmitLoadOfScalar - Load a scalar value from an address, taking
3826  /// care to appropriately convert from the memory representation to
3827  /// the LLVM value representation.
3828  llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
3829  SourceLocation Loc,
3831  bool isNontemporal = false) {
3832  return EmitLoadOfScalar(Addr, Volatile, Ty, Loc, LValueBaseInfo(Source),
3833  CGM.getTBAAAccessInfo(Ty), isNontemporal);
3834  }
3835 
3836  llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
3837  SourceLocation Loc, LValueBaseInfo BaseInfo,
3838  TBAAAccessInfo TBAAInfo,
3839  bool isNontemporal = false);
3840 
3841  /// EmitLoadOfScalar - Load a scalar value from an address, taking
3842  /// care to appropriately convert from the memory representation to
3843  /// the LLVM value representation. The l-value must be a simple
3844  /// l-value.
3845  llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
3846 
3847  /// EmitStoreOfScalar - Store a scalar value to an address, taking
3848  /// care to appropriately convert from the memory representation to
3849  /// the LLVM value representation.
3850  void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3851  bool Volatile, QualType Ty,
3853  bool isInit = false, bool isNontemporal = false) {
3854  EmitStoreOfScalar(Value, Addr, Volatile, Ty, LValueBaseInfo(Source),
3855  CGM.getTBAAAccessInfo(Ty), isInit, isNontemporal);
3856  }
3857 
3858  void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3859  bool Volatile, QualType Ty,
3860  LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo,
3861  bool isInit = false, bool isNontemporal = false);
3862 
3863  /// EmitStoreOfScalar - Store a scalar value to an address, taking
3864  /// care to appropriately convert from the memory representation to
3865  /// the LLVM value representation. The l-value must be a simple
3866  /// l-value. The isInit flag indicates whether this is an initialization.
3867  /// If so, atomic qualifiers are ignored and the store is always non-atomic.
3868  void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
3869 
3870  /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
3871  /// this method emits the address of the lvalue, then loads the result as an
3872  /// rvalue, returning the rvalue.
3877 
3878  /// EmitStoreThroughLValue - Store the specified rvalue into the specified
3879  /// lvalue, where both are guaranteed to the have the same type, and that type
3880  /// is 'Ty'.
3881  void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
3884 
3885  /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
3886  /// as EmitStoreThroughLValue.
3887  ///
3888  /// \param Result [out] - If non-null, this will be set to a Value* for the
3889  /// bit-field contents after the store, appropriate for use as the result of
3890  /// an assignment to the bit-field.
3892  llvm::Value **Result=nullptr);
3893 
3894  /// Emit an l-value for an assignment (simple or compound) of complex type.
3898  llvm::Value *&Result);
3899 
3900  // Note: only available for agg return types
3903  // Note: only available for agg return types
3905  // Note: only available for agg return types
3913  bool Accessed = false);
3916  bool IsLowerBound = true);
3918  LValue EmitMemberExpr(const MemberExpr *E);
3924  LValue EmitCastLValue(const CastExpr *E);
3927 
3929 
3931 
3932  Address EmitArrayToPointerDecay(const Expr *Array,
3933  LValueBaseInfo *BaseInfo = nullptr,
3934  TBAAAccessInfo *TBAAInfo = nullptr);
3935 
3937  llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
3938  ConstantEmission(llvm::Constant *C, bool isReference)
3939  : ValueAndIsReference(C, isReference) {}
3940  public:
3942  static ConstantEmission forReference(llvm::Constant *C) {
3943  return ConstantEmission(C, true);
3944  }
3945  static ConstantEmission forValue(llvm::Constant *C) {
3946  return ConstantEmission(C, false);
3947  }
3948 
3949  explicit operator bool() const {
3950  return ValueAndIsReference.getOpaqueValue() != nullptr;
3951  }
3952 
3953  bool isReference() const { return ValueAndIsReference.getInt(); }
3955  assert(isReference());
3956  return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
3957  refExpr->getType());
3958  }
3959 
3960  llvm::Constant *getValue() const {
3961  assert(!isReference());
3962  return ValueAndIsReference.getPointer();
3963  }
3964  };
3965 
3966  ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
3967  ConstantEmission tryEmitAsConstant(const MemberExpr *ME);
3968  llvm::Value *emitScalarConstant(const ConstantEmission &Constant, Expr *E);
3969 
3973 
3974  llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
3975  const ObjCIvarDecl *Ivar);
3978 
3979  /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
3980  /// if the Field is a reference, this will return the address of the reference
3981  /// and not the address of the value stored in the reference.
3983  const FieldDecl* Field);
3984 
3986  llvm::Value* Base, const ObjCIvarDecl *Ivar,
3987  unsigned CVRQualifiers);
3988 
3993 
3999  void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
4000 
4001  //===--------------------------------------------------------------------===//
4002  // Scalar Expression Emission
4003  //===--------------------------------------------------------------------===//
4004 
4005  /// EmitCall - Generate a call of the given function, expecting the given
4006  /// result type, and using the given argument list which specifies both the
4007  /// LLVM arguments and the types they were derived from.
4008  RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
4010  llvm::CallBase **callOrInvoke, bool IsMustTail,
4011  SourceLocation Loc);
4012  RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
4014  llvm::CallBase **callOrInvoke = nullptr,
4015  bool IsMustTail = false) {
4016  return EmitCall(CallInfo, Callee, ReturnValue, Args, callOrInvoke,
4017  IsMustTail, SourceLocation());
4018  }
4019  RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
4020  ReturnValueSlot ReturnValue, llvm::Value *Chain = nullptr);
4021  RValue EmitCallExpr(const CallExpr *E,
4024  CGCallee EmitCallee(const Expr *E);
4025 
4026  void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
4027  void checkTargetFeatures(SourceLocation Loc, const FunctionDecl *TargetDecl);
4028 
4029  llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
4030  const Twine &name = "");
4031  llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
4033  const Twine &name = "");
4034  llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4035  const Twine &name = "");
4036  llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4038  const Twine &name = "");
4039 
4041  getBundlesForFunclet(llvm::Value *Callee);
4042 
4043  llvm::CallBase *EmitCallOrInvoke(llvm::FunctionCallee Callee,
4045  const Twine &Name = "");
4046  llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4048  const Twine &name = "");
4049  llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4050  const Twine &name = "");
4051  void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4053 
4055  NestedNameSpecifier *Qual,
4056  llvm::Type *Ty);
4057 
4059  CXXDtorType Type,
4060  const CXXRecordDecl *RD);
4061 
4062  // Return the copy constructor name with the prefix "__copy_constructor_"
4063  // removed.
4065  CharUnits Alignment,
4066  bool IsVolatile,
4067  ASTContext &Ctx);
4068 
4069  // Return the destructor name with the prefix "__destructor_" removed.
4071  CharUnits Alignment,
4072  bool IsVolatile,
4073  ASTContext &Ctx);
4074 
4075  // These functions emit calls to the special functions of non-trivial C
4076  // structs.
4079  void callCStructDestructor(LValue Dst);
4080  void callCStructCopyConstructor(LValue Dst, LValue Src);
4081  void callCStructMoveConstructor(LValue Dst, LValue Src);
4084 
4085  RValue
4087  const CGCallee &Callee,
4088  ReturnValueSlot ReturnValue, llvm::Value *This,
4089  llvm::Value *ImplicitParam,
4090  QualType ImplicitParamTy, const CallExpr *E,
4091  CallArgList *RtlArgs);
4092  RValue EmitCXXDestructorCall(GlobalDecl Dtor, const CGCallee &Callee,
4093  llvm::Value *This, QualType ThisTy,
4094  llvm::Value *ImplicitParam,
4095  QualType ImplicitParamTy, const CallExpr *E);
4099  const CXXMethodDecl *MD,
4101  bool HasQualifier,
4102  NestedNameSpecifier *Qualifier,
4103  bool IsArrow, const Expr *Base);
4104  // Compute the object pointer.
4106  llvm::Value *memberPtr,
4107  const MemberPointerType *memberPtrType,
4108  LValueBaseInfo *BaseInfo = nullptr,
4109  TBAAAccessInfo *TBAAInfo = nullptr);
4112 
4114  const CXXMethodDecl *MD,
4117 
4120 
4124 
4125  RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
4127 
4128  RValue emitRotate(const CallExpr *E, bool IsRotateRight);
4129 
4130  /// Emit IR for __builtin_os_log_format.
4132 
4133  /// Emit IR for __builtin_is_aligned.
4135  /// Emit IR for __builtin_align_up/__builtin_align_down.
4136  RValue EmitBuiltinAlignTo(const CallExpr *E, bool AlignUp);
4137 
4138  llvm::Function *generateBuiltinOSLogHelperFunction(
4139  const analyze_os_log::OSLogBufferLayout &Layout,
4140  CharUnits BufferAlignment);
4141 
4143 
4144  /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
4145  /// is unhandled by the current target.
4146  llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4148 
4149  llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
4150  const llvm::CmpInst::Predicate Fp,
4151  const llvm::CmpInst::Predicate Ip,
4152  const llvm::Twine &Name = "");
4153  llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4155  llvm::Triple::ArchType Arch);
4156  llvm::Value *EmitARMMVEBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4158  llvm::Triple::ArchType Arch);
4159  llvm::Value *EmitARMCDEBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4161  llvm::Triple::ArchType Arch);
4162  llvm::Value *EmitCMSEClearRecord(llvm::Value *V, llvm::IntegerType *ITy,
4163  QualType RTy);
4164  llvm::Value *EmitCMSEClearRecord(llvm::Value *V, llvm::ArrayType *ATy,
4165  QualType RTy);
4166 
4167  llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
4168  unsigned LLVMIntrinsic,
4169  unsigned AltLLVMIntrinsic,
4170  const char *NameHint,
4171  unsigned Modifier,
4172  const CallExpr *E,
4174  Address PtrOp0, Address PtrOp1,
4175  llvm::Triple::ArchType Arch);
4176 
4177  llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
4178  unsigned Modifier, llvm::Type *ArgTy,
4179  const CallExpr *E);
4180  llvm::Value *EmitNeonCall(llvm::Function *F,
4182  const char *name,
4183  unsigned shift = 0, bool rightshift = false);
4184  llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx,
4185  const llvm::ElementCount &Count);
4186  llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
4187  llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
4188  bool negateForRightShift);
4189  llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
4190  llvm::Type *Ty, bool usgn, const char *name);
4191  llvm::Value *vectorWrapScalar16(llvm::Value *Op);
4192  /// SVEBuiltinMemEltTy - Returns the memory element type for this memory
4193  /// access builtin. Only required if it can't be inferred from the base
4194  /// pointer operand.
4195  llvm::Type *SVEBuiltinMemEltTy(const SVETypeFlags &TypeFlags);
4196 
4198  getSVEOverloadTypes(const SVETypeFlags &TypeFlags, llvm::Type *ReturnType,
4200  llvm::Type *getEltType(const SVETypeFlags &TypeFlags);
4201  llvm::ScalableVectorType *getSVEType(const SVETypeFlags &TypeFlags);
4202  llvm::ScalableVectorType *getSVEPredType(const SVETypeFlags &TypeFlags);
4203  llvm::Value *EmitSVETupleSetOrGet(const SVETypeFlags &TypeFlags,
4204  llvm::Type *ReturnType,
4206  llvm::Value *EmitSVETupleCreate(const SVETypeFlags &TypeFlags,
4207  llvm::Type *ReturnType,
4209  llvm::Value *EmitSVEAllTruePred(const SVETypeFlags &TypeFlags);
4210  llvm::Value *EmitSVEDupX(llvm::Value *Scalar);
4211  llvm::Value *EmitSVEDupX(llvm::Value *Scalar, llvm::Type *Ty);
4212  llvm::Value *EmitSVEReinterpret(llvm::Value *Val, llvm::Type *Ty);
4213  llvm::Value *EmitSVEPMull(const SVETypeFlags &TypeFlags,
4215  unsigned BuiltinID);
4216  llvm::Value *EmitSVEMovl(const SVETypeFlags &TypeFlags,
4218  unsigned BuiltinID);
4219  llvm::Value *EmitSVEPredicateCast(llvm::Value *Pred,
4220  llvm::ScalableVectorType *VTy);
4221  llvm::Value *EmitSVEGatherLoad(const SVETypeFlags &TypeFlags,
4223  unsigned IntID);
4224  llvm::Value *EmitSVEScatterStore(const SVETypeFlags &TypeFlags,
4226  unsigned IntID);
4227  llvm::Value *EmitSVEMaskedLoad(const CallExpr *, llvm::Type *ReturnTy,
4229  unsigned BuiltinID, bool IsZExtReturn);
4230  llvm::Value *EmitSVEMaskedStore(const CallExpr *,
4232  unsigned BuiltinID);
4233  llvm::Value *EmitSVEPrefetchLoad(const SVETypeFlags &TypeFlags,
4235  unsigned BuiltinID);
4236  llvm::Value *EmitSVEGatherPrefetch(const SVETypeFlags &TypeFlags,
4238  unsigned IntID);
4239  llvm::Value *EmitSVEStructLoad(const SVETypeFlags &TypeFlags,
4241  unsigned IntID);
4242  llvm::Value *EmitSVEStructStore(const SVETypeFlags &TypeFlags,
4244  unsigned IntID);
4245  llvm::Value *EmitAArch64SVEBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4246 
4247  llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4248  llvm::Triple::ArchType Arch);
4249  llvm::Value *EmitBPFBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4250 
4251  llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
4252  llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4253  llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4254  llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4255  llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4256  llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4257  llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
4258  const CallExpr *E);
4259  llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
4260  llvm::Value *EmitRISCVBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
4262  void ProcessOrderScopeAMDGCN(llvm::Value *Order, llvm::Value *Scope,
4263  llvm::AtomicOrdering &AO,
4264  llvm::SyncScope::ID &SSID);
4265 
4266  enum class MSVCIntrin;
4267  llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
4268 
4269  llvm::Value *EmitBuiltinAvailable(const VersionTuple &Version);
4270 
4271  llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
4272  llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
4273  llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
4274  llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
4275  llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
4276  llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
4277  const ObjCMethodDecl *MethodWithObjects);
4278  llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
4280  ReturnValueSlot Return = ReturnValueSlot());
4281 
4282  /// Retrieves the default cleanup kind for an ARC cleanup.
4283  /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
4285  return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
4287  }
4288 
4289  // ARC primitives.
4290  void EmitARCInitWeak(Address addr, llvm::Value *value);
4291  void EmitARCDestroyWeak(Address addr);
4292  llvm::Value *EmitARCLoadWeak(Address addr);
4293  llvm::Value *EmitARCLoadWeakRetained(Address addr);
4294  llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
4295  void emitARCCopyAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
4296  void emitARCMoveAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
4297  void EmitARCCopyWeak(Address dst, Address src);
4298  void EmitARCMoveWeak(Address dst, Address src);
4299  llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
4300  llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
4301  llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
4302  bool resultIgnored);
4303  llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
4304  bool resultIgnored);
4305  llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
4306  llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
4307  llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
4309  void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
4310  llvm::Value *EmitARCAutorelease(llvm::Value *value);
4311  llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
4312  llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
4313  llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
4314  llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
4315 
4316  llvm::Value *EmitObjCAutorelease(llvm::Value *value, llvm::Type *returnType);
4317  llvm::Value *EmitObjCRetainNonBlock(llvm::Value *value,
4318  llvm::Type *returnType);
4319  void EmitObjCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
4320 
4321  std::pair<LValue,llvm::Value*>
4323  std::pair<LValue,llvm::Value*>
4324  EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
4325  std::pair<LValue,llvm::Value*>
4326  EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
4327 
4328  llvm::Value *EmitObjCAlloc(llvm::Value *value,
4329  llvm::Type *returnType);
4330  llvm::Value *EmitObjCAllocWithZone(llvm::Value *value,
4331  llvm::Type *returnType);
4332  llvm::Value *EmitObjCAllocInit(llvm::Value *value, llvm::Type *resultType);
4333 
4334  llvm::Value *EmitObjCThrowOperand(const Expr *expr);
4335  llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
4336  llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
4337 
4338  llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
4339  llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
4340  bool allowUnsafeClaim);
4341  llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
4342  llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
4343  llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
4344 
4346 
4348 
4354 
4355  void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
4356  llvm::Value *EmitObjCAutoreleasePoolPush();
4357  llvm::Value *EmitObjCMRRAutoreleasePoolPush();
4358  void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
4359  void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
4360 
4361  /// Emits a reference binding to the passed in expression.
4363 
4364  //===--------------------------------------------------------------------===//
4365  // Expression Emission
4366  //===--------------------------------------------------------------------===//
4367 
4368  // Expressions are broken into three classes: scalar, complex, aggregate.
4369 
4370  /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
4371  /// scalar type, returning the result.
4372  llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
4373 
4374  /// Emit a conversion from the specified type to the specified destination
4375  /// type, both of which are LLVM scalar types.
4376  llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
4377  QualType DstTy, SourceLocation Loc);
4378 
4379  /// Emit a conversion from the specified complex type to the specified
4380  /// destination type, where the destination type is an LLVM scalar type.
4381  llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
4382  QualType DstTy,
4383  SourceLocation Loc);
4384 
4385  /// EmitAggExpr - Emit the computation of the specified expression
4386  /// of aggregate type. The result is computed into the given slot,
4387  /// which may be null to indicate that the value is not needed.
4388  void EmitAggExpr(const Expr *E, AggValueSlot AS);
4389 
4390  /// EmitAggExprToLValue - Emit the computation of the specified expression of
4391  /// aggregate type into a temporary LValue.
4392  LValue EmitAggExprToLValue(const Expr *E);
4393 
4394  /// Build all the stores needed to initialize an aggregate at Dest with the
4395  /// value Val.
4396  void EmitAggregateStore(llvm::Value *Val, Address Dest, bool DestIsVolatile);
4397 
4398  /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
4399  /// make sure it survives garbage collection until this point.
4400  void EmitExtendGCLifetime(llvm::Value *object);
4401 
4402  /// EmitComplexExpr - Emit the computation of the specified expression of
4403  /// complex type, returning the result.
4405  bool IgnoreReal = false,
4406  bool IgnoreImag = false);
4407 
4408  /// EmitComplexExprIntoLValue - Emit the given expression of complex
4409  /// type and place its result into the specified l-value.
4410  void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
4411 
4412  /// EmitStoreOfComplex - Store a complex number into the specified l-value.
4413  void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
4414 
4415  /// EmitLoadOfComplex - Load a complex number from the specified l-value.
4417 
4418  ComplexPairTy EmitPromotedComplexExpr(const Expr *E, QualType PromotionType);
4419  llvm::Value *EmitPromotedScalarExpr(const Expr *E, QualType PromotionType);
4420  ComplexPairTy EmitPromotedValue(ComplexPairTy result, QualType PromotionType);
4422 
4425 
4426  /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
4427  /// global variable that has already been created for it. If the initializer
4428  /// has a different type than GV does, this may free GV and return a different
4429  /// one. Otherwise it just returns GV.
4430  llvm::GlobalVariable *
4432  llvm::GlobalVariable *GV);
4433 
4434  // Emit an @llvm.invariant.start call for the given memory region.
4435  void EmitInvariantStart(llvm::Constant *Addr, CharUnits Size);
4436 
4437  /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
4438  /// variable with global storage.
4439  void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::GlobalVariable *GV,
4440  bool PerformInit);
4441 
4442  llvm::Function *createAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor,
4443  llvm::Constant *Addr);
4444 
4445  llvm::Function *createTLSAtExitStub(const VarDecl &VD,
4446  llvm::FunctionCallee Dtor,
4447  llvm::Constant *Addr,
4448  llvm::FunctionCallee &AtExit);
4449 
4450  /// Call atexit() with a function that passes the given argument to
4451  /// the given function.
4452  void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::FunctionCallee fn,
4453  llvm::Constant *addr);
4454 
4455  /// Call atexit() with function dtorStub.
4456  void registerGlobalDtorWithAtExit(llvm::Constant *dtorStub);
4457 
4458  /// Call unatexit() with function dtorStub.
4459  llvm::Value *unregisterGlobalDtorWithUnAtExit(llvm::Constant *dtorStub);
4460 
4461  /// Emit code in this function to perform a guarded variable
4462  /// initialization. Guarded initializations are used when it's not
4463  /// possible to prove that an initialization will be done exactly
4464  /// once, e.g. with a static local variable or a static data member
4465  /// of a class template.
4466  void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
4467  bool PerformInit);
4468 
4470 
4471  /// Emit a branch to select whether or not to perform guarded initialization.
4472  void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
4473  llvm::BasicBlock *InitBlock,
4474  llvm::BasicBlock *NoInitBlock,
4475  GuardKind Kind, const VarDecl *D);
4476 
4477  /// GenerateCXXGlobalInitFunc - Generates code for initializing global
4478  /// variables.
4479  void
4480  GenerateCXXGlobalInitFunc(llvm::Function *Fn,
4481  ArrayRef<llvm::Function *> CXXThreadLocals,
4483 
4484  /// GenerateCXXGlobalCleanUpFunc - Generates code for cleaning up global
4485  /// variables.
4487  llvm::Function *Fn,
4488  ArrayRef<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
4489  llvm::Constant *>>
4490  DtorsOrStermFinalizers);
4491 
4492  void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
4493  const VarDecl *D,
4494  llvm::GlobalVariable *Addr,
4495  bool PerformInit);
4496 
4497  void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
4498 
4499  void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
4500 
4501  void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
4502 
4504 
4505  //===--------------------------------------------------------------------===//
4506  // Annotations Emission
4507  //===--------------------------------------------------------------------===//
4508 
4509  /// Emit an annotation call (intrinsic).
4510  llvm::Value *EmitAnnotationCall(llvm::Function *AnnotationFn,
4511  llvm::Value *AnnotatedVal,
4512  StringRef AnnotationStr,
4513  SourceLocation Location,
4514  const AnnotateAttr *Attr);
4515 
4516  /// Emit local annotations for the local variable V, declared by D.
4517  void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
4518 
4519  /// Emit field annotations for the given field & value. Returns the
4520  /// annotation result.
4522 
4523  //===--------------------------------------------------------------------===//
4524  // Internal Helpers
4525  //===--------------------------------------------------------------------===//
4526 
4527  /// ContainsLabel - Return true if the statement contains a label in it. If
4528  /// this statement is not executed normally, it not containing a label means
4529  /// that we can just remove the code.
4530  static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
4531 
4532  /// containsBreak - Return true if the statement contains a break out of it.
4533  /// If the statement (recursively) contains a switch or loop with a break
4534  /// inside of it, this is fine.
4535  static bool containsBreak(const Stmt *S);
4536 
4537  /// Determine if the given statement might introduce a declaration into the
4538  /// current scope, by being a (possibly-labelled) DeclStmt.
4539  static bool mightAddDeclToScope(const Stmt *S);
4540 
4541  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
4542  /// to a constant, or if it does but contains a label, return false. If it
4543  /// constant folds return true and set the boolean result in Result.
4544  bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
4545  bool AllowLabels = false);
4546 
4547  /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
4548  /// to a constant, or if it does but contains a label, return false. If it
4549  /// constant folds return true and set the folded value.
4550  bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
4551  bool AllowLabels = false);
4552 
4553  /// isInstrumentedCondition - Determine whether the given condition is an
4554  /// instrumentable condition (i.e. no "&&" or "||").
4555  static bool isInstrumentedCondition(const Expr *C);
4556 
4557  /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
4558  /// increments a profile counter based on the semantics of the given logical
4559  /// operator opcode. This is used to instrument branch condition coverage
4560  /// for logical operators.
4562  llvm::BasicBlock *TrueBlock,
4563  llvm::BasicBlock *FalseBlock,
4564  uint64_t TrueCount = 0,
4566  const Expr *CntrIdx = nullptr);
4567 
4568  /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
4569  /// if statement) to the specified blocks. Based on the condition, this might
4570  /// try to simplify the codegen of the conditional based on the branch.
4571  /// TrueCount should be the number of times we expect the condition to
4572  /// evaluate to true based on PGO data.
4573  void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
4574  llvm::BasicBlock *FalseBlock, uint64_t TrueCount,
4576