Coverage Report

Created: 2022-01-22 13:19

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