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