Debian Codegraph @

clang/lib/CodeGen/CodeGenFunction.h

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