1 //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the internal per-function state used for llvm translation.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
15 #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
17 #include "CGBuilder.h"
18 #include "CGDebugInfo.h"
19 #include "CGLoopInfo.h"
21 #include "CodeGenModule.h"
22 #include "CodeGenPGO.h"
23 #include "EHScopeStack.h"
24 #include "VarBypassDetector.h"
25 #include "clang/AST/CharUnits.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/Type.h"
30 #include "clang/Basic/ABI.h"
31 #include "clang/Basic/CapturedStmt.h"
32 #include "clang/Basic/CodeGenOptions.h"
33 #include "clang/Basic/OpenMPKinds.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/MapVector.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/IR/ValueHandle.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Transforms/Utils/SanitizerStats.h"
57 class CXXDestructorDecl;
58 class CXXForRangeStmt;
62 class EnumConstantDecl;
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;
80 namespace analyze_os_log {
81 class OSLogBufferLayout;
91 class BlockByrefHelpers;
94 class BlockFieldFlags;
95 class RegionCodeGenTy;
96 class TargetCodeGenInfo;
100 /// The kind of evaluation to perform on values of a particular
101 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or
104 /// TODO: should vectors maybe be split out into their own thing?
105 enum TypeEvaluationKind {
111 #define LIST_SANITIZER_CHECKS \
112 SANITIZER_CHECK(AddOverflow, add_overflow, 0) \
113 SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \
114 SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \
115 SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \
116 SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \
117 SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \
118 SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 0) \
119 SANITIZER_CHECK(ImplicitConversion, implicit_conversion, 0) \
120 SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) \
121 SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \
122 SANITIZER_CHECK(MissingReturn, missing_return, 0) \
123 SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \
124 SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \
125 SANITIZER_CHECK(NullabilityArg, nullability_arg, 0) \
126 SANITIZER_CHECK(NullabilityReturn, nullability_return, 1) \
127 SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \
128 SANITIZER_CHECK(NonnullReturn, nonnull_return, 1) \
129 SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \
130 SANITIZER_CHECK(PointerOverflow, pointer_overflow, 0) \
131 SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \
132 SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \
133 SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \
134 SANITIZER_CHECK(AlignmentAssumption, alignment_assumption, 0) \
135 SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
137 enum SanitizerHandler {
138 #define SANITIZER_CHECK(Enum, Name, Version) Enum,
139 LIST_SANITIZER_CHECKS
140 #undef SANITIZER_CHECK
143 /// Helper class with most of the code for saving a value for a
144 /// conditional expression cleanup.
145 struct DominatingLLVMValue {
146 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
148 /// Answer whether the given value needs extra work to be saved.
149 static bool needsSaving(llvm::Value *value) {
150 // If it's not an instruction, we don't need to save.
151 if (!isa<llvm::Instruction>(value)) return false;
153 // If it's an instruction in the entry block, we don't need to save.
154 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
155 return (block != &block->getParent()->getEntryBlock());
158 static saved_type save(CodeGenFunction &CGF, llvm::Value *value);
159 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value);
162 /// A partial specialization of DominatingValue for llvm::Values that
163 /// might be llvm::Instructions.
164 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
166 static type restore(CodeGenFunction &CGF, saved_type value) {
167 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
171 /// A specialization of DominatingValue for Address.
172 template <> struct DominatingValue<Address> {
173 typedef Address type;
176 DominatingLLVMValue::saved_type SavedValue;
180 static bool needsSaving(type value) {
181 return DominatingLLVMValue::needsSaving(value.getPointer());
183 static saved_type save(CodeGenFunction &CGF, type value) {
184 return { DominatingLLVMValue::save(CGF, value.getPointer()),
185 value.getAlignment() };
187 static type restore(CodeGenFunction &CGF, saved_type value) {
188 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
193 /// A specialization of DominatingValue for RValue.
194 template <> struct DominatingValue<RValue> {
197 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
198 AggregateAddress, ComplexAddress };
203 saved_type(llvm::Value *v, Kind k, unsigned a = 0)
204 : Value(v), K(k), Align(a) {}
207 static bool needsSaving(RValue value);
208 static saved_type save(CodeGenFunction &CGF, RValue value);
209 RValue restore(CodeGenFunction &CGF);
211 // implementations in CGCleanup.cpp
214 static bool needsSaving(type value) {
215 return saved_type::needsSaving(value);
217 static saved_type save(CodeGenFunction &CGF, type value) {
218 return saved_type::save(CGF, value);
220 static type restore(CodeGenFunction &CGF, saved_type value) {
221 return value.restore(CGF);
225 /// CodeGenFunction - This class organizes the per-function state that is used
226 /// while generating LLVM code.
227 class CodeGenFunction : public CodeGenTypeCache {
228 CodeGenFunction(const CodeGenFunction &) = delete;
229 void operator=(const CodeGenFunction &) = delete;
231 friend class CGCXXABI;
233 /// A jump destination is an abstract label, branching to which may
234 /// require a jump out through normal cleanups.
236 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
237 JumpDest(llvm::BasicBlock *Block,
238 EHScopeStack::stable_iterator Depth,
240 : Block(Block), ScopeDepth(Depth), Index(Index) {}
242 bool isValid() const { return Block != nullptr; }
243 llvm::BasicBlock *getBlock() const { return Block; }
244 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
245 unsigned getDestIndex() const { return Index; }
247 // This should be used cautiously.
248 void setScopeDepth(EHScopeStack::stable_iterator depth) {
253 llvm::BasicBlock *Block;
254 EHScopeStack::stable_iterator ScopeDepth;
258 CodeGenModule &CGM; // Per-module state.
259 const TargetInfo &Target;
261 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
262 LoopInfoStack LoopStack;
265 // Stores variables for which we can't generate correct lifetime markers
267 VarBypassDetector Bypasses;
269 // CodeGen lambda for loops and support for ordered clause
270 typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
273 typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
274 const unsigned, const bool)>
277 // Codegen lambda for loop bounds in worksharing loop constructs
278 typedef llvm::function_ref<std::pair<LValue, LValue>(
279 CodeGenFunction &, const OMPExecutableDirective &S)>
282 // Codegen lambda for loop bounds in dispatch-based loop implementation
283 typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
284 CodeGenFunction &, const OMPExecutableDirective &S, Address LB,
286 CodeGenDispatchBoundsTy;
288 /// CGBuilder insert helper. This function is called after an
289 /// instruction is created using Builder.
290 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
291 llvm::BasicBlock *BB,
292 llvm::BasicBlock::iterator InsertPt) const;
294 /// CurFuncDecl - Holds the Decl for the current outermost
295 /// non-closure context.
296 const Decl *CurFuncDecl;
297 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
298 const Decl *CurCodeDecl;
299 const CGFunctionInfo *CurFnInfo;
301 llvm::Function *CurFn = nullptr;
303 // Holds coroutine data if the current function is a coroutine. We use a
304 // wrapper to manage its lifetime, so that we don't have to define CGCoroData
307 std::unique_ptr<CGCoroData> Data;
313 bool isCoroutine() const {
314 return CurCoro.Data != nullptr;
317 /// CurGD - The GlobalDecl for the current function being compiled.
320 /// PrologueCleanupDepth - The cleanup depth enclosing all the
321 /// cleanups associated with the parameters.
322 EHScopeStack::stable_iterator PrologueCleanupDepth;
324 /// ReturnBlock - Unified return block.
325 JumpDest ReturnBlock;
327 /// ReturnValue - The temporary alloca to hold the return
328 /// value. This is invalid iff the function has no return value.
329 Address ReturnValue = Address::invalid();
331 /// Return true if a label was seen in the current scope.
332 bool hasLabelBeenSeenInCurrentScope() const {
334 return CurLexicalScope->hasLabels();
335 return !LabelMap.empty();
338 /// AllocaInsertPoint - This is an instruction in the entry block before which
339 /// we prefer to insert allocas.
340 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
342 /// API for captured statement code generation.
343 class CGCapturedStmtInfo {
345 explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
346 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
347 explicit CGCapturedStmtInfo(const CapturedStmt &S,
348 CapturedRegionKind K = CR_Default)
349 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
351 RecordDecl::field_iterator Field =
352 S.getCapturedRecordDecl()->field_begin();
353 for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
355 I != E; ++I, ++Field) {
356 if (I->capturesThis())
357 CXXThisFieldDecl = *Field;
358 else if (I->capturesVariable())
359 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
360 else if (I->capturesVariableByCopy())
361 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
365 virtual ~CGCapturedStmtInfo();
367 CapturedRegionKind getKind() const { return Kind; }
369 virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
370 // Retrieve the value of the context parameter.
371 virtual llvm::Value *getContextValue() const { return ThisValue; }
373 /// Lookup the captured field decl for a variable.
374 virtual const FieldDecl *lookup(const VarDecl *VD) const {
375 return CaptureFields.lookup(VD->getCanonicalDecl());
378 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
379 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
381 static bool classof(const CGCapturedStmtInfo *) {
385 /// Emit the captured statement body.
386 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
387 CGF.incrementProfileCounter(S);
391 /// Get the name of the capture helper.
392 virtual StringRef getHelperName() const { return "__captured_stmt"; }
395 /// The kind of captured statement being generated.
396 CapturedRegionKind Kind;
398 /// Keep the map between VarDecl and FieldDecl.
399 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
401 /// The base address of the captured record, passed in as the first
402 /// argument of the parallel region function.
403 llvm::Value *ThisValue;
405 /// Captured 'this' type.
406 FieldDecl *CXXThisFieldDecl;
408 CGCapturedStmtInfo *CapturedStmtInfo = nullptr;
410 /// RAII for correct setting/restoring of CapturedStmtInfo.
411 class CGCapturedStmtRAII {
413 CodeGenFunction &CGF;
414 CGCapturedStmtInfo *PrevCapturedStmtInfo;
416 CGCapturedStmtRAII(CodeGenFunction &CGF,
417 CGCapturedStmtInfo *NewCapturedStmtInfo)
418 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
419 CGF.CapturedStmtInfo = NewCapturedStmtInfo;
421 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
424 /// An abstract representation of regular/ObjC call/message targets.
425 class AbstractCallee {
426 /// The function declaration of the callee.
427 const Decl *CalleeDecl;
430 AbstractCallee() : CalleeDecl(nullptr) {}
431 AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
432 AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
433 bool hasFunctionDecl() const {
434 return dyn_cast_or_null<FunctionDecl>(CalleeDecl);
436 const Decl *getDecl() const { return CalleeDecl; }
437 unsigned getNumParams() const {
438 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
439 return FD->getNumParams();
440 return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
442 const ParmVarDecl *getParamDecl(unsigned I) const {
443 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
444 return FD->getParamDecl(I);
445 return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
449 /// Sanitizers enabled for this function.
450 SanitizerSet SanOpts;
452 /// True if CodeGen currently emits code implementing sanitizer checks.
453 bool IsSanitizerScope = false;
455 /// RAII object to set/unset CodeGenFunction::IsSanitizerScope.
456 class SanitizerScope {
457 CodeGenFunction *CGF;
459 SanitizerScope(CodeGenFunction *CGF);
463 /// In C++, whether we are code generating a thunk. This controls whether we
464 /// should emit cleanups.
465 bool CurFuncIsThunk = false;
467 /// In ARC, whether we should autorelease the return value.
468 bool AutoreleaseResult = false;
470 /// Whether we processed a Microsoft-style asm block during CodeGen. These can
471 /// potentially set the return value.
472 bool SawAsmBlock = false;
474 const NamedDecl *CurSEHParent = nullptr;
476 /// True if the current function is an outlined SEH helper. This can be a
477 /// finally block or filter expression.
478 bool IsOutlinedSEHHelper = false;
480 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
481 llvm::Value *BlockPointer = nullptr;
483 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
484 FieldDecl *LambdaThisCaptureField = nullptr;
486 /// A mapping from NRVO variables to the flags used to indicate
487 /// when the NRVO has been applied to this variable.
488 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
490 EHScopeStack EHStack;
491 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
492 llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
494 llvm::Instruction *CurrentFuncletPad = nullptr;
496 class CallLifetimeEnd final : public EHScopeStack::Cleanup {
501 CallLifetimeEnd(Address addr, llvm::Value *size)
502 : Addr(addr.getPointer()), Size(size) {}
504 void Emit(CodeGenFunction &CGF, Flags flags) override {
505 CGF.EmitLifetimeEnd(Size, Addr);
509 /// Header for data within LifetimeExtendedCleanupStack.
510 struct LifetimeExtendedCleanupHeader {
511 /// The size of the following cleanup object.
513 /// The kind of cleanup to push: a value from the CleanupKind enumeration.
515 /// Whether this is a conditional cleanup.
516 unsigned IsConditional : 1;
518 size_t getSize() const { return Size; }
519 CleanupKind getKind() const { return (CleanupKind)Kind; }
520 bool isConditional() const { return IsConditional; }
523 /// i32s containing the indexes of the cleanup destinations.
524 Address NormalCleanupDest = Address::invalid();
526 unsigned NextCleanupDestIndex = 1;
528 /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
529 CGBlockInfo *FirstBlockInfo = nullptr;
531 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
532 llvm::BasicBlock *EHResumeBlock = nullptr;
534 /// The exception slot. All landing pads write the current exception pointer
535 /// into this alloca.
536 llvm::Value *ExceptionSlot = nullptr;
538 /// The selector slot. Under the MandatoryCleanup model, all landing pads
539 /// write the current selector value into this alloca.
540 llvm::AllocaInst *EHSelectorSlot = nullptr;
542 /// A stack of exception code slots. Entering an __except block pushes a slot
543 /// on the stack and leaving pops one. The __exception_code() intrinsic loads
544 /// a value from the top of the stack.
545 SmallVector<Address, 1> SEHCodeSlotStack;
547 /// Value returned by __exception_info intrinsic.
548 llvm::Value *SEHInfo = nullptr;
550 /// Emits a landing pad for the current EH stack.
551 llvm::BasicBlock *EmitLandingPad();
553 llvm::BasicBlock *getInvokeDestImpl();
556 typename DominatingValue<T>::saved_type saveValueInCond(T value) {
557 return DominatingValue<T>::save(*this, value);
561 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
563 SmallVector<llvm::Value*, 8> ObjCEHValueStack;
565 /// A class controlling the emission of a finally block.
567 /// Where the catchall's edge through the cleanup should go.
568 JumpDest RethrowDest;
570 /// A function to call to enter the catch.
571 llvm::Constant *BeginCatchFn;
573 /// An i1 variable indicating whether or not the @finally is
574 /// running for an exception.
575 llvm::AllocaInst *ForEHVar;
577 /// An i8* variable into which the exception pointer to rethrow
579 llvm::AllocaInst *SavedExnVar;
582 void enter(CodeGenFunction &CGF, const Stmt *Finally,
583 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
584 llvm::Constant *rethrowFn);
585 void exit(CodeGenFunction &CGF);
588 /// Returns true inside SEH __try blocks.
589 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
591 /// Returns true while emitting a cleanuppad.
592 bool isCleanupPadScope() const {
593 return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
596 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
597 /// current full-expression. Safe against the possibility that
598 /// we're currently inside a conditionally-evaluated expression.
599 template <class T, class... As>
600 void pushFullExprCleanup(CleanupKind kind, As... A) {
601 // If we're not in a conditional branch, or if none of the
602 // arguments requires saving, then use the unconditional cleanup.
603 if (!isInConditionalBranch())
604 return EHStack.pushCleanup<T>(kind, A...);
606 // Stash values in a tuple so we can guarantee the order of saves.
607 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
608 SavedTuple Saved{saveValueInCond(A)...};
610 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
611 EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
612 initFullExprCleanup();
615 /// Queue a cleanup to be pushed after finishing the current
617 template <class T, class... As>
618 void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
619 if (!isInConditionalBranch())
620 return pushCleanupAfterFullExprImpl<T>(Kind, Address::invalid(), A...);
622 Address ActiveFlag = createCleanupActiveFlag();
623 assert(!DominatingValue<Address>::needsSaving(ActiveFlag) &&
624 "cleanup active flag should never need saving");
626 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
627 SavedTuple Saved{saveValueInCond(A)...};
629 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
630 pushCleanupAfterFullExprImpl<CleanupType>(Kind, ActiveFlag, Saved);
633 template <class T, class... As>
634 void pushCleanupAfterFullExprImpl(CleanupKind Kind, Address ActiveFlag,
636 LifetimeExtendedCleanupHeader Header = {sizeof(T), Kind,
637 ActiveFlag.isValid()};
639 size_t OldSize = LifetimeExtendedCleanupStack.size();
640 LifetimeExtendedCleanupStack.resize(
641 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size +
642 (Header.IsConditional ? sizeof(ActiveFlag) : 0));
644 static_assert(sizeof(Header) % alignof(T) == 0,
645 "Cleanup will be allocated on misaligned address");
646 char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
647 new (Buffer) LifetimeExtendedCleanupHeader(Header);
648 new (Buffer + sizeof(Header)) T(A...);
649 if (Header.IsConditional)
650 new (Buffer + sizeof(Header) + sizeof(T)) Address(ActiveFlag);
653 /// Set up the last cleanup that was pushed as a conditional
654 /// full-expression cleanup.
655 void initFullExprCleanup() {
656 initFullExprCleanupWithFlag(createCleanupActiveFlag());
659 void initFullExprCleanupWithFlag(Address ActiveFlag);
660 Address createCleanupActiveFlag();
662 /// PushDestructorCleanup - Push a cleanup to call the
663 /// complete-object destructor of an object of the given type at the
664 /// given address. Does nothing if T is not a C++ class type with a
665 /// non-trivial destructor.
666 void PushDestructorCleanup(QualType T, Address Addr);
668 /// PushDestructorCleanup - Push a cleanup to call the
669 /// complete-object variant of the given destructor on the object at
670 /// the given address.
671 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, Address Addr);
673 /// PopCleanupBlock - Will pop the cleanup entry on the stack and
674 /// process all branch fixups.
675 void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
677 /// DeactivateCleanupBlock - Deactivates the given cleanup block.
678 /// The block cannot be reactivated. Pops it if it's the top of the
681 /// \param DominatingIP - An instruction which is known to
682 /// dominate the current IP (if set) and which lies along
683 /// all paths of execution between the current IP and the
684 /// the point at which the cleanup comes into scope.
685 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
686 llvm::Instruction *DominatingIP);
688 /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
689 /// Cannot be used to resurrect a deactivated cleanup.
691 /// \param DominatingIP - An instruction which is known to
692 /// dominate the current IP (if set) and which lies along
693 /// all paths of execution between the current IP and the
694 /// the point at which the cleanup comes into scope.
695 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
696 llvm::Instruction *DominatingIP);
698 /// Enters a new scope for capturing cleanups, all of which
699 /// will be executed once the scope is exited.
700 class RunCleanupsScope {
701 EHScopeStack::stable_iterator CleanupStackDepth, OldCleanupScopeDepth;
702 size_t LifetimeExtendedCleanupStackSize;
703 bool OldDidCallStackSave;
708 RunCleanupsScope(const RunCleanupsScope &) = delete;
709 void operator=(const RunCleanupsScope &) = delete;
712 CodeGenFunction& CGF;
715 /// Enter a new cleanup scope.
716 explicit RunCleanupsScope(CodeGenFunction &CGF)
717 : PerformCleanup(true), CGF(CGF)
719 CleanupStackDepth = CGF.EHStack.stable_begin();
720 LifetimeExtendedCleanupStackSize =
721 CGF.LifetimeExtendedCleanupStack.size();
722 OldDidCallStackSave = CGF.DidCallStackSave;
723 CGF.DidCallStackSave = false;
724 OldCleanupScopeDepth = CGF.CurrentCleanupScopeDepth;
725 CGF.CurrentCleanupScopeDepth = CleanupStackDepth;
728 /// Exit this cleanup scope, emitting any accumulated cleanups.
729 ~RunCleanupsScope() {
734 /// Determine whether this scope requires any cleanups.
735 bool requiresCleanups() const {
736 return CGF.EHStack.stable_begin() != CleanupStackDepth;
739 /// Force the emission of cleanups now, instead of waiting
740 /// until this object is destroyed.
741 /// \param ValuesToReload - A list of values that need to be available at
742 /// the insertion point after cleanup emission. If cleanup emission created
743 /// a shared cleanup block, these value pointers will be rewritten.
744 /// Otherwise, they not will be modified.
745 void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) {
746 assert(PerformCleanup && "Already forced cleanup");
747 CGF.DidCallStackSave = OldDidCallStackSave;
748 CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize,
750 PerformCleanup = false;
751 CGF.CurrentCleanupScopeDepth = OldCleanupScopeDepth;
755 // Cleanup stack depth of the RunCleanupsScope that was pushed most recently.
756 EHScopeStack::stable_iterator CurrentCleanupScopeDepth =
757 EHScopeStack::stable_end();
759 class LexicalScope : public RunCleanupsScope {
761 SmallVector<const LabelDecl*, 4> Labels;
762 LexicalScope *ParentScope;
764 LexicalScope(const LexicalScope &) = delete;
765 void operator=(const LexicalScope &) = delete;
768 /// Enter a new cleanup scope.
769 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
770 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
771 CGF.CurLexicalScope = this;
772 if (CGDebugInfo *DI = CGF.getDebugInfo())
773 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
776 void addLabel(const LabelDecl *label) {
777 assert(PerformCleanup && "adding label to dead scope?");
778 Labels.push_back(label);
781 /// Exit this cleanup scope, emitting any accumulated
784 if (CGDebugInfo *DI = CGF.getDebugInfo())
785 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
787 // If we should perform a cleanup, force them now. Note that
788 // this ends the cleanup scope before rescoping any labels.
789 if (PerformCleanup) {
790 ApplyDebugLocation DL(CGF, Range.getEnd());
795 /// Force the emission of cleanups now, instead of waiting
796 /// until this object is destroyed.
797 void ForceCleanup() {
798 CGF.CurLexicalScope = ParentScope;
799 RunCleanupsScope::ForceCleanup();
805 bool hasLabels() const {
806 return !Labels.empty();
809 void rescopeLabels();
812 typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
814 /// The class used to assign some variables some temporarily addresses.
816 DeclMapTy SavedLocals;
817 DeclMapTy SavedTempAddresses;
818 OMPMapVars(const OMPMapVars &) = delete;
819 void operator=(const OMPMapVars &) = delete;
822 explicit OMPMapVars() = default;
824 assert(SavedLocals.empty() && "Did not restored original addresses.");
827 /// Sets the address of the variable \p LocalVD to be \p TempAddr in
829 /// \return true if at least one variable was set already, false otherwise.
830 bool setVarAddr(CodeGenFunction &CGF, const VarDecl *LocalVD,
832 LocalVD = LocalVD->getCanonicalDecl();
833 // Only save it once.
834 if (SavedLocals.count(LocalVD)) return false;
836 // Copy the existing local entry to SavedLocals.
837 auto it = CGF.LocalDeclMap.find(LocalVD);
838 if (it != CGF.LocalDeclMap.end())
839 SavedLocals.try_emplace(LocalVD, it->second);
841 SavedLocals.try_emplace(LocalVD, Address::invalid());
843 // Generate the private entry.
844 QualType VarTy = LocalVD->getType();
845 if (VarTy->isReferenceType()) {
846 Address Temp = CGF.CreateMemTemp(VarTy);
847 CGF.Builder.CreateStore(TempAddr.getPointer(), Temp);
850 SavedTempAddresses.try_emplace(LocalVD, TempAddr);
855 /// Applies new addresses to the list of the variables.
856 /// \return true if at least one variable is using new address, false
858 bool apply(CodeGenFunction &CGF) {
859 copyInto(SavedTempAddresses, CGF.LocalDeclMap);
860 SavedTempAddresses.clear();
861 return !SavedLocals.empty();
864 /// Restores original addresses of the variables.
865 void restore(CodeGenFunction &CGF) {
866 if (!SavedLocals.empty()) {
867 copyInto(SavedLocals, CGF.LocalDeclMap);
873 /// Copy all the entries in the source map over the corresponding
874 /// entries in the destination, which must exist.
875 static void copyInto(const DeclMapTy &Src, DeclMapTy &Dest) {
876 for (auto &Pair : Src) {
877 if (!Pair.second.isValid()) {
878 Dest.erase(Pair.first);
882 auto I = Dest.find(Pair.first);
884 I->second = Pair.second;
891 /// The scope used to remap some variables as private in the OpenMP loop body
892 /// (or other captured region emitted without outlining), and to restore old
893 /// vars back on exit.
894 class OMPPrivateScope : public RunCleanupsScope {
895 OMPMapVars MappedVars;
896 OMPPrivateScope(const OMPPrivateScope &) = delete;
897 void operator=(const OMPPrivateScope &) = delete;
900 /// Enter a new OpenMP private scope.
901 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
903 /// Registers \p LocalVD variable as a private and apply \p PrivateGen
904 /// function for it to generate corresponding private variable. \p
905 /// PrivateGen returns an address of the generated private variable.
906 /// \return true if the variable is registered as private, false if it has
907 /// been privatized already.
908 bool addPrivate(const VarDecl *LocalVD,
909 const llvm::function_ref<Address()> PrivateGen) {
910 assert(PerformCleanup && "adding private to dead scope");
911 return MappedVars.setVarAddr(CGF, LocalVD, PrivateGen());
914 /// Privatizes local variables previously registered as private.
915 /// Registration is separate from the actual privatization to allow
916 /// initializers use values of the original variables, not the private one.
917 /// This is important, for example, if the private variable is a class
918 /// variable initialized by a constructor that references other private
919 /// variables. But at initialization original variables must be used, not
921 /// \return true if at least one variable was privatized, false otherwise.
922 bool Privatize() { return MappedVars.apply(CGF); }
924 void ForceCleanup() {
925 RunCleanupsScope::ForceCleanup();
926 MappedVars.restore(CGF);
929 /// Exit scope - all the mapped variables are restored.
935 /// Checks if the global variable is captured in current function.
936 bool isGlobalVarCaptured(const VarDecl *VD) const {
937 VD = VD->getCanonicalDecl();
938 return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
942 /// Takes the old cleanup stack size and emits the cleanup blocks
943 /// that have been added.
945 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
946 std::initializer_list<llvm::Value **> ValuesToReload = {});
948 /// Takes the old cleanup stack size and emits the cleanup blocks
949 /// that have been added, then adds all lifetime-extended cleanups from
950 /// the given position to the stack.
952 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
953 size_t OldLifetimeExtendedStackSize,
954 std::initializer_list<llvm::Value **> ValuesToReload = {});
956 void ResolveBranchFixups(llvm::BasicBlock *Target);
958 /// The given basic block lies in the current EH scope, but may be a
959 /// target of a potentially scope-crossing jump; get a stable handle
960 /// to which we can perform this jump later.
961 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
962 return JumpDest(Target,
963 EHStack.getInnermostNormalCleanup(),
964 NextCleanupDestIndex++);
967 /// The given basic block lies in the current EH scope, but may be a
968 /// target of a potentially scope-crossing jump; get a stable handle
969 /// to which we can perform this jump later.
970 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
971 return getJumpDestInCurrentScope(createBasicBlock(Name));
974 /// EmitBranchThroughCleanup - Emit a branch from the current insert
975 /// block through the normal cleanup handling code (if any) and then
977 void EmitBranchThroughCleanup(JumpDest Dest);
979 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
980 /// specified destination obviously has no cleanups to run. 'false' is always
981 /// a conservatively correct answer for this method.
982 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
984 /// popCatchScope - Pops the catch scope at the top of the EHScope
985 /// stack, emitting any required code (other than the catch handlers
987 void popCatchScope();
989 llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
990 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
992 getFuncletEHDispatchBlock(EHScopeStack::stable_iterator scope);
994 /// An object to manage conditionally-evaluated expressions.
995 class ConditionalEvaluation {
996 llvm::BasicBlock *StartBB;
999 ConditionalEvaluation(CodeGenFunction &CGF)
1000 : StartBB(CGF.Builder.GetInsertBlock()) {}
1002 void begin(CodeGenFunction &CGF) {
1003 assert(CGF.OutermostConditional != this);
1004 if (!CGF.OutermostConditional)
1005 CGF.OutermostConditional = this;
1008 void end(CodeGenFunction &CGF) {
1009 assert(CGF.OutermostConditional != nullptr);
1010 if (CGF.OutermostConditional == this)
1011 CGF.OutermostConditional = nullptr;
1014 /// Returns a block which will be executed prior to each
1015 /// evaluation of the conditional code.
1016 llvm::BasicBlock *getStartingBlock() const {
1021 /// isInConditionalBranch - Return true if we're currently emitting
1022 /// one branch or the other of a conditional expression.
1023 bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
1025 void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
1026 assert(isInConditionalBranch());
1027 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
1028 auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
1029 store->setAlignment(addr.getAlignment().getQuantity());
1032 /// An RAII object to record that we're evaluating a statement
1034 class StmtExprEvaluation {
1035 CodeGenFunction &CGF;
1037 /// We have to save the outermost conditional: cleanups in a
1038 /// statement expression aren't conditional just because the
1040 ConditionalEvaluation *SavedOutermostConditional;
1043 StmtExprEvaluation(CodeGenFunction &CGF)
1044 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
1045 CGF.OutermostConditional = nullptr;
1048 ~StmtExprEvaluation() {
1049 CGF.OutermostConditional = SavedOutermostConditional;
1050 CGF.EnsureInsertPoint();
1054 /// An object which temporarily prevents a value from being
1055 /// destroyed by aggressive peephole optimizations that assume that
1056 /// all uses of a value have been realized in the IR.
1057 class PeepholeProtection {
1058 llvm::Instruction *Inst;
1059 friend class CodeGenFunction;
1062 PeepholeProtection() : Inst(nullptr) {}
1065 /// A non-RAII class containing all the information about a bound
1066 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
1067 /// this which makes individual mappings very simple; using this
1068 /// class directly is useful when you have a variable number of
1069 /// opaque values or don't want the RAII functionality for some
1071 class OpaqueValueMappingData {
1072 const OpaqueValueExpr *OpaqueValue;
1074 CodeGenFunction::PeepholeProtection Protection;
1076 OpaqueValueMappingData(const OpaqueValueExpr *ov,
1078 : OpaqueValue(ov), BoundLValue(boundLValue) {}
1080 OpaqueValueMappingData() : OpaqueValue(nullptr) {}
1082 static bool shouldBindAsLValue(const Expr *expr) {
1083 // gl-values should be bound as l-values for obvious reasons.
1084 // Records should be bound as l-values because IR generation
1085 // always keeps them in memory. Expressions of function type
1086 // act exactly like l-values but are formally required to be
1088 return expr->isGLValue() ||
1089 expr->getType()->isFunctionType() ||
1090 hasAggregateEvaluationKind(expr->getType());
1093 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
1094 const OpaqueValueExpr *ov,
1096 if (shouldBindAsLValue(ov))
1097 return bind(CGF, ov, CGF.EmitLValue(e));
1098 return bind(CGF, ov, CGF.EmitAnyExpr(e));
1101 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
1102 const OpaqueValueExpr *ov,
1104 assert(shouldBindAsLValue(ov));
1105 CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
1106 return OpaqueValueMappingData(ov, true);
1109 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
1110 const OpaqueValueExpr *ov,
1112 assert(!shouldBindAsLValue(ov));
1113 CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
1115 OpaqueValueMappingData data(ov, false);
1117 // Work around an extremely aggressive peephole optimization in
1118 // EmitScalarConversion which assumes that all other uses of a
1119 // value are extant.
1120 data.Protection = CGF.protectFromPeepholes(rv);
1125 bool isValid() const { return OpaqueValue != nullptr; }
1126 void clear() { OpaqueValue = nullptr; }
1128 void unbind(CodeGenFunction &CGF) {
1129 assert(OpaqueValue && "no data to unbind!");
1132 CGF.OpaqueLValues.erase(OpaqueValue);
1134 CGF.OpaqueRValues.erase(OpaqueValue);
1135 CGF.unprotectFromPeepholes(Protection);
1140 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
1141 class OpaqueValueMapping {
1142 CodeGenFunction &CGF;
1143 OpaqueValueMappingData Data;
1146 static bool shouldBindAsLValue(const Expr *expr) {
1147 return OpaqueValueMappingData::shouldBindAsLValue(expr);
1150 /// Build the opaque value mapping for the given conditional
1151 /// operator if it's the GNU ?: extension. This is a common
1152 /// enough pattern that the convenience operator is really
1155 OpaqueValueMapping(CodeGenFunction &CGF,
1156 const AbstractConditionalOperator *op) : CGF(CGF) {
1157 if (isa<ConditionalOperator>(op))
1158 // Leave Data empty.
1161 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
1162 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
1166 /// Build the opaque value mapping for an OpaqueValueExpr whose source
1167 /// expression is set to the expression the OVE represents.
1168 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
1171 assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
1172 "for OVE with no source expression");
1173 Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
1177 OpaqueValueMapping(CodeGenFunction &CGF,
1178 const OpaqueValueExpr *opaqueValue,
1180 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
1183 OpaqueValueMapping(CodeGenFunction &CGF,
1184 const OpaqueValueExpr *opaqueValue,
1186 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
1194 ~OpaqueValueMapping() {
1195 if (Data.isValid()) Data.unbind(CGF);
1200 CGDebugInfo *DebugInfo;
1201 /// Used to create unique names for artificial VLA size debug info variables.
1202 unsigned VLAExprCounter = 0;
1203 bool DisableDebugInfo = false;
1205 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
1206 /// calling llvm.stacksave for multiple VLAs in the same scope.
1207 bool DidCallStackSave = false;
1209 /// IndirectBranch - The first time an indirect goto is seen we create a block
1210 /// with an indirect branch. Every time we see the address of a label taken,
1211 /// we add the label to the indirect goto. Every subsequent indirect goto is
1212 /// codegen'd as a jump to the IndirectBranch's basic block.
1213 llvm::IndirectBrInst *IndirectBranch = nullptr;
1215 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
1217 DeclMapTy LocalDeclMap;
1219 // Keep track of the cleanups for callee-destructed parameters pushed to the
1220 // cleanup stack so that they can be deactivated later.
1221 llvm::DenseMap<const ParmVarDecl *, EHScopeStack::stable_iterator>
1222 CalleeDestructedParamCleanups;
1224 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
1225 /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
1227 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
1230 /// Track escaped local variables with auto storage. Used during SEH
1231 /// outlining to produce a call to llvm.localescape.
1232 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
1234 /// LabelMap - This keeps track of the LLVM basic block for each C label.
1235 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
1237 // BreakContinueStack - This keeps track of where break and continue
1238 // statements should jump to.
1239 struct BreakContinue {
1240 BreakContinue(JumpDest Break, JumpDest Continue)
1241 : BreakBlock(Break), ContinueBlock(Continue) {}
1243 JumpDest BreakBlock;
1244 JumpDest ContinueBlock;
1246 SmallVector<BreakContinue, 8> BreakContinueStack;
1248 /// Handles cancellation exit points in OpenMP-related constructs.
1249 class OpenMPCancelExitStack {
1250 /// Tracks cancellation exit point and join point for cancel-related exit
1251 /// and normal exit.
1253 CancelExit() = default;
1254 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
1256 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
1257 OpenMPDirectiveKind Kind = OMPD_unknown;
1258 /// true if the exit block has been emitted already by the special
1259 /// emitExit() call, false if the default codegen is used.
1260 bool HasBeenEmitted = false;
1265 SmallVector<CancelExit, 8> Stack;
1268 OpenMPCancelExitStack() : Stack(1) {}
1269 ~OpenMPCancelExitStack() = default;
1270 /// Fetches the exit block for the current OpenMP construct.
1271 JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
1272 /// Emits exit block with special codegen procedure specific for the related
1273 /// OpenMP construct + emits code for normal construct cleanup.
1274 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1275 const llvm::function_ref<void(CodeGenFunction &)> CodeGen) {
1276 if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
1277 assert(CGF.getOMPCancelDestination(Kind).isValid());
1278 assert(CGF.HaveInsertPoint());
1279 assert(!Stack.back().HasBeenEmitted);
1280 auto IP = CGF.Builder.saveAndClearIP();
1281 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1283 CGF.EmitBranch(Stack.back().ContBlock.getBlock());
1284 CGF.Builder.restoreIP(IP);
1285 Stack.back().HasBeenEmitted = true;
1289 /// Enter the cancel supporting \a Kind construct.
1290 /// \param Kind OpenMP directive that supports cancel constructs.
1291 /// \param HasCancel true, if the construct has inner cancel directive,
1292 /// false otherwise.
1293 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
1294 Stack.push_back({Kind,
1295 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
1297 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
1300 /// Emits default exit point for the cancel construct (if the special one
1301 /// has not be used) + join point for cancel/normal exits.
1302 void exit(CodeGenFunction &CGF) {
1303 if (getExitBlock().isValid()) {
1304 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
1305 bool HaveIP = CGF.HaveInsertPoint();
1306 if (!Stack.back().HasBeenEmitted) {
1308 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1309 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1310 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1312 CGF.EmitBlock(Stack.back().ContBlock.getBlock());
1314 CGF.Builder.CreateUnreachable();
1315 CGF.Builder.ClearInsertionPoint();
1321 OpenMPCancelExitStack OMPCancelStack;
1325 /// Calculate branch weights appropriate for PGO data
1326 llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
1327 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
1328 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1329 uint64_t LoopCount);
1332 /// Increment the profiler's counter for the given statement by \p StepV.
1333 /// If \p StepV is null, the default increment is 1.
1334 void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
1335 if (CGM.getCodeGenOpts().hasProfileClangInstr())
1336 PGO.emitCounterIncrement(Builder, S, StepV);
1337 PGO.setCurrentStmt(S);
1340 /// Get the profiler's count for the given statement.
1341 uint64_t getProfileCount(const Stmt *S) {
1342 Optional<uint64_t> Count = PGO.getStmtCount(S);
1343 if (!Count.hasValue())
1348 /// Set the profiler's current count.
1349 void setCurrentProfileCount(uint64_t Count) {
1350 PGO.setCurrentRegionCount(Count);
1353 /// Get the profiler's current count. This is generally the count for the most
1354 /// recently incremented counter.
1355 uint64_t getCurrentProfileCount() {
1356 return PGO.getCurrentRegionCount();
1361 /// SwitchInsn - This is nearest current switch instruction. It is null if
1362 /// current context is not in a switch.
1363 llvm::SwitchInst *SwitchInsn = nullptr;
1364 /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1365 SmallVector<uint64_t, 16> *SwitchWeights = nullptr;
1367 /// CaseRangeBlock - This block holds if condition check for last case
1368 /// statement range in current switch instruction.
1369 llvm::BasicBlock *CaseRangeBlock = nullptr;
1371 /// OpaqueLValues - Keeps track of the current set of opaque value
1373 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1374 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1376 // VLASizeMap - This keeps track of the associated size for each VLA type.
1377 // We track this by the size expression rather than the type itself because
1378 // in certain situations, like a const qualifier applied to an VLA typedef,
1379 // multiple VLA types can share the same size expression.
1380 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1381 // enter/leave scopes.
1382 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
1384 /// A block containing a single 'unreachable' instruction. Created
1385 /// lazily by getUnreachableBlock().
1386 llvm::BasicBlock *UnreachableBlock = nullptr;
1388 /// Counts of the number return expressions in the function.
1389 unsigned NumReturnExprs = 0;
1391 /// Count the number of simple (constant) return expressions in the function.
1392 unsigned NumSimpleReturnExprs = 0;
1394 /// The last regular (non-return) debug location (breakpoint) in the function.
1395 SourceLocation LastStopPoint;
1398 /// A scope within which we are constructing the fields of an object which
1399 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1400 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1401 class FieldConstructionScope {
1403 FieldConstructionScope(CodeGenFunction &CGF, Address This)
1404 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1405 CGF.CXXDefaultInitExprThis = This;
1407 ~FieldConstructionScope() {
1408 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1412 CodeGenFunction &CGF;
1413 Address OldCXXDefaultInitExprThis;
1416 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1417 /// is overridden to be the object under construction.
1418 class CXXDefaultInitExprScope {
1420 CXXDefaultInitExprScope(CodeGenFunction &CGF)
1421 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1422 OldCXXThisAlignment(CGF.CXXThisAlignment) {
1423 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
1424 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
1426 ~CXXDefaultInitExprScope() {
1427 CGF.CXXThisValue = OldCXXThisValue;
1428 CGF.CXXThisAlignment = OldCXXThisAlignment;
1432 CodeGenFunction &CGF;
1433 llvm::Value *OldCXXThisValue;
1434 CharUnits OldCXXThisAlignment;
1437 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1438 /// current loop index is overridden.
1439 class ArrayInitLoopExprScope {
1441 ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
1442 : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
1443 CGF.ArrayInitIndex = Index;
1445 ~ArrayInitLoopExprScope() {
1446 CGF.ArrayInitIndex = OldArrayInitIndex;
1450 CodeGenFunction &CGF;
1451 llvm::Value *OldArrayInitIndex;
1454 class InlinedInheritingConstructorScope {
1456 InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
1457 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1458 OldCurCodeDecl(CGF.CurCodeDecl),
1459 OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1460 OldCXXABIThisValue(CGF.CXXABIThisValue),
1461 OldCXXThisValue(CGF.CXXThisValue),
1462 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1463 OldCXXThisAlignment(CGF.CXXThisAlignment),
1464 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1465 OldCXXInheritedCtorInitExprArgs(
1466 std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1468 CGF.CurFuncDecl = CGF.CurCodeDecl =
1469 cast<CXXConstructorDecl>(GD.getDecl());
1470 CGF.CXXABIThisDecl = nullptr;
1471 CGF.CXXABIThisValue = nullptr;
1472 CGF.CXXThisValue = nullptr;
1473 CGF.CXXABIThisAlignment = CharUnits();
1474 CGF.CXXThisAlignment = CharUnits();
1475 CGF.ReturnValue = Address::invalid();
1476 CGF.FnRetTy = QualType();
1477 CGF.CXXInheritedCtorInitExprArgs.clear();
1479 ~InlinedInheritingConstructorScope() {
1480 CGF.CurGD = OldCurGD;
1481 CGF.CurFuncDecl = OldCurFuncDecl;
1482 CGF.CurCodeDecl = OldCurCodeDecl;
1483 CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1484 CGF.CXXABIThisValue = OldCXXABIThisValue;
1485 CGF.CXXThisValue = OldCXXThisValue;
1486 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1487 CGF.CXXThisAlignment = OldCXXThisAlignment;
1488 CGF.ReturnValue = OldReturnValue;
1489 CGF.FnRetTy = OldFnRetTy;
1490 CGF.CXXInheritedCtorInitExprArgs =
1491 std::move(OldCXXInheritedCtorInitExprArgs);
1495 CodeGenFunction &CGF;
1496 GlobalDecl OldCurGD;
1497 const Decl *OldCurFuncDecl;
1498 const Decl *OldCurCodeDecl;
1499 ImplicitParamDecl *OldCXXABIThisDecl;
1500 llvm::Value *OldCXXABIThisValue;
1501 llvm::Value *OldCXXThisValue;
1502 CharUnits OldCXXABIThisAlignment;
1503 CharUnits OldCXXThisAlignment;
1504 Address OldReturnValue;
1505 QualType OldFnRetTy;
1506 CallArgList OldCXXInheritedCtorInitExprArgs;
1510 /// CXXThisDecl - When generating code for a C++ member function,
1511 /// this will hold the implicit 'this' declaration.
1512 ImplicitParamDecl *CXXABIThisDecl = nullptr;
1513 llvm::Value *CXXABIThisValue = nullptr;
1514 llvm::Value *CXXThisValue = nullptr;
1515 CharUnits CXXABIThisAlignment;
1516 CharUnits CXXThisAlignment;
1518 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1519 /// this expression.
1520 Address CXXDefaultInitExprThis = Address::invalid();
1522 /// The current array initialization index when evaluating an
1523 /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
1524 llvm::Value *ArrayInitIndex = nullptr;
1526 /// The values of function arguments to use when evaluating
1527 /// CXXInheritedCtorInitExprs within this context.
1528 CallArgList CXXInheritedCtorInitExprArgs;
1530 /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1531 /// destructor, this will hold the implicit argument (e.g. VTT).
1532 ImplicitParamDecl *CXXStructorImplicitParamDecl = nullptr;
1533 llvm::Value *CXXStructorImplicitParamValue = nullptr;
1535 /// OutermostConditional - Points to the outermost active
1536 /// conditional control. This is used so that we know if a
1537 /// temporary should be destroyed conditionally.
1538 ConditionalEvaluation *OutermostConditional = nullptr;
1540 /// The current lexical scope.
1541 LexicalScope *CurLexicalScope = nullptr;
1543 /// The current source location that should be used for exception
1545 SourceLocation CurEHLocation;
1547 /// BlockByrefInfos - For each __block variable, contains
1548 /// information about the layout of the variable.
1549 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
1551 /// Used by -fsanitize=nullability-return to determine whether the return
1552 /// value can be checked.
1553 llvm::Value *RetValNullabilityPrecondition = nullptr;
1555 /// Check if -fsanitize=nullability-return instrumentation is required for
1557 bool requiresReturnValueNullabilityCheck() const {
1558 return RetValNullabilityPrecondition;
1561 /// Used to store precise source locations for return statements by the
1562 /// runtime return value checks.
1563 Address ReturnLocation = Address::invalid();
1565 /// Check if the return value of this function requires sanitization.
1566 bool requiresReturnValueCheck() const {
1567 return requiresReturnValueNullabilityCheck() ||
1568 (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
1569 CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>());
1572 llvm::BasicBlock *TerminateLandingPad = nullptr;
1573 llvm::BasicBlock *TerminateHandler = nullptr;
1574 llvm::BasicBlock *TrapBB = nullptr;
1576 /// Terminate funclets keyed by parent funclet pad.
1577 llvm::MapVector<llvm::Value *, llvm::BasicBlock *> TerminateFunclets;
1579 /// Largest vector width used in ths function. Will be used to create a
1580 /// function attribute.
1581 unsigned LargestVectorWidth = 0;
1583 /// True if we need emit the life-time markers.
1584 const bool ShouldEmitLifetimeMarkers;
1586 /// Add OpenCL kernel arg metadata and the kernel attribute metadata to
1587 /// the function metadata.
1588 void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
1589 llvm::Function *Fn);
1592 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
1595 CodeGenTypes &getTypes() const { return CGM.getTypes(); }
1596 ASTContext &getContext() const { return CGM.getContext(); }
1597 CGDebugInfo *getDebugInfo() {
1598 if (DisableDebugInfo)
1602 void disableDebugInfo() { DisableDebugInfo = true; }
1603 void enableDebugInfo() { DisableDebugInfo = false; }
1605 bool shouldUseFusedARCCalls() {
1606 return CGM.getCodeGenOpts().OptimizationLevel == 0;
1609 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
1611 /// Returns a pointer to the function's exception object and selector slot,
1612 /// which is assigned in every landing pad.
1613 Address getExceptionSlot();
1614 Address getEHSelectorSlot();
1616 /// Returns the contents of the function's exception object and selector
1618 llvm::Value *getExceptionFromSlot();
1619 llvm::Value *getSelectorFromSlot();
1621 Address getNormalCleanupDestSlot();
1623 llvm::BasicBlock *getUnreachableBlock() {
1624 if (!UnreachableBlock) {
1625 UnreachableBlock = createBasicBlock("unreachable");
1626 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
1628 return UnreachableBlock;
1631 llvm::BasicBlock *getInvokeDest() {
1632 if (!EHStack.requiresLandingPad()) return nullptr;
1633 return getInvokeDestImpl();
1636 bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
1638 const TargetInfo &getTarget() const { return Target; }
1639 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
1640 const TargetCodeGenInfo &getTargetHooks() const {
1641 return CGM.getTargetCodeGenInfo();
1644 //===--------------------------------------------------------------------===//
1646 //===--------------------------------------------------------------------===//
1648 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
1650 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1651 Address arrayEndPointer,
1652 QualType elementType,
1653 CharUnits elementAlignment,
1654 Destroyer *destroyer);
1655 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1656 llvm::Value *arrayEnd,
1657 QualType elementType,
1658 CharUnits elementAlignment,
1659 Destroyer *destroyer);
1661 void pushDestroy(QualType::DestructionKind dtorKind,
1662 Address addr, QualType type);
1663 void pushEHDestroy(QualType::DestructionKind dtorKind,
1664 Address addr, QualType type);
1665 void pushDestroy(CleanupKind kind, Address addr, QualType type,
1666 Destroyer *destroyer, bool useEHCleanupForArray);
1667 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
1668 QualType type, Destroyer *destroyer,
1669 bool useEHCleanupForArray);
1670 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1671 llvm::Value *CompletePtr,
1672 QualType ElementType);
1673 void pushStackRestore(CleanupKind kind, Address SPMem);
1674 void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
1675 bool useEHCleanupForArray);
1676 llvm::Function *generateDestroyHelper(Address addr, QualType type,
1677 Destroyer *destroyer,
1678 bool useEHCleanupForArray,
1680 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
1681 QualType elementType, CharUnits elementAlign,
1682 Destroyer *destroyer,
1683 bool checkZeroLength, bool useEHCleanup);
1685 Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
1687 /// Determines whether an EH cleanup is required to destroy a type
1688 /// with the given destruction kind.
1689 bool needsEHCleanup(QualType::DestructionKind kind) {
1691 case QualType::DK_none:
1693 case QualType::DK_cxx_destructor:
1694 case QualType::DK_objc_weak_lifetime:
1695 case QualType::DK_nontrivial_c_struct:
1696 return getLangOpts().Exceptions;
1697 case QualType::DK_objc_strong_lifetime:
1698 return getLangOpts().Exceptions &&
1699 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1701 llvm_unreachable("bad destruction kind");
1704 CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1705 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1708 //===--------------------------------------------------------------------===//
1710 //===--------------------------------------------------------------------===//
1712 void GenerateObjCMethod(const ObjCMethodDecl *OMD);
1714 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
1716 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
1717 void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1718 const ObjCPropertyImplDecl *PID);
1719 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1720 const ObjCPropertyImplDecl *propImpl,
1721 const ObjCMethodDecl *GetterMothodDecl,
1722 llvm::Constant *AtomicHelperFn);
1724 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1725 ObjCMethodDecl *MD, bool ctor);
1727 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1728 /// for the given property.
1729 void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1730 const ObjCPropertyImplDecl *PID);
1731 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1732 const ObjCPropertyImplDecl *propImpl,
1733 llvm::Constant *AtomicHelperFn);
1735 //===--------------------------------------------------------------------===//
1737 //===--------------------------------------------------------------------===//
1739 /// Emit block literal.
1740 /// \return an LLVM value which is a pointer to a struct which contains
1741 /// information about the block, including the block invoke function, the
1742 /// captured variables, etc.
1743 llvm::Value *EmitBlockLiteral(const BlockExpr *);
1744 static void destroyBlockInfos(CGBlockInfo *info);
1746 llvm::Function *GenerateBlockFunction(GlobalDecl GD,
1747 const CGBlockInfo &Info,
1748 const DeclMapTy &ldm,
1749 bool IsLambdaConversionToBlock,
1750 bool BuildGlobalBlock);
1752 /// Check if \p T is a C++ class that has a destructor that can throw.
1753 static bool cxxDestructorCanThrow(QualType T);
1755 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1756 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
1757 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
1758 const ObjCPropertyImplDecl *PID);
1759 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
1760 const ObjCPropertyImplDecl *PID);
1761 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
1763 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags,
1766 class AutoVarEmission;
1768 void emitByrefStructureInit(const AutoVarEmission &emission);
1770 /// Enter a cleanup to destroy a __block variable. Note that this
1771 /// cleanup should be a no-op if the variable hasn't left the stack
1772 /// yet; if a cleanup is required for the variable itself, that needs
1773 /// to be done externally.
1775 /// \param Kind Cleanup kind.
1777 /// \param Addr When \p LoadBlockVarAddr is false, the address of the __block
1778 /// structure that will be passed to _Block_object_dispose. When
1779 /// \p LoadBlockVarAddr is true, the address of the field of the block
1780 /// structure that holds the address of the __block structure.
1782 /// \param Flags The flag that will be passed to _Block_object_dispose.
1784 /// \param LoadBlockVarAddr Indicates whether we need to emit a load from
1785 /// \p Addr to get the address of the __block structure.
1786 void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags,
1787 bool LoadBlockVarAddr, bool CanThrow);
1789 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
1792 Address LoadBlockStruct();
1793 Address GetAddrOfBlockDecl(const VarDecl *var);
1795 /// BuildBlockByrefAddress - Computes the location of the
1796 /// data in a variable which is declared as __block.
1797 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
1798 bool followForward = true);
1799 Address emitBlockByrefAddress(Address baseAddr,
1800 const BlockByrefInfo &info,
1802 const llvm::Twine &name);
1804 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
1806 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
1808 void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1809 const CGFunctionInfo &FnInfo);
1811 /// Annotate the function with an attribute that disables TSan checking at
1813 void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn);
1815 /// Emit code for the start of a function.
1816 /// \param Loc The location to be associated with the function.
1817 /// \param StartLoc The location of the function body.
1818 void StartFunction(GlobalDecl GD,
1821 const CGFunctionInfo &FnInfo,
1822 const FunctionArgList &Args,
1823 SourceLocation Loc = SourceLocation(),
1824 SourceLocation StartLoc = SourceLocation());
1826 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
1828 void EmitConstructorBody(FunctionArgList &Args);
1829 void EmitDestructorBody(FunctionArgList &Args);
1830 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
1831 void EmitFunctionBody(const Stmt *Body);
1832 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
1834 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
1835 CallArgList &CallArgs);
1836 void EmitLambdaBlockInvokeBody();
1837 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
1838 void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD);
1839 void EmitAsanPrologueOrEpilogue(bool Prologue);
1841 /// Emit the unified return block, trying to avoid its emission when
1843 /// \return The debug location of the user written return statement if the
1844 /// return block is is avoided.
1845 llvm::DebugLoc EmitReturnBlock();
1847 /// FinishFunction - Complete IR generation of the current function. It is
1848 /// legal to call this function even if there is no current insertion point.
1849 void FinishFunction(SourceLocation EndLoc=SourceLocation());
1851 void StartThunk(llvm::Function *Fn, GlobalDecl GD,
1852 const CGFunctionInfo &FnInfo, bool IsUnprototyped);
1854 void EmitCallAndReturnForThunk(llvm::Constant *Callee, const ThunkInfo *Thunk,
1855 bool IsUnprototyped);
1859 /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
1860 void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr,
1861 llvm::Value *Callee);
1863 /// Generate a thunk for the given method.
1864 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1865 GlobalDecl GD, const ThunkInfo &Thunk,
1866 bool IsUnprototyped);
1868 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
1869 const CGFunctionInfo &FnInfo,
1870 GlobalDecl GD, const ThunkInfo &Thunk);
1872 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1873 FunctionArgList &Args);
1875 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
1877 /// Struct with all information about dynamic [sub]class needed to set vptr.
1880 const CXXRecordDecl *NearestVBase;
1881 CharUnits OffsetFromNearestVBase;
1882 const CXXRecordDecl *VTableClass;
1885 /// Initialize the vtable pointer of the given subobject.
1886 void InitializeVTablePointer(const VPtr &vptr);
1888 typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
1890 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1891 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
1893 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
1894 CharUnits OffsetFromNearestVBase,
1895 bool BaseIsNonVirtualPrimaryBase,
1896 const CXXRecordDecl *VTableClass,
1897 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
1899 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1901 /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1903 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
1904 const CXXRecordDecl *VTableClass);
1906 enum CFITypeCheckKind {
1910 CFITCK_UnrelatedCast,
1916 /// Derived is the presumed address of an object of type T after a
1917 /// cast. If T is a polymorphic class type, emit a check that the virtual
1918 /// table for Derived belongs to a class derived from T.
1919 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
1920 bool MayBeNull, CFITypeCheckKind TCK,
1921 SourceLocation Loc);
1923 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
1924 /// If vptr CFI is enabled, emit a check that VTable is valid.
1925 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
1926 CFITypeCheckKind TCK, SourceLocation Loc);
1928 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
1929 /// RD using llvm.type.test.
1930 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
1931 CFITypeCheckKind TCK, SourceLocation Loc);
1933 /// If whole-program virtual table optimization is enabled, emit an assumption
1934 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
1935 /// enabled, emit a check that VTable is a member of RD's type identifier.
1936 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
1937 llvm::Value *VTable, SourceLocation Loc);
1939 /// Returns whether we should perform a type checked load when loading a
1940 /// virtual function for virtual calls to members of RD. This is generally
1941 /// true when both vcall CFI and whole-program-vtables are enabled.
1942 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
1944 /// Emit a type checked load from the given vtable.
1945 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
1946 uint64_t VTableByteOffset);
1948 /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1949 /// given phase of destruction for a destructor. The end result
1950 /// should call destructors on members and base classes in reverse
1951 /// order of their construction.
1952 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1954 /// ShouldInstrumentFunction - Return true if the current function should be
1955 /// instrumented with __cyg_profile_func_* calls
1956 bool ShouldInstrumentFunction();
1958 /// ShouldXRayInstrument - Return true if the current function should be
1959 /// instrumented with XRay nop sleds.
1960 bool ShouldXRayInstrumentFunction() const;
1962 /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit
1963 /// XRay custom event handling calls.
1964 bool AlwaysEmitXRayCustomEvents() const;
1966 /// AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit
1967 /// XRay typed event handling calls.
1968 bool AlwaysEmitXRayTypedEvents() const;
1970 /// Encode an address into a form suitable for use in a function prologue.
1971 llvm::Constant *EncodeAddrForUseInPrologue(llvm::Function *F,
1972 llvm::Constant *Addr);
1974 /// Decode an address used in a function prologue, encoded by \c
1975 /// EncodeAddrForUseInPrologue.
1976 llvm::Value *DecodeAddrUsedInPrologue(llvm::Value *F,
1977 llvm::Value *EncodedAddr);
1979 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
1980 /// arguments for the given function. This is also responsible for naming the
1981 /// LLVM function arguments.
1982 void EmitFunctionProlog(const CGFunctionInfo &FI,
1984 const FunctionArgList &Args);
1986 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
1987 /// given temporary.
1988 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
1989 SourceLocation EndLoc);
1991 /// Emit a test that checks if the return value \p RV is nonnull.
1992 void EmitReturnValueCheck(llvm::Value *RV);
1994 /// EmitStartEHSpec - Emit the start of the exception spec.
1995 void EmitStartEHSpec(const Decl *D);
1997 /// EmitEndEHSpec - Emit the end of the exception spec.
1998 void EmitEndEHSpec(const Decl *D);
2000 /// getTerminateLandingPad - Return a landing pad that just calls terminate.
2001 llvm::BasicBlock *getTerminateLandingPad();
2003 /// getTerminateLandingPad - Return a cleanup funclet that just calls
2005 llvm::BasicBlock *getTerminateFunclet();
2007 /// getTerminateHandler - Return a handler (not a landing pad, just
2008 /// a catch handler) that just calls terminate. This is used when
2009 /// a terminate scope encloses a try.
2010 llvm::BasicBlock *getTerminateHandler();
2012 llvm::Type *ConvertTypeForMem(QualType T);
2013 llvm::Type *ConvertType(QualType T);
2014 llvm::Type *ConvertType(const TypeDecl *T) {
2015 return ConvertType(getContext().getTypeDeclType(T));
2018 /// LoadObjCSelf - Load the value of self. This function is only valid while
2019 /// generating code for an Objective-C method.
2020 llvm::Value *LoadObjCSelf();
2022 /// TypeOfSelfObject - Return type of object that this self represents.
2023 QualType TypeOfSelfObject();
2025 /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T.
2026 static TypeEvaluationKind getEvaluationKind(QualType T);
2028 static bool hasScalarEvaluationKind(QualType T) {
2029 return getEvaluationKind(T) == TEK_Scalar;
2032 static bool hasAggregateEvaluationKind(QualType T) {
2033 return getEvaluationKind(T) == TEK_Aggregate;
2036 /// createBasicBlock - Create an LLVM basic block.
2037 llvm::BasicBlock *createBasicBlock(const Twine &name = "",
2038 llvm::Function *parent = nullptr,
2039 llvm::BasicBlock *before = nullptr) {
2040 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
2043 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
2045 JumpDest getJumpDestForLabel(const LabelDecl *S);
2047 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
2048 /// another basic block, simplify it. This assumes that no other code could
2049 /// potentially reference the basic block.
2050 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
2052 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
2053 /// adding a fall-through branch from the current insert block if
2054 /// necessary. It is legal to call this function even if there is no current
2055 /// insertion point.
2057 /// IsFinished - If true, indicates that the caller has finished emitting
2058 /// branches to the given block and does not expect to emit code into it. This
2059 /// means the block can be ignored if it is unreachable.
2060 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
2062 /// EmitBlockAfterUses - Emit the given block somewhere hopefully
2063 /// near its uses, and leave the insertion point in it.
2064 void EmitBlockAfterUses(llvm::BasicBlock *BB);
2066 /// EmitBranch - Emit a branch to the specified basic block from the current
2067 /// insert block, taking care to avoid creation of branches from dummy
2068 /// blocks. It is legal to call this function even if there is no current
2069 /// insertion point.
2071 /// This function clears the current insertion point. The caller should follow
2072 /// calls to this function with calls to Emit*Block prior to generation new
2074 void EmitBranch(llvm::BasicBlock *Block);
2076 /// HaveInsertPoint - True if an insertion point is defined. If not, this
2077 /// indicates that the current code being emitted is unreachable.
2078 bool HaveInsertPoint() const {
2079 return Builder.GetInsertBlock() != nullptr;
2082 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
2083 /// emitted IR has a place to go. Note that by definition, if this function
2084 /// creates a block then that block is unreachable; callers may do better to
2085 /// detect when no insertion point is defined and simply skip IR generation.
2086 void EnsureInsertPoint() {
2087 if (!HaveInsertPoint())
2088 EmitBlock(createBasicBlock());
2091 /// ErrorUnsupported - Print out an error that codegen doesn't support the
2092 /// specified stmt yet.
2093 void ErrorUnsupported(const Stmt *S, const char *Type);
2095 //===--------------------------------------------------------------------===//
2097 //===--------------------------------------------------------------------===//
2099 LValue MakeAddrLValue(Address Addr, QualType T,
2100 AlignmentSource Source = AlignmentSource::Type) {
2101 return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
2102 CGM.getTBAAAccessInfo(T));
2105 LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo,
2106 TBAAAccessInfo TBAAInfo) {
2107 return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
2110 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
2111 AlignmentSource Source = AlignmentSource::Type) {
2112 return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
2113 LValueBaseInfo(Source), CGM.getTBAAAccessInfo(T));
2116 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
2117 LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) {
2118 return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
2119 BaseInfo, TBAAInfo);
2122 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
2123 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
2124 CharUnits getNaturalTypeAlignment(QualType T,
2125 LValueBaseInfo *BaseInfo = nullptr,
2126 TBAAAccessInfo *TBAAInfo = nullptr,
2127 bool forPointeeType = false);
2128 CharUnits getNaturalPointeeTypeAlignment(QualType T,
2129 LValueBaseInfo *BaseInfo = nullptr,
2130 TBAAAccessInfo *TBAAInfo = nullptr);
2132 Address EmitLoadOfReference(LValue RefLVal,
2133 LValueBaseInfo *PointeeBaseInfo = nullptr,
2134 TBAAAccessInfo *PointeeTBAAInfo = nullptr);
2135 LValue EmitLoadOfReferenceLValue(LValue RefLVal);
2136 LValue EmitLoadOfReferenceLValue(Address RefAddr, QualType RefTy,
2137 AlignmentSource Source =
2138 AlignmentSource::Type) {
2139 LValue RefLVal = MakeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source),
2140 CGM.getTBAAAccessInfo(RefTy));
2141 return EmitLoadOfReferenceLValue(RefLVal);
2144 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
2145 LValueBaseInfo *BaseInfo = nullptr,
2146 TBAAAccessInfo *TBAAInfo = nullptr);
2147 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
2149 /// CreateTempAlloca - This creates an alloca and inserts it into the entry
2150 /// block if \p ArraySize is nullptr, otherwise inserts it at the current
2151 /// insertion point of the builder. The caller is responsible for setting an
2152 /// appropriate alignment on
2155 /// \p ArraySize is the number of array elements to be allocated if it
2158 /// LangAS::Default is the address space of pointers to local variables and
2159 /// temporaries, as exposed in the source language. In certain
2160 /// configurations, this is not the same as the alloca address space, and a
2161 /// cast is needed to lift the pointer from the alloca AS into
2162 /// LangAS::Default. This can happen when the target uses a restricted
2163 /// address space for the stack but the source language requires
2164 /// LangAS::Default to be a generic address space. The latter condition is
2165 /// common for most programming languages; OpenCL is an exception in that
2166 /// LangAS::Default is the private address space, which naturally maps
2169 /// Because the address of a temporary is often exposed to the program in
2170 /// various ways, this function will perform the cast. The original alloca
2171 /// instruction is returned through \p Alloca if it is not nullptr.
2173 /// The cast is not performaed in CreateTempAllocaWithoutCast. This is
2174 /// more efficient if the caller knows that the address will not be exposed.
2175 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp",
2176 llvm::Value *ArraySize = nullptr);
2177 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
2178 const Twine &Name = "tmp",
2179 llvm::Value *ArraySize = nullptr,
2180 Address *Alloca = nullptr);
2181 Address CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align,
2182 const Twine &Name = "tmp",
2183 llvm::Value *ArraySize = nullptr);
2185 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
2186 /// default ABI alignment of the given LLVM type.
2188 /// IMPORTANT NOTE: This is *not* generally the right alignment for
2189 /// any given AST type that happens to have been lowered to the
2190 /// given IR type. This should only ever be used for function-local,
2191 /// IR-driven manipulations like saving and restoring a value. Do
2192 /// not hand this address off to arbitrary IRGen routines, and especially
2193 /// do not pass it as an argument to a function that might expect a
2194 /// properly ABI-aligned value.
2195 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
2196 const Twine &Name = "tmp");
2198 /// InitTempAlloca - Provide an initial value for the given alloca which
2199 /// will be observable at all locations in the function.
2201 /// The address should be something that was returned from one of
2202 /// the CreateTempAlloca or CreateMemTemp routines, and the
2203 /// initializer must be valid in the entry block (i.e. it must
2204 /// either be a constant or an argument value).
2205 void InitTempAlloca(Address Alloca, llvm::Value *Value);
2207 /// CreateIRTemp - Create a temporary IR object of the given type, with
2208 /// appropriate alignment. This routine should only be used when an temporary
2209 /// value needs to be stored into an alloca (for example, to avoid explicit
2210 /// PHI construction), but the type is the IR type, not the type appropriate
2211 /// for storing in memory.
2213 /// That is, this is exactly equivalent to CreateMemTemp, but calling
2214 /// ConvertType instead of ConvertTypeForMem.
2215 Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
2217 /// CreateMemTemp - Create a temporary memory object of the given type, with
2218 /// appropriate alignmen and cast it to the default address space. Returns
2219 /// the original alloca instruction by \p Alloca if it is not nullptr.
2220 Address CreateMemTemp(QualType T, const Twine &Name = "tmp",
2221 Address *Alloca = nullptr);
2222 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp",
2223 Address *Alloca = nullptr);
2225 /// CreateMemTemp - Create a temporary memory object of the given type, with
2226 /// appropriate alignmen without casting it to the default address space.
2227 Address CreateMemTempWithoutCast(QualType T, const Twine &Name = "tmp");
2228 Address CreateMemTempWithoutCast(QualType T, CharUnits Align,
2229 const Twine &Name = "tmp");
2231 /// CreateAggTemp - Create a temporary memory object for the given
2233 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
2234 return AggValueSlot::forAddr(CreateMemTemp(T, Name),
2236 AggValueSlot::IsNotDestructed,
2237 AggValueSlot::DoesNotNeedGCBarriers,
2238 AggValueSlot::IsNotAliased,
2239 AggValueSlot::DoesNotOverlap);
2242 /// Emit a cast to void* in the appropriate address space.
2243 llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
2245 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
2246 /// expression and compare the result against zero, returning an Int1Ty value.
2247 llvm::Value *EvaluateExprAsBool(const Expr *E);
2249 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
2250 void EmitIgnoredExpr(const Expr *E);
2252 /// EmitAnyExpr - Emit code to compute the specified expression which can have
2253 /// any type. The result is returned as an RValue struct. If this is an
2254 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
2255 /// the result should be returned.
2257 /// \param ignoreResult True if the resulting value isn't used.
2258 RValue EmitAnyExpr(const Expr *E,
2259 AggValueSlot aggSlot = AggValueSlot::ignored(),
2260 bool ignoreResult = false);
2262 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
2263 // or the value of the expression, depending on how va_list is defined.
2264 Address EmitVAListRef(const Expr *E);
2266 /// Emit a "reference" to a __builtin_ms_va_list; this is
2267 /// always the value of the expression, because a __builtin_ms_va_list is a
2268 /// pointer to a char.
2269 Address EmitMSVAListRef(const Expr *E);
2271 /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
2272 /// always be accessible even if no aggregate location is provided.
2273 RValue EmitAnyExprToTemp(const Expr *E);
2275 /// EmitAnyExprToMem - Emits the code necessary to evaluate an
2276 /// arbitrary expression into the given memory location.
2277 void EmitAnyExprToMem(const Expr *E, Address Location,
2278 Qualifiers Quals, bool IsInitializer);
2280 void EmitAnyExprToExn(const Expr *E, Address Addr);
2282 /// EmitExprAsInit - Emits the code necessary to initialize a
2283 /// location in memory with the given initializer.
2284 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2285 bool capturedByInit);
2287 /// hasVolatileMember - returns true if aggregate type has a volatile
2289 bool hasVolatileMember(QualType T) {
2290 if (const RecordType *RT = T->getAs<RecordType>()) {
2291 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2292 return RD->hasVolatileMember();
2297 /// Determine whether a return value slot may overlap some other object.
2298 AggValueSlot::Overlap_t overlapForReturnValue() {
2299 // FIXME: Assuming no overlap here breaks guaranteed copy elision for base
2300 // class subobjects. These cases may need to be revisited depending on the
2301 // resolution of the relevant core issue.
2302 return AggValueSlot::DoesNotOverlap;
2305 /// Determine whether a field initialization may overlap some other object.
2306 AggValueSlot::Overlap_t overlapForFieldInit(const FieldDecl *FD) {
2307 // FIXME: These cases can result in overlap as a result of P0840R0's
2308 // [[no_unique_address]] attribute. We can still infer NoOverlap in the
2309 // presence of that attribute if the field is within the nvsize of its
2310 // containing class, because non-virtual subobjects are initialized in
2312 return AggValueSlot::DoesNotOverlap;
2315 /// Determine whether a base class initialization may overlap some other
2317 AggValueSlot::Overlap_t overlapForBaseInit(const CXXRecordDecl *RD,
2318 const CXXRecordDecl *BaseRD,
2321 /// Emit an aggregate assignment.
2322 void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy) {
2323 bool IsVolatile = hasVolatileMember(EltTy);
2324 EmitAggregateCopy(Dest, Src, EltTy, AggValueSlot::MayOverlap, IsVolatile);
2327 void EmitAggregateCopyCtor(LValue Dest, LValue Src,
2328 AggValueSlot::Overlap_t MayOverlap) {
2329 EmitAggregateCopy(Dest, Src, Src.getType(), MayOverlap);
2332 /// EmitAggregateCopy - Emit an aggregate copy.
2334 /// \param isVolatile \c true iff either the source or the destination is
2336 /// \param MayOverlap Whether the tail padding of the destination might be
2337 /// occupied by some other object. More efficient code can often be
2338 /// generated if not.
2339 void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy,
2340 AggValueSlot::Overlap_t MayOverlap,
2341 bool isVolatile = false);
2343 /// GetAddrOfLocalVar - Return the address of a local variable.
2344 Address GetAddrOfLocalVar(const VarDecl *VD) {
2345 auto it = LocalDeclMap.find(VD);
2346 assert(it != LocalDeclMap.end() &&
2347 "Invalid argument to GetAddrOfLocalVar(), no decl!");
2351 /// Given an opaque value expression, return its LValue mapping if it exists,
2352 /// otherwise create one.
2353 LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e);
2355 /// Given an opaque value expression, return its RValue mapping if it exists,
2356 /// otherwise create one.
2357 RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e);
2359 /// Get the index of the current ArrayInitLoopExpr, if any.
2360 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2362 /// getAccessedFieldNo - Given an encoded value and a result number, return
2363 /// the input field number being accessed.
2364 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2366 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
2367 llvm::BasicBlock *GetIndirectGotoBlock();
2369 /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
2370 static bool IsWrappedCXXThis(const Expr *E);
2372 /// EmitNullInitialization - Generate code to set a value of the given type to
2373 /// null, If the type contains data member pointers, they will be initialized
2374 /// to -1 in accordance with the Itanium C++ ABI.
2375 void EmitNullInitialization(Address DestPtr, QualType Ty);
2377 /// Emits a call to an LLVM variable-argument intrinsic, either
2378 /// \c llvm.va_start or \c llvm.va_end.
2379 /// \param ArgValue A reference to the \c va_list as emitted by either
2380 /// \c EmitVAListRef or \c EmitMSVAListRef.
2381 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2382 /// calls \c llvm.va_end.
2383 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2385 /// Generate code to get an argument from the passed in pointer
2386 /// and update it accordingly.
2387 /// \param VE The \c VAArgExpr for which to generate code.
2388 /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2389 /// either \c EmitVAListRef or \c EmitMSVAListRef.
2390 /// \returns A pointer to the argument.
2391 // FIXME: We should be able to get rid of this method and use the va_arg
2392 // instruction in LLVM instead once it works well enough.
2393 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
2395 /// emitArrayLength - Compute the length of an array, even if it's a
2396 /// VLA, and drill down to the base element type.
2397 llvm::Value *emitArrayLength(const ArrayType *arrayType,
2401 /// EmitVLASize - Capture all the sizes for the VLA expressions in
2402 /// the given variably-modified type and store them in the VLASizeMap.
2404 /// This function can be called with a null (unreachable) insert point.
2405 void EmitVariablyModifiedType(QualType Ty);
2407 struct VlaSizePair {
2408 llvm::Value *NumElts;
2411 VlaSizePair(llvm::Value *NE, QualType T) : NumElts(NE), Type(T) {}
2414 /// Return the number of elements for a single dimension
2415 /// for the given array type.
2416 VlaSizePair getVLAElements1D(const VariableArrayType *vla);
2417 VlaSizePair getVLAElements1D(QualType vla);
2419 /// Returns an LLVM value that corresponds to the size,
2420 /// in non-variably-sized elements, of a variable length array type,
2421 /// plus that largest non-variably-sized element type. Assumes that
2422 /// the type has already been emitted with EmitVariablyModifiedType.
2423 VlaSizePair getVLASize(const VariableArrayType *vla);
2424 VlaSizePair getVLASize(QualType vla);
2426 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2427 /// generating code for an C++ member function.
2428 llvm::Value *LoadCXXThis() {
2429 assert(CXXThisValue && "no 'this' value for this function");
2430 return CXXThisValue;
2432 Address LoadCXXThisAddress();
2434 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2436 // FIXME: Every place that calls LoadCXXVTT is something
2437 // that needs to be abstracted properly.
2438 llvm::Value *LoadCXXVTT() {
2439 assert(CXXStructorImplicitParamValue && "no VTT value for this function");
2440 return CXXStructorImplicitParamValue;
2443 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
2444 /// complete class to the given direct base.
2446 GetAddressOfDirectBaseInCompleteClass(Address Value,
2447 const CXXRecordDecl *Derived,
2448 const CXXRecordDecl *Base,
2449 bool BaseIsVirtual);
2451 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2453 /// GetAddressOfBaseClass - This function will add the necessary delta to the
2454 /// load of 'this' and returns address of the base class.
2455 Address GetAddressOfBaseClass(Address Value,
2456 const CXXRecordDecl *Derived,
2457 CastExpr::path_const_iterator PathBegin,
2458 CastExpr::path_const_iterator PathEnd,
2459 bool NullCheckValue, SourceLocation Loc);
2461 Address GetAddressOfDerivedClass(Address Value,
2462 const CXXRecordDecl *Derived,
2463 CastExpr::path_const_iterator PathBegin,
2464 CastExpr::path_const_iterator PathEnd,
2465 bool NullCheckValue);
2467 /// GetVTTParameter - Return the VTT parameter that should be passed to a
2468 /// base constructor/destructor with virtual bases.
2469 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2470 /// to ItaniumCXXABI.cpp together with all the references to VTT.
2471 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2474 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2475 CXXCtorType CtorType,
2476 const FunctionArgList &Args,
2477 SourceLocation Loc);
2478 // It's important not to confuse this and the previous function. Delegating
2479 // constructors are the C++0x feature. The constructor delegate optimization
2480 // is used to reduce duplication in the base and complete consturctors where
2481 // they are substantially the same.
2482 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2483 const FunctionArgList &Args);
2485 /// Emit a call to an inheriting constructor (that is, one that invokes a
2486 /// constructor inherited from a base class) by inlining its definition. This
2487 /// is necessary if the ABI does not support forwarding the arguments to the
2488 /// base class constructor (because they're variadic or similar).
2489 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2490 CXXCtorType CtorType,
2491 bool ForVirtualBase,
2495 /// Emit a call to a constructor inherited from a base class, passing the
2496 /// current constructor's arguments along unmodified (without even making
2498 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
2499 bool ForVirtualBase, Address This,
2500 bool InheritedFromVBase,
2501 const CXXInheritedCtorInitExpr *E);
2503 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2504 bool ForVirtualBase, bool Delegating,
2505 Address This, const CXXConstructExpr *E,
2506 AggValueSlot::Overlap_t Overlap,
2507 bool NewPointerIsChecked);
2509 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2510 bool ForVirtualBase, bool Delegating,
2511 Address This, CallArgList &Args,
2512 AggValueSlot::Overlap_t Overlap,
2514 bool NewPointerIsChecked);
2516 /// Emit assumption load for all bases. Requires to be be called only on
2517 /// most-derived class and not under construction of the object.
2518 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2520 /// Emit assumption that vptr load == global vtable.
2521 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2523 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2524 Address This, Address Src,
2525 const CXXConstructExpr *E);
2527 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2528 const ArrayType *ArrayTy,
2530 const CXXConstructExpr *E,
2531 bool NewPointerIsChecked,
2532 bool ZeroInitialization = false);
2534 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2535 llvm::Value *NumElements,
2537 const CXXConstructExpr *E,
2538 bool NewPointerIsChecked,
2539 bool ZeroInitialization = false);
2541 static Destroyer destroyCXXObject;
2543 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
2544 bool ForVirtualBase, bool Delegating,
2547 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2548 llvm::Type *ElementTy, Address NewPtr,
2549 llvm::Value *NumElements,
2550 llvm::Value *AllocSizeWithoutCookie);
2552 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2555 llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
2556 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2558 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
2559 void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
2561 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
2562 QualType DeleteTy, llvm::Value *NumElements = nullptr,
2563 CharUnits CookieSize = CharUnits());
2565 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
2566 const CallExpr *TheCallExpr, bool IsDelete);
2568 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2569 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2570 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
2572 /// Situations in which we might emit a check for the suitability of a
2573 /// pointer or glvalue.
2574 enum TypeCheckKind {
2575 /// Checking the operand of a load. Must be suitably sized and aligned.
2577 /// Checking the destination of a store. Must be suitably sized and aligned.
2579 /// Checking the bound value in a reference binding. Must be suitably sized
2580 /// and aligned, but is not required to refer to an object (until the
2581 /// reference is used), per core issue 453.
2582 TCK_ReferenceBinding,
2583 /// Checking the object expression in a non-static data member access. Must
2584 /// be an object within its lifetime.
2586 /// Checking the 'this' pointer for a call to a non-static member function.
2587 /// Must be an object within its lifetime.
2589 /// Checking the 'this' pointer for a constructor call.
2590 TCK_ConstructorCall,
2591 /// Checking the operand of a static_cast to a derived pointer type. Must be
2592 /// null or an object within its lifetime.
2593 TCK_DowncastPointer,
2594 /// Checking the operand of a static_cast to a derived reference type. Must
2595 /// be an object within its lifetime.
2596 TCK_DowncastReference,
2597 /// Checking the operand of a cast to a base object. Must be suitably sized
2600 /// Checking the operand of a cast to a virtual base object. Must be an
2601 /// object within its lifetime.
2602 TCK_UpcastToVirtualBase,
2603 /// Checking the value assigned to a _Nonnull pointer. Must not be null.
2605 /// Checking the operand of a dynamic_cast or a typeid expression. Must be
2606 /// null or an object within its lifetime.
2607 TCK_DynamicOperation
2610 /// Determine whether the pointer type check \p TCK permits null pointers.
2611 static bool isNullPointerAllowed(TypeCheckKind TCK);
2613 /// Determine whether the pointer type check \p TCK requires a vptr check.
2614 static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty);
2616 /// Whether any type-checking sanitizers are enabled. If \c false,
2617 /// calls to EmitTypeCheck can be skipped.
2618 bool sanitizePerformTypeCheck() const;
2620 /// Emit a check that \p V is the address of storage of the
2621 /// appropriate size and alignment for an object of type \p Type.
2622 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
2623 QualType Type, CharUnits Alignment = CharUnits::Zero(),
2624 SanitizerSet SkippedChecks = SanitizerSet());
2626 /// Emit a check that \p Base points into an array object, which
2627 /// we can access at index \p Index. \p Accessed should be \c false if we
2628 /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
2629 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
2630 QualType IndexType, bool Accessed);
2632 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2633 bool isInc, bool isPre);
2634 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
2635 bool isInc, bool isPre);
2637 /// Converts Location to a DebugLoc, if debug information is enabled.
2638 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
2641 //===--------------------------------------------------------------------===//
2642 // Declaration Emission
2643 //===--------------------------------------------------------------------===//
2645 /// EmitDecl - Emit a declaration.
2647 /// This function can be called with a null (unreachable) insert point.
2648 void EmitDecl(const Decl &D);
2650 /// EmitVarDecl - Emit a local variable declaration.
2652 /// This function can be called with a null (unreachable) insert point.
2653 void EmitVarDecl(const VarDecl &D);
2655 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2656 bool capturedByInit);
2658 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
2659 llvm::Value *Address);
2661 /// Determine whether the given initializer is trivial in the sense
2662 /// that it requires no code to be generated.
2663 bool isTrivialInitializer(const Expr *Init);
2665 /// EmitAutoVarDecl - Emit an auto variable declaration.
2667 /// This function can be called with a null (unreachable) insert point.
2668 void EmitAutoVarDecl(const VarDecl &D);
2670 class AutoVarEmission {
2671 friend class CodeGenFunction;
2673 const VarDecl *Variable;
2675 /// The address of the alloca for languages with explicit address space
2676 /// (e.g. OpenCL) or alloca casted to generic pointer for address space
2677 /// agnostic languages (e.g. C++). Invalid if the variable was emitted
2678 /// as a global constant.
2681 llvm::Value *NRVOFlag;
2683 /// True if the variable is a __block variable that is captured by an
2685 bool IsEscapingByRef;
2687 /// True if the variable is of aggregate type and has a constant
2689 bool IsConstantAggregate;
2691 /// Non-null if we should use lifetime annotations.
2692 llvm::Value *SizeForLifetimeMarkers;
2694 /// Address with original alloca instruction. Invalid if the variable was
2695 /// emitted as a global constant.
2699 AutoVarEmission(Invalid)
2700 : Variable(nullptr), Addr(Address::invalid()),
2701 AllocaAddr(Address::invalid()) {}
2703 AutoVarEmission(const VarDecl &variable)
2704 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
2705 IsEscapingByRef(false), IsConstantAggregate(false),
2706 SizeForLifetimeMarkers(nullptr), AllocaAddr(Address::invalid()) {}
2708 bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
2711 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
2713 bool useLifetimeMarkers() const {
2714 return SizeForLifetimeMarkers != nullptr;
2716 llvm::Value *getSizeForLifetimeMarkers() const {
2717 assert(useLifetimeMarkers());
2718 return SizeForLifetimeMarkers;
2721 /// Returns the raw, allocated address, which is not necessarily
2722 /// the address of the object itself. It is casted to default
2723 /// address space for address space agnostic languages.
2724 Address getAllocatedAddress() const {
2728 /// Returns the address for the original alloca instruction.
2729 Address getOriginalAllocatedAddress() const { return AllocaAddr; }
2731 /// Returns the address of the object within this declaration.
2732 /// Note that this does not chase the forwarding pointer for
2734 Address getObjectAddress(CodeGenFunction &CGF) const {
2735 if (!IsEscapingByRef) return Addr;
2737 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
2740 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
2741 void EmitAutoVarInit(const AutoVarEmission &emission);
2742 void EmitAutoVarCleanups(const AutoVarEmission &emission);
2743 void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
2744 QualType::DestructionKind dtorKind);
2746 /// Emits the alloca and debug information for the size expressions for each
2747 /// dimension of an array. It registers the association of its (1-dimensional)
2748 /// QualTypes and size expression's debug node, so that CGDebugInfo can
2749 /// reference this node when creating the DISubrange object to describe the
2751 void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI,
2753 bool EmitDebugInfo);
2755 void EmitStaticVarDecl(const VarDecl &D,
2756 llvm::GlobalValue::LinkageTypes Linkage);
2761 ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
2763 static ParamValue forDirect(llvm::Value *value) {
2764 return ParamValue(value, 0);
2766 static ParamValue forIndirect(Address addr) {
2767 assert(!addr.getAlignment().isZero());
2768 return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
2771 bool isIndirect() const { return Alignment != 0; }
2772 llvm::Value *getAnyValue() const { return Value; }
2774 llvm::Value *getDirectValue() const {
2775 assert(!isIndirect());
2779 Address getIndirectAddress() const {
2780 assert(isIndirect());
2781 return Address(Value, CharUnits::fromQuantity(Alignment));
2785 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
2786 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
2788 /// protectFromPeepholes - Protect a value that we're intending to
2789 /// store to the side, but which will probably be used later, from
2790 /// aggressive peepholing optimizations that might delete it.
2792 /// Pass the result to unprotectFromPeepholes to declare that
2793 /// protection is no longer required.
2795 /// There's no particular reason why this shouldn't apply to
2796 /// l-values, it's just that no existing peepholes work on pointers.
2797 PeepholeProtection protectFromPeepholes(RValue rvalue);
2798 void unprotectFromPeepholes(PeepholeProtection protection);
2800 void EmitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty,
2802 SourceLocation AssumptionLoc,
2803 llvm::Value *Alignment,
2804 llvm::Value *OffsetValue,
2805 llvm::Value *TheCheck,
2806 llvm::Instruction *Assumption);
2808 void EmitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty,
2809 SourceLocation Loc, SourceLocation AssumptionLoc,
2810 llvm::Value *Alignment,
2811 llvm::Value *OffsetValue = nullptr);
2813 void EmitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty,
2814 SourceLocation Loc, SourceLocation AssumptionLoc,
2816 llvm::Value *OffsetValue = nullptr);
2818 void EmitAlignmentAssumption(llvm::Value *PtrValue, const Expr *E,
2819 SourceLocation AssumptionLoc, unsigned Alignment,
2820 llvm::Value *OffsetValue = nullptr);
2822 //===--------------------------------------------------------------------===//
2823 // Statement Emission
2824 //===--------------------------------------------------------------------===//
2826 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
2827 void EmitStopPoint(const Stmt *S);
2829 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
2830 /// this function even if there is no current insertion point.
2832 /// This function may clear the current insertion point; callers should use
2833 /// EnsureInsertPoint if they wish to subsequently generate code without first
2834 /// calling EmitBlock, EmitBranch, or EmitStmt.
2835 void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = None);
2837 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
2838 /// necessarily require an insertion point or debug information; typically
2839 /// because the statement amounts to a jump or a container of other
2842 /// \return True if the statement was handled.
2843 bool EmitSimpleStmt(const Stmt *S);
2845 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
2846 AggValueSlot AVS = AggValueSlot::ignored());
2847 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
2848 bool GetLast = false,
2850 AggValueSlot::ignored());
2852 /// EmitLabel - Emit the block for the given label. It is legal to call this
2853 /// function even if there is no current insertion point.
2854 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
2856 void EmitLabelStmt(const LabelStmt &S);
2857 void EmitAttributedStmt(const AttributedStmt &S);
2858 void EmitGotoStmt(const GotoStmt &S);
2859 void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
2860 void EmitIfStmt(const IfStmt &S);
2862 void EmitWhileStmt(const WhileStmt &S,
2863 ArrayRef<const Attr *> Attrs = None);
2864 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
2865 void EmitForStmt(const ForStmt &S,
2866 ArrayRef<const Attr *> Attrs = None);
2867 void EmitReturnStmt(const ReturnStmt &S);
2868 void EmitDeclStmt(const DeclStmt &S);
2869 void EmitBreakStmt(const BreakStmt &S);
2870 void EmitContinueStmt(const ContinueStmt &S);
2871 void EmitSwitchStmt(const SwitchStmt &S);
2872 void EmitDefaultStmt(const DefaultStmt &S);
2873 void EmitCaseStmt(const CaseStmt &S);
2874 void EmitCaseStmtRange(const CaseStmt &S);
2875 void EmitAsmStmt(const AsmStmt &S);
2877 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
2878 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
2879 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
2880 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
2881 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
2883 void EmitCoroutineBody(const CoroutineBodyStmt &S);
2884 void EmitCoreturnStmt(const CoreturnStmt &S);
2885 RValue EmitCoawaitExpr(const CoawaitExpr &E,
2886 AggValueSlot aggSlot = AggValueSlot::ignored(),
2887 bool ignoreResult = false);
2888 LValue EmitCoawaitLValue(const CoawaitExpr *E);
2889 RValue EmitCoyieldExpr(const CoyieldExpr &E,
2890 AggValueSlot aggSlot = AggValueSlot::ignored(),
2891 bool ignoreResult = false);
2892 LValue EmitCoyieldLValue(const CoyieldExpr *E);
2893 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
2895 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2896 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2898 void EmitCXXTryStmt(const CXXTryStmt &S);
2899 void EmitSEHTryStmt(const SEHTryStmt &S);
2900 void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
2901 void EnterSEHTryStmt(const SEHTryStmt &S);
2902 void ExitSEHTryStmt(const SEHTryStmt &S);
2904 void pushSEHCleanup(CleanupKind kind,
2905 llvm::Function *FinallyFunc);
2906 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
2907 const Stmt *OutlinedStmt);
2909 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2910 const SEHExceptStmt &Except);
2912 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2913 const SEHFinallyStmt &Finally);
2915 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
2916 llvm::Value *ParentFP,
2917 llvm::Value *EntryEBP);
2918 llvm::Value *EmitSEHExceptionCode();
2919 llvm::Value *EmitSEHExceptionInfo();
2920 llvm::Value *EmitSEHAbnormalTermination();
2922 /// Emit simple code for OpenMP directives in Simd-only mode.
2923 void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D);
2925 /// Scan the outlined statement for captures from the parent function. For
2926 /// each capture, mark the capture as escaped and emit a call to
2927 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
2928 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
2931 /// Recovers the address of a local in a parent function. ParentVar is the
2932 /// address of the variable used in the immediate parent function. It can
2933 /// either be an alloca or a call to llvm.localrecover if there are nested
2934 /// outlined functions. ParentFP is the frame pointer of the outermost parent
2936 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
2938 llvm::Value *ParentFP);
2940 void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
2941 ArrayRef<const Attr *> Attrs = None);
2943 /// Controls insertion of cancellation exit blocks in worksharing constructs.
2944 class OMPCancelStackRAII {
2945 CodeGenFunction &CGF;
2948 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
2951 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
2953 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
2956 /// Returns calculated size of the specified type.
2957 llvm::Value *getTypeSize(QualType Ty);
2958 LValue InitCapturedStruct(const CapturedStmt &S);
2959 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
2960 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
2961 Address GenerateCapturedStmtArgument(const CapturedStmt &S);
2962 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
2963 void GenerateOpenMPCapturedVars(const CapturedStmt &S,
2964 SmallVectorImpl<llvm::Value *> &CapturedVars);
2965 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
2966 SourceLocation Loc);
2967 /// Perform element by element copying of arrays with type \a
2968 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
2969 /// generated by \a CopyGen.
2971 /// \param DestAddr Address of the destination array.
2972 /// \param SrcAddr Address of the source array.
2973 /// \param OriginalType Type of destination and source arrays.
2974 /// \param CopyGen Copying procedure that copies value of single array element
2975 /// to another single array element.
2976 void EmitOMPAggregateAssign(
2977 Address DestAddr, Address SrcAddr, QualType OriginalType,
2978 const llvm::function_ref<void(Address, Address)> CopyGen);
2979 /// Emit proper copying of data from one variable to another.
2981 /// \param OriginalType Original type of the copied variables.
2982 /// \param DestAddr Destination address.
2983 /// \param SrcAddr Source address.
2984 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
2985 /// type of the base array element).
2986 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
2987 /// the base array element).
2988 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
2990 void EmitOMPCopy(QualType OriginalType,
2991 Address DestAddr, Address SrcAddr,
2992 const VarDecl *DestVD, const VarDecl *SrcVD,
2994 /// Emit atomic update code for constructs: \a X = \a X \a BO \a E or
2995 /// \a X = \a E \a BO \a E.
2997 /// \param X Value to be updated.
2998 /// \param E Update value.
2999 /// \param BO Binary operation for update operation.
3000 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
3001 /// expression, false otherwise.
3002 /// \param AO Atomic ordering of the generated atomic instructions.
3003 /// \param CommonGen Code generator for complex expressions that cannot be
3004 /// expressed through atomicrmw instruction.
3005 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
3006 /// generated, <false, RValue::get(nullptr)> otherwise.
3007 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
3008 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3009 llvm::AtomicOrdering AO, SourceLocation Loc,
3010 const llvm::function_ref<RValue(RValue)> CommonGen);
3011 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
3012 OMPPrivateScope &PrivateScope);
3013 void EmitOMPPrivateClause(const OMPExecutableDirective &D,
3014 OMPPrivateScope &PrivateScope);
3015 void EmitOMPUseDevicePtrClause(
3016 const OMPClause &C, OMPPrivateScope &PrivateScope,
3017 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
3018 /// Emit code for copyin clause in \a D directive. The next code is
3019 /// generated at the start of outlined functions for directives:
3021 /// threadprivate_var1 = master_threadprivate_var1;
3022 /// operator=(threadprivate_var2, master_threadprivate_var2);
3024 /// __kmpc_barrier(&loc, global_tid);
3027 /// \param D OpenMP directive possibly with 'copyin' clause(s).
3028 /// \returns true if at least one copyin variable is found, false otherwise.
3029 bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
3030 /// Emit initial code for lastprivate variables. If some variable is
3031 /// not also firstprivate, then the default initialization is used. Otherwise
3032 /// initialization of this variable is performed by EmitOMPFirstprivateClause
3035 /// \param D Directive that may have 'lastprivate' directives.
3036 /// \param PrivateScope Private scope for capturing lastprivate variables for
3037 /// proper codegen in internal captured statement.
3039 /// \returns true if there is at least one lastprivate variable, false
3041 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
3042 OMPPrivateScope &PrivateScope);
3043 /// Emit final copying of lastprivate values to original variables at
3044 /// the end of the worksharing or simd directive.
3046 /// \param D Directive that has at least one 'lastprivate' directives.
3047 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
3048 /// it is the last iteration of the loop code in associated directive, or to
3049 /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
3050 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
3052 llvm::Value *IsLastIterCond = nullptr);
3053 /// Emit initial code for linear clauses.
3054 void EmitOMPLinearClause(const OMPLoopDirective &D,
3055 CodeGenFunction::OMPPrivateScope &PrivateScope);
3056 /// Emit final code for linear clauses.
3057 /// \param CondGen Optional conditional code for final part of codegen for
3059 void EmitOMPLinearClauseFinal(
3060 const OMPLoopDirective &D,
3061 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
3062 /// Emit initial code for reduction variables. Creates reduction copies
3063 /// and initializes them with the values according to OpenMP standard.
3065 /// \param D Directive (possibly) with the 'reduction' clause.
3066 /// \param PrivateScope Private scope for capturing reduction variables for
3067 /// proper codegen in internal captured statement.
3069 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
3070 OMPPrivateScope &PrivateScope);
3071 /// Emit final update of reduction values to original variables at
3072 /// the end of the directive.
3074 /// \param D Directive that has at least one 'reduction' directives.
3075 /// \param ReductionKind The kind of reduction to perform.
3076 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
3077 const OpenMPDirectiveKind ReductionKind);
3078 /// Emit initial code for linear variables. Creates private copies
3079 /// and initializes them with the values according to OpenMP standard.
3081 /// \param D Directive (possibly) with the 'linear' clause.
3082 /// \return true if at least one linear variable is found that should be
3083 /// initialized with the value of the original variable, false otherwise.
3084 bool EmitOMPLinearClauseInit(const OMPLoopDirective &D);
3086 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
3087 llvm::Value * /*OutlinedFn*/,
3088 const OMPTaskDataTy & /*Data*/)>
3090 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
3091 const OpenMPDirectiveKind CapturedRegion,
3092 const RegionCodeGenTy &BodyGen,
3093 const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
3094 struct OMPTargetDataInfo {
3095 Address BasePointersArray = Address::invalid();
3096 Address PointersArray = Address::invalid();
3097 Address SizesArray = Address::invalid();
3098 unsigned NumberOfTargetItems = 0;
3099 explicit OMPTargetDataInfo() = default;
3100 OMPTargetDataInfo(Address BasePointersArray, Address PointersArray,
3101 Address SizesArray, unsigned NumberOfTargetItems)
3102 : BasePointersArray(BasePointersArray), PointersArray(PointersArray),
3103 SizesArray(SizesArray), NumberOfTargetItems(NumberOfTargetItems) {}
3105 void EmitOMPTargetTaskBasedDirective(const OMPExecutableDirective &S,
3106 const RegionCodeGenTy &BodyGen,
3107 OMPTargetDataInfo &InputInfo);
3109 void EmitOMPParallelDirective(const OMPParallelDirective &S);
3110 void EmitOMPSimdDirective(const OMPSimdDirective &S);
3111 void EmitOMPForDirective(const OMPForDirective &S);
3112 void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
3113 void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
3114 void EmitOMPSectionDirective(const OMPSectionDirective &S);
3115 void EmitOMPSingleDirective(const OMPSingleDirective &S);
3116 void EmitOMPMasterDirective(const OMPMasterDirective &S);
3117 void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
3118 void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
3119 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
3120 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
3121 void EmitOMPTaskDirective(const OMPTaskDirective &S);
3122 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
3123 void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
3124 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
3125 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
3126 void EmitOMPFlushDirective(const OMPFlushDirective &S);
3127 void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
3128 void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
3129 void EmitOMPTargetDirective(const OMPTargetDirective &S);
3130 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
3131 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
3132 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
3133 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
3134 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
3136 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
3137 void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
3139 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
3140 void EmitOMPCancelDirective(const OMPCancelDirective &S);
3141 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
3142 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
3143 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
3144 void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
3145 void EmitOMPDistributeParallelForDirective(
3146 const OMPDistributeParallelForDirective &S);
3147 void EmitOMPDistributeParallelForSimdDirective(
3148 const OMPDistributeParallelForSimdDirective &S);
3149 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
3150 void EmitOMPTargetParallelForSimdDirective(
3151 const OMPTargetParallelForSimdDirective &S);
3152 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
3153 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
3155 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
3156 void EmitOMPTeamsDistributeParallelForSimdDirective(
3157 const OMPTeamsDistributeParallelForSimdDirective &S);
3158 void EmitOMPTeamsDistributeParallelForDirective(
3159 const OMPTeamsDistributeParallelForDirective &S);
3160 void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
3161 void EmitOMPTargetTeamsDistributeDirective(
3162 const OMPTargetTeamsDistributeDirective &S);
3163 void EmitOMPTargetTeamsDistributeParallelForDirective(
3164 const OMPTargetTeamsDistributeParallelForDirective &S);
3165 void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
3166 const OMPTargetTeamsDistributeParallelForSimdDirective &S);
3167 void EmitOMPTargetTeamsDistributeSimdDirective(
3168 const OMPTargetTeamsDistributeSimdDirective &S);
3170 /// Emit device code for the target directive.
3171 static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3172 StringRef ParentName,
3173 const OMPTargetDirective &S);
3175 EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
3176 const OMPTargetParallelDirective &S);
3177 /// Emit device code for the target parallel for directive.
3178 static void EmitOMPTargetParallelForDeviceFunction(
3179 CodeGenModule &CGM, StringRef ParentName,
3180 const OMPTargetParallelForDirective &S);
3181 /// Emit device code for the target parallel for simd directive.
3182 static void EmitOMPTargetParallelForSimdDeviceFunction(
3183 CodeGenModule &CGM, StringRef ParentName,
3184 const OMPTargetParallelForSimdDirective &S);
3185 /// Emit device code for the target teams directive.
3187 EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
3188 const OMPTargetTeamsDirective &S);
3189 /// Emit device code for the target teams distribute directive.
3190 static void EmitOMPTargetTeamsDistributeDeviceFunction(
3191 CodeGenModule &CGM, StringRef ParentName,
3192 const OMPTargetTeamsDistributeDirective &S);
3193 /// Emit device code for the target teams distribute simd directive.
3194 static void EmitOMPTargetTeamsDistributeSimdDeviceFunction(
3195 CodeGenModule &CGM, StringRef ParentName,
3196 const OMPTargetTeamsDistributeSimdDirective &S);
3197 /// Emit device code for the target simd directive.
3198 static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM,
3199 StringRef ParentName,
3200 const OMPTargetSimdDirective &S);
3201 /// Emit device code for the target teams distribute parallel for simd
3203 static void EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
3204 CodeGenModule &CGM, StringRef ParentName,
3205 const OMPTargetTeamsDistributeParallelForSimdDirective &S);
3207 static void EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
3208 CodeGenModule &CGM, StringRef ParentName,
3209 const OMPTargetTeamsDistributeParallelForDirective &S);
3210 /// Emit inner loop of the worksharing/simd construct.
3212 /// \param S Directive, for which the inner loop must be emitted.
3213 /// \param RequiresCleanup true, if directive has some associated private
3215 /// \param LoopCond Bollean condition for loop continuation.
3216 /// \param IncExpr Increment expression for loop control variable.
3217 /// \param BodyGen Generator for the inner body of the inner loop.
3218 /// \param PostIncGen Genrator for post-increment code (required for ordered
3219 /// loop directvies).
3220 void EmitOMPInnerLoop(
3221 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
3222 const Expr *IncExpr,
3223 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
3224 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen);
3226 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
3227 /// Emit initial code for loop counters of loop-based directives.
3228 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
3229 OMPPrivateScope &LoopScope);
3231 /// Helper for the OpenMP loop directives.
3232 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
3234 /// Emit code for the worksharing loop-based directive.
3235 /// \return true, if this construct has any lastprivate clause, false -
3237 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB,
3238 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
3239 const CodeGenDispatchBoundsTy &CGDispatchBounds);
3241 /// Emit code for the distribute loop-based directive.
3242 void EmitOMPDistributeLoop(const OMPLoopDirective &S,
3243 const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
3245 /// Helpers for the OpenMP loop directives.
3246 void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
3247 void EmitOMPSimdFinal(
3248 const OMPLoopDirective &D,
3249 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
3251 /// Emits the lvalue for the expression with possibly captured variable.
3252 LValue EmitOMPSharedLValue(const Expr *E);
3255 /// Helpers for blocks.
3256 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
3258 /// struct with the values to be passed to the OpenMP loop-related functions
3259 struct OMPLoopArguments {
3260 /// loop lower bound
3261 Address LB = Address::invalid();
3262 /// loop upper bound
3263 Address UB = Address::invalid();
3265 Address ST = Address::invalid();
3266 /// isLastIteration argument for runtime functions
3267 Address IL = Address::invalid();
3268 /// Chunk value generated by sema
3269 llvm::Value *Chunk = nullptr;
3270 /// EnsureUpperBound
3271 Expr *EUB = nullptr;
3272 /// IncrementExpression
3273 Expr *IncExpr = nullptr;
3274 /// Loop initialization
3275 Expr *Init = nullptr;
3276 /// Loop exit condition
3277 Expr *Cond = nullptr;
3278 /// Update of LB after a whole chunk has been executed
3279 Expr *NextLB = nullptr;
3280 /// Update of UB after a whole chunk has been executed
3281 Expr *NextUB = nullptr;
3282 OMPLoopArguments() = default;
3283 OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
3284 llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
3285 Expr *IncExpr = nullptr, Expr *Init = nullptr,
3286 Expr *Cond = nullptr, Expr *NextLB = nullptr,
3287 Expr *NextUB = nullptr)
3288 : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
3289 IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
3292 void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
3293 const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
3294 const OMPLoopArguments &LoopArgs,
3295 const CodeGenLoopTy &CodeGenLoop,
3296 const CodeGenOrderedTy &CodeGenOrdered);
3297 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
3298 bool IsMonotonic, const OMPLoopDirective &S,
3299 OMPPrivateScope &LoopScope, bool Ordered,
3300 const OMPLoopArguments &LoopArgs,
3301 const CodeGenDispatchBoundsTy &CGDispatchBounds);
3302 void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
3303 const OMPLoopDirective &S,
3304 OMPPrivateScope &LoopScope,
3305 const OMPLoopArguments &LoopArgs,
3306 const CodeGenLoopTy &CodeGenLoopContent);
3307 /// Emit code for sections directive.
3308 void EmitSections(const OMPExecutableDirective &S);
3312 //===--------------------------------------------------------------------===//
3313 // LValue Expression Emission
3314 //===--------------------------------------------------------------------===//
3316 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
3317 RValue GetUndefRValue(QualType Ty);
3319 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
3320 /// and issue an ErrorUnsupported style diagnostic (using the
3322 RValue EmitUnsupportedRValue(const Expr *E,
3325 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
3326 /// an ErrorUnsupported style diagnostic (using the provided Name).
3327 LValue EmitUnsupportedLValue(const Expr *E,
3330 /// EmitLValue - Emit code to compute a designator that specifies the location
3331 /// of the expression.
3333 /// This can return one of two things: a simple address or a bitfield
3334 /// reference. In either case, the LLVM Value* in the LValue structure is
3335 /// guaranteed to be an LLVM pointer type.
3337 /// If this returns a bitfield reference, nothing about the pointee type of
3338 /// the LLVM value is known: For example, it may not be a pointer to an
3341 /// If this returns a normal address, and if the lvalue's C type is fixed
3342 /// size, this method guarantees that the returned pointer type will point to
3343 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
3344 /// variable length type, this is not possible.
3346 LValue EmitLValue(const Expr *E);
3348 /// Same as EmitLValue but additionally we generate checking code to
3349 /// guard against undefined behavior. This is only suitable when we know
3350 /// that the address will be used to access the object.
3351 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
3353 RValue convertTempToRValue(Address addr, QualType type,
3354 SourceLocation Loc);
3356 void EmitAtomicInit(Expr *E, LValue lvalue);
3358 bool LValueIsSuitableForInlineAtomic(LValue Src);
3360 RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
3361 AggValueSlot Slot = AggValueSlot::ignored());
3363 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
3364 llvm::AtomicOrdering AO, bool IsVolatile = false,
3365 AggValueSlot slot = AggValueSlot::ignored());
3367 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
3369 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
3370 bool IsVolatile, bool isInit);
3372 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
3373 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
3374 llvm::AtomicOrdering Success =
3375 llvm::AtomicOrdering::SequentiallyConsistent,
3376 llvm::AtomicOrdering Failure =
3377 llvm::AtomicOrdering::SequentiallyConsistent,
3378 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
3380 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
3381 const llvm::function_ref<RValue(RValue)> &UpdateOp,
3384 /// EmitToMemory - Change a scalar value from its value
3385 /// representation to its in-memory representation.
3386 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
3388 /// EmitFromMemory - Change a scalar value from its memory
3389 /// representation to its value representation.
3390 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
3392 /// Check if the scalar \p Value is within the valid range for the given
3395 /// Returns true if a check is needed (even if the range is unknown).
3396 bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
3397 SourceLocation Loc);
3399 /// EmitLoadOfScalar - Load a scalar value from an address, taking
3400 /// care to appropriately convert from the memory representation to
3401 /// the LLVM value representation.
3402 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
3404 AlignmentSource Source = AlignmentSource::Type,
3405 bool isNontemporal = false) {
3406 return EmitLoadOfScalar(Addr, Volatile, Ty, Loc, LValueBaseInfo(Source),
3407 CGM.getTBAAAccessInfo(Ty), isNontemporal);
3410 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
3411 SourceLocation Loc, LValueBaseInfo BaseInfo,
3412 TBAAAccessInfo TBAAInfo,
3413 bool isNontemporal = false);
3415 /// EmitLoadOfScalar - Load a scalar value from an address, taking
3416 /// care to appropriately convert from the memory representation to
3417 /// the LLVM value representation. The l-value must be a simple
3419 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
3421 /// EmitStoreOfScalar - Store a scalar value to an address, taking
3422 /// care to appropriately convert from the memory representation to
3423 /// the LLVM value representation.
3424 void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3425 bool Volatile, QualType Ty,
3426 AlignmentSource Source = AlignmentSource::Type,
3427 bool isInit = false, bool isNontemporal = false) {
3428 EmitStoreOfScalar(Value, Addr, Volatile, Ty, LValueBaseInfo(Source),
3429 CGM.getTBAAAccessInfo(Ty), isInit, isNontemporal);
3432 void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3433 bool Volatile, QualType Ty,
3434 LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo,
3435 bool isInit = false, bool isNontemporal = false);
3437 /// EmitStoreOfScalar - Store a scalar value to an address, taking
3438 /// care to appropriately convert from the memory representation to
3439 /// the LLVM value representation. The l-value must be a simple
3440 /// l-value. The isInit flag indicates whether this is an initialization.
3441 /// If so, atomic qualifiers are ignored and the store is always non-atomic.
3442 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
3444 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
3445 /// this method emits the address of the lvalue, then loads the result as an
3446 /// rvalue, returning the rvalue.
3447 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
3448 RValue EmitLoadOfExtVectorElementLValue(LValue V);
3449 RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc);
3450 RValue EmitLoadOfGlobalRegLValue(LValue LV);
3452 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
3453 /// lvalue, where both are guaranteed to the have the same type, and that type
3455 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
3456 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
3457 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
3459 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
3460 /// as EmitStoreThroughLValue.
3462 /// \param Result [out] - If non-null, this will be set to a Value* for the
3463 /// bit-field contents after the store, appropriate for use as the result of
3464 /// an assignment to the bit-field.
3465 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
3466 llvm::Value **Result=nullptr);
3468 /// Emit an l-value for an assignment (simple or compound) of complex type.
3469 LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
3470 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
3471 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
3472 llvm::Value *&Result);
3474 // Note: only available for agg return types
3475 LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
3476 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
3477 // Note: only available for agg return types
3478 LValue EmitCallExprLValue(const CallExpr *E);
3479 // Note: only available for agg return types
3480 LValue EmitVAArgExprLValue(const VAArgExpr *E);
3481 LValue EmitDeclRefLValue(const DeclRefExpr *E);
3482 LValue EmitStringLiteralLValue(const StringLiteral *E);
3483 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
3484 LValue EmitPredefinedLValue(const PredefinedExpr *E);
3485 LValue EmitUnaryOpLValue(const UnaryOperator *E);
3486 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3487 bool Accessed = false);
3488 LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3489 bool IsLowerBound = true);
3490 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
3491 LValue EmitMemberExpr(const MemberExpr *E);
3492 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
3493 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
3494 LValue EmitInitListLValue(const InitListExpr *E);
3495 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
3496 LValue EmitCastLValue(const CastExpr *E);
3497 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
3498 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
3500 Address EmitExtVectorElementLValue(LValue V);
3502 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
3504 Address EmitArrayToPointerDecay(const Expr *Array,
3505 LValueBaseInfo *BaseInfo = nullptr,
3506 TBAAAccessInfo *TBAAInfo = nullptr);
3508 class ConstantEmission {
3509 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
3510 ConstantEmission(llvm::Constant *C, bool isReference)
3511 : ValueAndIsReference(C, isReference) {}
3513 ConstantEmission() {}
3514 static ConstantEmission forReference(llvm::Constant *C) {
3515 return ConstantEmission(C, true);
3517 static ConstantEmission forValue(llvm::Constant *C) {
3518 return ConstantEmission(C, false);
3521 explicit operator bool() const {
3522 return ValueAndIsReference.getOpaqueValue() != nullptr;
3525 bool isReference() const { return ValueAndIsReference.getInt(); }
3526 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
3527 assert(isReference());
3528 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
3529 refExpr->getType());
3532 llvm::Constant *getValue() const {
3533 assert(!isReference());
3534 return ValueAndIsReference.getPointer();
3538 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
3539 ConstantEmission tryEmitAsConstant(const MemberExpr *ME);
3540 llvm::Value *emitScalarConstant(const ConstantEmission &Constant, Expr *E);
3542 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
3543 AggValueSlot slot = AggValueSlot::ignored());
3544 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
3546 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
3547 const ObjCIvarDecl *Ivar);
3548 LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
3549 LValue EmitLValueForLambdaField(const FieldDecl *Field);
3551 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
3552 /// if the Field is a reference, this will return the address of the reference
3553 /// and not the address of the value stored in the reference.
3554 LValue EmitLValueForFieldInitialization(LValue Base,
3555 const FieldDecl* Field);
3557 LValue EmitLValueForIvar(QualType ObjectTy,
3558 llvm::Value* Base, const ObjCIvarDecl *Ivar,
3559 unsigned CVRQualifiers);
3561 LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
3562 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
3563 LValue EmitLambdaLValue(const LambdaExpr *E);
3564 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
3565 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
3567 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
3568 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
3569 LValue EmitStmtExprLValue(const StmtExpr *E);
3570 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
3571 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
3572 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
3574 //===--------------------------------------------------------------------===//
3575 // Scalar Expression Emission
3576 //===--------------------------------------------------------------------===//
3578 /// EmitCall - Generate a call of the given function, expecting the given
3579 /// result type, and using the given argument list which specifies both the
3580 /// LLVM arguments and the types they were derived from.
3581 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
3582 ReturnValueSlot ReturnValue, const CallArgList &Args,
3583 llvm::Instruction **callOrInvoke, SourceLocation Loc);
3584 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
3585 ReturnValueSlot ReturnValue, const CallArgList &Args,
3586 llvm::Instruction **callOrInvoke = nullptr) {
3587 return EmitCall(CallInfo, Callee, ReturnValue, Args, callOrInvoke,
3590 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
3591 ReturnValueSlot ReturnValue, llvm::Value *Chain = nullptr);
3592 RValue EmitCallExpr(const CallExpr *E,
3593 ReturnValueSlot ReturnValue = ReturnValueSlot());
3594 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3595 CGCallee EmitCallee(const Expr *E);
3597 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
3599 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3600 const Twine &name = "");
3601 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3602 ArrayRef<llvm::Value*> args,
3603 const Twine &name = "");
3604 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3605 const Twine &name = "");
3606 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3607 ArrayRef<llvm::Value*> args,
3608 const Twine &name = "");
3610 SmallVector<llvm::OperandBundleDef, 1>
3611 getBundlesForFunclet(llvm::Value *Callee);
3613 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
3614 ArrayRef<llvm::Value *> Args,
3615 const Twine &Name = "");
3616 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3617 ArrayRef<llvm::Value*> args,
3618 const Twine &name = "");
3619 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3620 const Twine &name = "");
3621 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3622 ArrayRef<llvm::Value*> args);
3624 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
3625 NestedNameSpecifier *Qual,
3628 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
3630 const CXXRecordDecl *RD);
3632 // Return the copy constructor name with the prefix "__copy_constructor_"
3634 static std::string getNonTrivialCopyConstructorStr(QualType QT,
3635 CharUnits Alignment,
3639 // Return the destructor name with the prefix "__destructor_" removed.
3640 static std::string getNonTrivialDestructorStr(QualType QT,
3641 CharUnits Alignment,
3645 // These functions emit calls to the special functions of non-trivial C
3647 void defaultInitNonTrivialCStructVar(LValue Dst);
3648 void callCStructDefaultConstructor(LValue Dst);
3649 void callCStructDestructor(LValue Dst);
3650 void callCStructCopyConstructor(LValue Dst, LValue Src);
3651 void callCStructMoveConstructor(LValue Dst, LValue Src);
3652 void callCStructCopyAssignmentOperator(LValue Dst, LValue Src);
3653 void callCStructMoveAssignmentOperator(LValue Dst, LValue Src);
3656 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
3657 const CGCallee &Callee,
3658 ReturnValueSlot ReturnValue, llvm::Value *This,
3659 llvm::Value *ImplicitParam,
3660 QualType ImplicitParamTy, const CallExpr *E,
3661 CallArgList *RtlArgs);
3662 RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD,
3663 const CGCallee &Callee,
3664 llvm::Value *This, llvm::Value *ImplicitParam,
3665 QualType ImplicitParamTy, const CallExpr *E,
3667 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
3668 ReturnValueSlot ReturnValue);
3669 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
3670 const CXXMethodDecl *MD,
3671 ReturnValueSlot ReturnValue,
3673 NestedNameSpecifier *Qualifier,
3674 bool IsArrow, const Expr *Base);
3675 // Compute the object pointer.
3676 Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
3677 llvm::Value *memberPtr,
3678 const MemberPointerType *memberPtrType,
3679 LValueBaseInfo *BaseInfo = nullptr,
3680 TBAAAccessInfo *TBAAInfo = nullptr);
3681 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
3682 ReturnValueSlot ReturnValue);
3684 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
3685 const CXXMethodDecl *MD,
3686 ReturnValueSlot ReturnValue);
3687 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
3689 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
3690 ReturnValueSlot ReturnValue);
3692 RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E,
3693 ReturnValueSlot ReturnValue);
3695 RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
3696 const CallExpr *E, ReturnValueSlot ReturnValue);
3698 RValue emitRotate(const CallExpr *E, bool IsRotateRight);
3700 /// Emit IR for __builtin_os_log_format.
3701 RValue emitBuiltinOSLogFormat(const CallExpr &E);
3703 llvm::Function *generateBuiltinOSLogHelperFunction(
3704 const analyze_os_log::OSLogBufferLayout &Layout,
3705 CharUnits BufferAlignment);
3707 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3709 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
3710 /// is unhandled by the current target.
3711 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3713 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
3714 const llvm::CmpInst::Predicate Fp,
3715 const llvm::CmpInst::Predicate Ip,
3716 const llvm::Twine &Name = "");
3717 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
3718 llvm::Triple::ArchType Arch);
3720 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
3721 unsigned LLVMIntrinsic,
3722 unsigned AltLLVMIntrinsic,
3723 const char *NameHint,
3726 SmallVectorImpl<llvm::Value *> &Ops,
3727 Address PtrOp0, Address PtrOp1,
3728 llvm::Triple::ArchType Arch);
3730 llvm::Value *EmitISOVolatileLoad(const CallExpr *E);
3731 llvm::Value *EmitISOVolatileStore(const CallExpr *E);
3733 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
3734 unsigned Modifier, llvm::Type *ArgTy,
3736 llvm::Value *EmitNeonCall(llvm::Function *F,
3737 SmallVectorImpl<llvm::Value*> &O,
3739 unsigned shift = 0, bool rightshift = false);
3740 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
3741 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
3742 bool negateForRightShift);
3743 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
3744 llvm::Type *Ty, bool usgn, const char *name);
3745 llvm::Value *vectorWrapScalar16(llvm::Value *Op);
3746 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E,
3747 llvm::Triple::ArchType Arch);
3749 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
3750 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3751 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3752 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3753 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3754 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3755 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
3757 llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3760 enum class MSVCIntrin;
3763 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
3765 llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args);
3767 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
3768 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
3769 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
3770 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
3771 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
3772 llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
3773 const ObjCMethodDecl *MethodWithObjects);
3774 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
3775 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
3776 ReturnValueSlot Return = ReturnValueSlot());
3778 /// Retrieves the default cleanup kind for an ARC cleanup.
3779 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
3780 CleanupKind getARCCleanupKind() {
3781 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
3782 ? NormalAndEHCleanup : NormalCleanup;
3786 void EmitARCInitWeak(Address addr, llvm::Value *value);
3787 void EmitARCDestroyWeak(Address addr);
3788 llvm::Value *EmitARCLoadWeak(Address addr);
3789 llvm::Value *EmitARCLoadWeakRetained(Address addr);
3790 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
3791 void emitARCCopyAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
3792 void emitARCMoveAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
3793 void EmitARCCopyWeak(Address dst, Address src);
3794 void EmitARCMoveWeak(Address dst, Address src);
3795 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
3796 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
3797 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
3798 bool resultIgnored);
3799 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
3800 bool resultIgnored);
3801 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
3802 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
3803 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
3804 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
3805 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
3806 llvm::Value *EmitARCAutorelease(llvm::Value *value);
3807 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
3808 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
3809 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
3810 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
3812 llvm::Value *EmitObjCAutorelease(llvm::Value *value, llvm::Type *returnType);
3813 llvm::Value *EmitObjCRetainNonBlock(llvm::Value *value,
3814 llvm::Type *returnType);
3815 void EmitObjCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
3817 std::pair<LValue,llvm::Value*>
3818 EmitARCStoreAutoreleasing(const BinaryOperator *e);
3819 std::pair<LValue,llvm::Value*>
3820 EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
3821 std::pair<LValue,llvm::Value*>
3822 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
3824 llvm::Value *EmitObjCAlloc(llvm::Value *value,
3825 llvm::Type *returnType);
3826 llvm::Value *EmitObjCAllocWithZone(llvm::Value *value,
3827 llvm::Type *returnType);
3828 llvm::Value *EmitObjCThrowOperand(const Expr *expr);
3829 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
3830 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
3832 llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
3833 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
3834 bool allowUnsafeClaim);
3835 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
3836 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
3837 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
3839 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
3841 static Destroyer destroyARCStrongImprecise;
3842 static Destroyer destroyARCStrongPrecise;
3843 static Destroyer destroyARCWeak;
3844 static Destroyer emitARCIntrinsicUse;
3845 static Destroyer destroyNonTrivialCStruct;
3847 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
3848 llvm::Value *EmitObjCAutoreleasePoolPush();
3849 llvm::Value *EmitObjCMRRAutoreleasePoolPush();
3850 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
3851 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
3853 /// Emits a reference binding to the passed in expression.
3854 RValue EmitReferenceBindingToExpr(const Expr *E);
3856 //===--------------------------------------------------------------------===//
3857 // Expression Emission
3858 //===--------------------------------------------------------------------===//
3860 // Expressions are broken into three classes: scalar, complex, aggregate.
3862 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
3863 /// scalar type, returning the result.
3864 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
3866 /// Emit a conversion from the specified type to the specified destination
3867 /// type, both of which are LLVM scalar types.
3868 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
3869 QualType DstTy, SourceLocation Loc);
3871 /// Emit a conversion from the specified complex type to the specified
3872 /// destination type, where the destination type is an LLVM scalar type.
3873 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
3875 SourceLocation Loc);
3877 /// EmitAggExpr - Emit the computation of the specified expression
3878 /// of aggregate type. The result is computed into the given slot,
3879 /// which may be null to indicate that the value is not needed.
3880 void EmitAggExpr(const Expr *E, AggValueSlot AS);
3882 /// EmitAggExprToLValue - Emit the computation of the specified expression of
3883 /// aggregate type into a temporary LValue.
3884 LValue EmitAggExprToLValue(const Expr *E);
3886 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3887 /// make sure it survives garbage collection until this point.
3888 void EmitExtendGCLifetime(llvm::Value *object);
3890 /// EmitComplexExpr - Emit the computation of the specified expression of
3891 /// complex type, returning the result.
3892 ComplexPairTy EmitComplexExpr(const Expr *E,
3893 bool IgnoreReal = false,
3894 bool IgnoreImag = false);
3896 /// EmitComplexExprIntoLValue - Emit the given expression of complex
3897 /// type and place its result into the specified l-value.
3898 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
3900 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
3901 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
3903 /// EmitLoadOfComplex - Load a complex number from the specified l-value.
3904 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
3906 Address emitAddrOfRealComponent(Address complex, QualType complexType);
3907 Address emitAddrOfImagComponent(Address complex, QualType complexType);
3909 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
3910 /// global variable that has already been created for it. If the initializer
3911 /// has a different type than GV does, this may free GV and return a different
3912 /// one. Otherwise it just returns GV.
3913 llvm::GlobalVariable *
3914 AddInitializerToStaticVarDecl(const VarDecl &D,
3915 llvm::GlobalVariable *GV);
3917 // Emit an @llvm.invariant.start call for the given memory region.
3918 void EmitInvariantStart(llvm::Constant *Addr, CharUnits Size);
3920 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
3921 /// variable with global storage.
3922 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
3925 llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
3926 llvm::Constant *Addr);
3928 /// Call atexit() with a function that passes the given argument to
3929 /// the given function.
3930 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
3931 llvm::Constant *addr);
3933 /// Call atexit() with function dtorStub.
3934 void registerGlobalDtorWithAtExit(llvm::Constant *dtorStub);
3936 /// Emit code in this function to perform a guarded variable
3937 /// initialization. Guarded initializations are used when it's not
3938 /// possible to prove that an initialization will be done exactly
3939 /// once, e.g. with a static local variable or a static data member
3940 /// of a class template.
3941 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
3944 enum class GuardKind { VariableGuard, TlsGuard };
3946 /// Emit a branch to select whether or not to perform guarded initialization.
3947 void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
3948 llvm::BasicBlock *InitBlock,
3949 llvm::BasicBlock *NoInitBlock,
3950 GuardKind Kind, const VarDecl *D);
3952 /// GenerateCXXGlobalInitFunc - Generates code for initializing global
3955 GenerateCXXGlobalInitFunc(llvm::Function *Fn,
3956 ArrayRef<llvm::Function *> CXXThreadLocals,
3957 ConstantAddress Guard = ConstantAddress::invalid());
3959 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
3961 void GenerateCXXGlobalDtorsFunc(
3963 const std::vector<std::pair<llvm::WeakTrackingVH, llvm::Constant *>>
3966 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
3968 llvm::GlobalVariable *Addr,
3971 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
3973 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
3975 void enterFullExpression(const FullExpr *E) {
3976 if (const auto *EWC = dyn_cast<ExprWithCleanups>(E))
3977 if (EWC->getNumObjects() == 0)
3979 enterNonTrivialFullExpression(E);
3981 void enterNonTrivialFullExpression(const FullExpr *E);
3983 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
3985 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
3987 RValue EmitAtomicExpr(AtomicExpr *E);
3989 //===--------------------------------------------------------------------===//
3990 // Annotations Emission
3991 //===--------------------------------------------------------------------===//
3993 /// Emit an annotation call (intrinsic or builtin).
3994 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
3995 llvm::Value *AnnotatedVal,
3996 StringRef AnnotationStr,
3997 SourceLocation Location);
3999 /// Emit local annotations for the local variable V, declared by D.
4000 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
4002 /// Emit field annotations for the given field & value. Returns the
4003 /// annotation result.
4004 Address EmitFieldAnnotations(const FieldDecl *D, Address V);
4006 //===--------------------------------------------------------------------===//
4008 //===--------------------------------------------------------------------===//
4010 /// ContainsLabel - Return true if the statement contains a label in it. If
4011 /// this statement is not executed normally, it not containing a label means
4012 /// that we can just remove the code.
4013 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
4015 /// containsBreak - Return true if the statement contains a break out of it.
4016 /// If the statement (recursively) contains a switch or loop with a break
4017 /// inside of it, this is fine.
4018 static bool containsBreak(const Stmt *S);
4020 /// Determine if the given statement might introduce a declaration into the
4021 /// current scope, by being a (possibly-labelled) DeclStmt.
4022 static bool mightAddDeclToScope(const Stmt *S);
4024 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
4025 /// to a constant, or if it does but contains a label, return false. If it
4026 /// constant folds return true and set the boolean result in Result.
4027 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
4028 bool AllowLabels = false);
4030 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
4031 /// to a constant, or if it does but contains a label, return false. If it
4032 /// constant folds return true and set the folded value.
4033 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
4034 bool AllowLabels = false);
4036 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
4037 /// if statement) to the specified blocks. Based on the condition, this might
4038 /// try to simplify the codegen of the conditional based on the branch.
4039 /// TrueCount should be the number of times we expect the condition to
4040 /// evaluate to true based on PGO data.
4041 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
4042 llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
4044 /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is
4045 /// nonnull, if \p LHS is marked _Nonnull.
4046 void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc);
4048 /// An enumeration which makes it easier to specify whether or not an
4049 /// operation is a subtraction.
4050 enum { NotSubtraction = false, IsSubtraction = true };
4052 /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to
4053 /// detect undefined behavior when the pointer overflow sanitizer is enabled.
4054 /// \p SignedIndices indicates whether any of the GEP indices are signed.
4055 /// \p IsSubtraction indicates whether the expression used to form the GEP
4056 /// is a subtraction.
4057 llvm::Value *EmitCheckedInBoundsGEP(llvm::Value *Ptr,
4058 ArrayRef<llvm::Value *> IdxList,
4062 const Twine &Name = "");
4064 /// Specifies which type of sanitizer check to apply when handling a
4065 /// particular builtin.
4066 enum BuiltinCheckKind {
4071 /// Emits an argument for a call to a builtin. If the builtin sanitizer is
4072 /// enabled, a runtime check specified by \p Kind is also emitted.
4073 llvm::Value *EmitCheckedArgForBuiltin(const Expr *E, BuiltinCheckKind Kind);
4075 /// Emit a description of a type in a format suitable for passing to
4076 /// a runtime sanitizer handler.
4077 llvm::Constant *EmitCheckTypeDescriptor(QualType T);
4079 /// Convert a value into a format suitable for passing to a runtime
4080 /// sanitizer handler.
4081 llvm::Value *EmitCheckValue(llvm::Value *V);
4083 /// Emit a description of a source location in a format suitable for
4084 /// passing to a runtime sanitizer handler.
4085 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
4087 /// Create a basic block that will call a handler function in a
4088 /// sanitizer runtime with the provided arguments, and create a conditional
4090 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
4091 SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
4092 ArrayRef<llvm::Value *> DynamicArgs);
4094 /// Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
4095 /// if Cond if false.
4096 void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
4097 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
4098 ArrayRef<llvm::Constant *> StaticArgs);
4100 /// Emit a reached-unreachable diagnostic if \p Loc is valid and runtime
4101 /// checking is enabled. Otherwise, just emit an unreachable instruction.
4102 void EmitUnreachable(SourceLocation Loc);
4104 /// Create a basic block that will call the trap intrinsic, and emit a
4105 /// conditional branch to it, for the -ftrapv checks.
4106 void EmitTrapCheck(llvm::Value *Checked);
4108 /// Emit a call to trap or debugtrap and attach function attribute
4109 /// "trap-func-name" if specified.
4110 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
4112 /// Emit a stub for the cross-DSO CFI check function.
4113 void EmitCfiCheckStub();
4115 /// Emit a cross-DSO CFI failure handling function.
4116 void EmitCfiCheckFail();
4118 /// Create a check for a function parameter that may potentially be
4119 /// declared as non-null.
4120 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
4121 AbstractCallee AC, unsigned ParmNum);
4123 /// EmitCallArg - Emit a single call argument.
4124 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
4126 /// EmitDelegateCallArg - We are performing a delegate call; that
4127 /// is, the current function is delegating to another one. Produce
4128 /// a r-value suitable for passing the given parameter.
4129 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
4130 SourceLocation loc);
4132 /// SetFPAccuracy - Set the minimum required accuracy of the given floating
4133 /// point operation, expressed as the maximum relative error in ulp.
4134 void SetFPAccuracy(llvm::Value *Val, float Accuracy);
4137 llvm::MDNode *getRangeForLoadFromType(QualType Ty);
4138 void EmitReturnOfRValue(RValue RV, QualType Ty);
4140 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
4142 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
4143 DeferredReplacements;
4145 /// Set the address of a local variable.
4146 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
4147 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
4148 LocalDeclMap.insert({VD, Addr});
4151 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
4152 /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
4154 /// \param AI - The first function argument of the expansion.
4155 void ExpandTypeFromArgs(QualType Ty, LValue Dst,
4156 SmallVectorImpl<llvm::Value *>::iterator &AI);
4158 /// ExpandTypeToArgs - Expand an CallArg \arg Arg, with the LLVM type for \arg
4159 /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
4160 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
4161 void ExpandTypeToArgs(QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
4162 SmallVectorImpl<llvm::Value *> &IRCallArgs,
4163 unsigned &IRCallArgPos);
4165 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
4166 const Expr *InputExpr, std::string &ConstraintStr);
4168 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
4169 LValue InputValue, QualType InputType,
4170 std::string &ConstraintStr,
4171 SourceLocation Loc);
4173 /// Attempts to statically evaluate the object size of E. If that
4174 /// fails, emits code to figure the size of E out for us. This is
4175 /// pass_object_size aware.
4177 /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
4178 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
4179 llvm::IntegerType *ResType,
4180 llvm::Value *EmittedE);
4182 /// Emits the size of E, as required by __builtin_object_size. This
4183 /// function is aware of pass_object_size parameters, and will act accordingly
4184 /// if E is a parameter with the pass_object_size attribute.
4185 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
4186 llvm::IntegerType *ResType,
4187 llvm::Value *EmittedE);
4191 // Determine whether the given argument is an Objective-C method
4192 // that may have type parameters in its signature.
4193 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4194 const DeclContext *dc = method->getDeclContext();
4195 if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
4196 return classDecl->getTypeParamListAsWritten();
4199 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4200 return catDecl->getTypeParamList();
4206 template<typename T>
4207 static bool isObjCMethodWithTypeParams(const T *) { return false; }
4210 enum class EvaluationOrder {
4211 ///! No language constraints on evaluation order.
4213 ///! Language semantics require left-to-right evaluation.
4215 ///! Language semantics require right-to-left evaluation.
4219 /// EmitCallArgs - Emit call arguments for a function.
4220 template <typename T>
4221 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
4222 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4223 AbstractCallee AC = AbstractCallee(),
4224 unsigned ParamsToSkip = 0,
4225 EvaluationOrder Order = EvaluationOrder::Default) {
4226 SmallVector<QualType, 16> ArgTypes;
4227 CallExpr::const_arg_iterator Arg = ArgRange.begin();
4229 assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
4230 "Can't skip parameters if type info is not provided");
4231 if (CallArgTypeInfo) {
4233 bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
4236 // First, use the argument types that the type info knows about
4237 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
4238 E = CallArgTypeInfo->param_type_end();
4239 I != E; ++I, ++Arg) {
4240 assert(Arg != ArgRange.end() && "Running over edge of argument list!");
4241 assert((isGenericMethod ||
4242 ((*I)->isVariablyModifiedType() ||
4243 (*I).getNonReferenceType()->isObjCRetainableType() ||
4245 .getCanonicalType((*I).getNonReferenceType())
4248 .getCanonicalType((*Arg)->getType())
4250 "type mismatch in call argument!");
4251 ArgTypes.push_back(*I);
4255 // Either we've emitted all the call args, or we have a call to variadic
4257 assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
4258 CallArgTypeInfo->isVariadic()) &&
4259 "Extra arguments in non-variadic function!");
4261 // If we still have any arguments, emit them using the type of the argument.
4262 for (auto *A : llvm::make_range(Arg, ArgRange.end()))
4263 ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType());
4265 EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order);
4268 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
4269 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4270 AbstractCallee AC = AbstractCallee(),
4271 unsigned ParamsToSkip = 0,
4272 EvaluationOrder Order = EvaluationOrder::Default);
4274 /// EmitPointerWithAlignment - Given an expression with a pointer type,
4275 /// emit the value and compute our best estimate of the alignment of the
4278 /// \param BaseInfo - If non-null, this will be initialized with
4279 /// information about the source of the alignment and the may-alias
4280 /// attribute. Note that this function will conservatively fall back on
4281 /// the type when it doesn't recognize the expression and may-alias will
4282 /// be set to false.
4284 /// One reasonable way to use this information is when there's a language
4285 /// guarantee that the pointer must be aligned to some stricter value, and
4286 /// we're simply trying to ensure that sufficiently obvious uses of under-
4287 /// aligned objects don't get miscompiled; for example, a placement new
4288 /// into the address of a local variable. In such a case, it's quite
4289 /// reasonable to just ignore the returned alignment when it isn't from an
4290 /// explicit source.
4291 Address EmitPointerWithAlignment(const Expr *Addr,
4292 LValueBaseInfo *BaseInfo = nullptr,
4293 TBAAAccessInfo *TBAAInfo = nullptr);
4295 /// If \p E references a parameter with pass_object_size info or a constant
4296 /// array size modifier, emit the object size divided by the size of \p EltTy.
4297 /// Otherwise return null.
4298 llvm::Value *LoadPassedObjectSize(const Expr *E, QualType EltTy);
4300 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
4302 struct MultiVersionResolverOption {
4303 llvm::Function *Function;
4306 StringRef Architecture;
4307 llvm::SmallVector<StringRef, 8> Features;
4309 Conds(StringRef Arch, ArrayRef<StringRef> Feats)
4310 : Architecture(Arch), Features(Feats.begin(), Feats.end()) {}
4313 MultiVersionResolverOption(llvm::Function *F, StringRef Arch,
4314 ArrayRef<StringRef> Feats)
4315 : Function(F), Conditions(Arch, Feats) {}
4318 // Emits the body of a multiversion function's resolver. Assumes that the
4319 // options are already sorted in the proper order, with the 'default' option
4320 // last (if it exists).
4321 void EmitMultiVersionResolver(llvm::Function *Resolver,
4322 ArrayRef<MultiVersionResolverOption> Options);
4324 static uint64_t GetX86CpuSupportsMask(ArrayRef<StringRef> FeatureStrs);
4327 QualType getVarArgType(const Expr *Arg);
4329 void EmitDeclMetadata();
4331 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
4332 const AutoVarEmission &emission);
4334 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
4336 llvm::Value *GetValueForARMHint(unsigned BuiltinID);
4337 llvm::Value *EmitX86CpuIs(const CallExpr *E);
4338 llvm::Value *EmitX86CpuIs(StringRef CPUStr);
4339 llvm::Value *EmitX86CpuSupports(const CallExpr *E);
4340 llvm::Value *EmitX86CpuSupports(ArrayRef<StringRef> FeatureStrs);
4341 llvm::Value *EmitX86CpuSupports(uint64_t Mask);
4342 llvm::Value *EmitX86CpuInit();
4343 llvm::Value *FormResolverCondition(const MultiVersionResolverOption &RO);
4346 inline DominatingLLVMValue::saved_type
4347 DominatingLLVMValue::save(CodeGenFunction &CGF, llvm::Value *value) {
4348 if (!needsSaving(value)) return saved_type(value, false);
4350 // Otherwise, we need an alloca.
4351 auto align = CharUnits::fromQuantity(
4352 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
4354 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
4355 CGF.Builder.CreateStore(value, alloca);
4357 return saved_type(alloca.getPointer(), true);
4360 inline llvm::Value *DominatingLLVMValue::restore(CodeGenFunction &CGF,
4362 // If the value says it wasn't saved, trust that it's still dominating.
4363 if (!value.getInt()) return value.getPointer();
4365 // Otherwise, it should be an alloca instruction, as set up in save().
4366 auto alloca = cast<llvm::AllocaInst>(value.getPointer());
4367 return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
4370 } // end namespace CodeGen
4371 } // end namespace clang