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/OpenMPKinds.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Frontend/CodeGenOptions.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/IR/ValueHandle.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Transforms/Utils/SanitizerStats.h"
56 class CXXDestructorDecl;
57 class CXXForRangeStmt;
61 class EnumConstantDecl;
63 class FunctionProtoType;
65 class ObjCContainerDecl;
66 class ObjCInterfaceDecl;
69 class ObjCImplementationDecl;
70 class ObjCPropertyImplDecl;
73 class ObjCForCollectionStmt;
75 class ObjCAtThrowStmt;
76 class ObjCAtSynchronizedStmt;
77 class ObjCAutoreleasePoolStmt;
86 class BlockByrefHelpers;
89 class BlockFieldFlags;
90 class RegionCodeGenTy;
91 class TargetCodeGenInfo;
95 /// The kind of evaluation to perform on values of a particular
96 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or
99 /// TODO: should vectors maybe be split out into their own thing?
100 enum TypeEvaluationKind {
106 #define LIST_SANITIZER_CHECKS \
107 SANITIZER_CHECK(AddOverflow, add_overflow, 0) \
108 SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \
109 SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \
110 SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \
111 SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \
112 SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \
113 SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 0) \
114 SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \
115 SANITIZER_CHECK(MissingReturn, missing_return, 0) \
116 SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \
117 SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \
118 SANITIZER_CHECK(NullabilityArg, nullability_arg, 0) \
119 SANITIZER_CHECK(NullabilityReturn, nullability_return, 0) \
120 SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \
121 SANITIZER_CHECK(NonnullReturn, nonnull_return, 0) \
122 SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \
123 SANITIZER_CHECK(PointerOverflow, pointer_overflow, 0) \
124 SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \
125 SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \
126 SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \
127 SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
129 enum SanitizerHandler {
130 #define SANITIZER_CHECK(Enum, Name, Version) Enum,
131 LIST_SANITIZER_CHECKS
132 #undef SANITIZER_CHECK
135 /// CodeGenFunction - This class organizes the per-function state that is used
136 /// while generating LLVM code.
137 class CodeGenFunction : public CodeGenTypeCache {
138 CodeGenFunction(const CodeGenFunction &) = delete;
139 void operator=(const CodeGenFunction &) = delete;
141 friend class CGCXXABI;
143 /// A jump destination is an abstract label, branching to which may
144 /// require a jump out through normal cleanups.
146 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
147 JumpDest(llvm::BasicBlock *Block,
148 EHScopeStack::stable_iterator Depth,
150 : Block(Block), ScopeDepth(Depth), Index(Index) {}
152 bool isValid() const { return Block != nullptr; }
153 llvm::BasicBlock *getBlock() const { return Block; }
154 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
155 unsigned getDestIndex() const { return Index; }
157 // This should be used cautiously.
158 void setScopeDepth(EHScopeStack::stable_iterator depth) {
163 llvm::BasicBlock *Block;
164 EHScopeStack::stable_iterator ScopeDepth;
168 CodeGenModule &CGM; // Per-module state.
169 const TargetInfo &Target;
171 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
172 LoopInfoStack LoopStack;
175 // Stores variables for which we can't generate correct lifetime markers
177 VarBypassDetector Bypasses;
179 // CodeGen lambda for loops and support for ordered clause
180 typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
183 typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
184 const unsigned, const bool)>
187 // Codegen lambda for loop bounds in worksharing loop constructs
188 typedef llvm::function_ref<std::pair<LValue, LValue>(
189 CodeGenFunction &, const OMPExecutableDirective &S)>
192 // Codegen lambda for loop bounds in dispatch-based loop implementation
193 typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
194 CodeGenFunction &, const OMPExecutableDirective &S, Address LB,
196 CodeGenDispatchBoundsTy;
198 /// \brief CGBuilder insert helper. This function is called after an
199 /// instruction is created using Builder.
200 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
201 llvm::BasicBlock *BB,
202 llvm::BasicBlock::iterator InsertPt) const;
204 /// CurFuncDecl - Holds the Decl for the current outermost
205 /// non-closure context.
206 const Decl *CurFuncDecl;
207 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
208 const Decl *CurCodeDecl;
209 const CGFunctionInfo *CurFnInfo;
211 llvm::Function *CurFn;
213 // Holds coroutine data if the current function is a coroutine. We use a
214 // wrapper to manage its lifetime, so that we don't have to define CGCoroData
217 std::unique_ptr<CGCoroData> Data;
223 /// CurGD - The GlobalDecl for the current function being compiled.
226 /// PrologueCleanupDepth - The cleanup depth enclosing all the
227 /// cleanups associated with the parameters.
228 EHScopeStack::stable_iterator PrologueCleanupDepth;
230 /// ReturnBlock - Unified return block.
231 JumpDest ReturnBlock;
233 /// ReturnValue - The temporary alloca to hold the return
234 /// value. This is invalid iff the function has no return value.
237 /// Return true if a label was seen in the current scope.
238 bool hasLabelBeenSeenInCurrentScope() const {
240 return CurLexicalScope->hasLabels();
241 return !LabelMap.empty();
244 /// AllocaInsertPoint - This is an instruction in the entry block before which
245 /// we prefer to insert allocas.
246 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
248 /// \brief API for captured statement code generation.
249 class CGCapturedStmtInfo {
251 explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
252 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
253 explicit CGCapturedStmtInfo(const CapturedStmt &S,
254 CapturedRegionKind K = CR_Default)
255 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
257 RecordDecl::field_iterator Field =
258 S.getCapturedRecordDecl()->field_begin();
259 for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
261 I != E; ++I, ++Field) {
262 if (I->capturesThis())
263 CXXThisFieldDecl = *Field;
264 else if (I->capturesVariable())
265 CaptureFields[I->getCapturedVar()] = *Field;
266 else if (I->capturesVariableByCopy())
267 CaptureFields[I->getCapturedVar()] = *Field;
271 virtual ~CGCapturedStmtInfo();
273 CapturedRegionKind getKind() const { return Kind; }
275 virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
276 // \brief Retrieve the value of the context parameter.
277 virtual llvm::Value *getContextValue() const { return ThisValue; }
279 /// \brief Lookup the captured field decl for a variable.
280 virtual const FieldDecl *lookup(const VarDecl *VD) const {
281 return CaptureFields.lookup(VD);
284 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
285 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
287 static bool classof(const CGCapturedStmtInfo *) {
291 /// \brief Emit the captured statement body.
292 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
293 CGF.incrementProfileCounter(S);
297 /// \brief Get the name of the capture helper.
298 virtual StringRef getHelperName() const { return "__captured_stmt"; }
301 /// \brief The kind of captured statement being generated.
302 CapturedRegionKind Kind;
304 /// \brief Keep the map between VarDecl and FieldDecl.
305 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
307 /// \brief The base address of the captured record, passed in as the first
308 /// argument of the parallel region function.
309 llvm::Value *ThisValue;
311 /// \brief Captured 'this' type.
312 FieldDecl *CXXThisFieldDecl;
314 CGCapturedStmtInfo *CapturedStmtInfo;
316 /// \brief RAII for correct setting/restoring of CapturedStmtInfo.
317 class CGCapturedStmtRAII {
319 CodeGenFunction &CGF;
320 CGCapturedStmtInfo *PrevCapturedStmtInfo;
322 CGCapturedStmtRAII(CodeGenFunction &CGF,
323 CGCapturedStmtInfo *NewCapturedStmtInfo)
324 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
325 CGF.CapturedStmtInfo = NewCapturedStmtInfo;
327 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
330 /// An abstract representation of regular/ObjC call/message targets.
331 class AbstractCallee {
332 /// The function declaration of the callee.
333 const Decl *CalleeDecl;
336 AbstractCallee() : CalleeDecl(nullptr) {}
337 AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
338 AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
339 bool hasFunctionDecl() const {
340 return dyn_cast_or_null<FunctionDecl>(CalleeDecl);
342 const Decl *getDecl() const { return CalleeDecl; }
343 unsigned getNumParams() const {
344 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
345 return FD->getNumParams();
346 return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
348 const ParmVarDecl *getParamDecl(unsigned I) const {
349 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
350 return FD->getParamDecl(I);
351 return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
355 /// \brief Sanitizers enabled for this function.
356 SanitizerSet SanOpts;
358 /// \brief True if CodeGen currently emits code implementing sanitizer checks.
359 bool IsSanitizerScope;
361 /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope.
362 class SanitizerScope {
363 CodeGenFunction *CGF;
365 SanitizerScope(CodeGenFunction *CGF);
369 /// In C++, whether we are code generating a thunk. This controls whether we
370 /// should emit cleanups.
373 /// In ARC, whether we should autorelease the return value.
374 bool AutoreleaseResult;
376 /// Whether we processed a Microsoft-style asm block during CodeGen. These can
377 /// potentially set the return value.
380 const FunctionDecl *CurSEHParent = nullptr;
382 /// True if the current function is an outlined SEH helper. This can be a
383 /// finally block or filter expression.
384 bool IsOutlinedSEHHelper;
386 const CodeGen::CGBlockInfo *BlockInfo;
387 llvm::Value *BlockPointer;
389 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
390 FieldDecl *LambdaThisCaptureField;
392 /// \brief A mapping from NRVO variables to the flags used to indicate
393 /// when the NRVO has been applied to this variable.
394 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
396 EHScopeStack EHStack;
397 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
398 llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
400 llvm::Instruction *CurrentFuncletPad = nullptr;
402 class CallLifetimeEnd final : public EHScopeStack::Cleanup {
407 CallLifetimeEnd(Address addr, llvm::Value *size)
408 : Addr(addr.getPointer()), Size(size) {}
410 void Emit(CodeGenFunction &CGF, Flags flags) override {
411 CGF.EmitLifetimeEnd(Size, Addr);
415 /// Header for data within LifetimeExtendedCleanupStack.
416 struct LifetimeExtendedCleanupHeader {
417 /// The size of the following cleanup object.
419 /// The kind of cleanup to push: a value from the CleanupKind enumeration.
422 size_t getSize() const { return Size; }
423 CleanupKind getKind() const { return Kind; }
426 /// i32s containing the indexes of the cleanup destinations.
427 llvm::AllocaInst *NormalCleanupDest;
429 unsigned NextCleanupDestIndex;
431 /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
432 CGBlockInfo *FirstBlockInfo;
434 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
435 llvm::BasicBlock *EHResumeBlock;
437 /// The exception slot. All landing pads write the current exception pointer
438 /// into this alloca.
439 llvm::Value *ExceptionSlot;
441 /// The selector slot. Under the MandatoryCleanup model, all landing pads
442 /// write the current selector value into this alloca.
443 llvm::AllocaInst *EHSelectorSlot;
445 /// A stack of exception code slots. Entering an __except block pushes a slot
446 /// on the stack and leaving pops one. The __exception_code() intrinsic loads
447 /// a value from the top of the stack.
448 SmallVector<Address, 1> SEHCodeSlotStack;
450 /// Value returned by __exception_info intrinsic.
451 llvm::Value *SEHInfo = nullptr;
453 /// Emits a landing pad for the current EH stack.
454 llvm::BasicBlock *EmitLandingPad();
456 llvm::BasicBlock *getInvokeDestImpl();
459 typename DominatingValue<T>::saved_type saveValueInCond(T value) {
460 return DominatingValue<T>::save(*this, value);
464 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
466 SmallVector<llvm::Value*, 8> ObjCEHValueStack;
468 /// A class controlling the emission of a finally block.
470 /// Where the catchall's edge through the cleanup should go.
471 JumpDest RethrowDest;
473 /// A function to call to enter the catch.
474 llvm::Constant *BeginCatchFn;
476 /// An i1 variable indicating whether or not the @finally is
477 /// running for an exception.
478 llvm::AllocaInst *ForEHVar;
480 /// An i8* variable into which the exception pointer to rethrow
482 llvm::AllocaInst *SavedExnVar;
485 void enter(CodeGenFunction &CGF, const Stmt *Finally,
486 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
487 llvm::Constant *rethrowFn);
488 void exit(CodeGenFunction &CGF);
491 /// Returns true inside SEH __try blocks.
492 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
494 /// Returns true while emitting a cleanuppad.
495 bool isCleanupPadScope() const {
496 return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
499 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
500 /// current full-expression. Safe against the possibility that
501 /// we're currently inside a conditionally-evaluated expression.
502 template <class T, class... As>
503 void pushFullExprCleanup(CleanupKind kind, As... A) {
504 // If we're not in a conditional branch, or if none of the
505 // arguments requires saving, then use the unconditional cleanup.
506 if (!isInConditionalBranch())
507 return EHStack.pushCleanup<T>(kind, A...);
509 // Stash values in a tuple so we can guarantee the order of saves.
510 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
511 SavedTuple Saved{saveValueInCond(A)...};
513 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
514 EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
515 initFullExprCleanup();
518 /// \brief Queue a cleanup to be pushed after finishing the current
520 template <class T, class... As>
521 void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
522 assert(!isInConditionalBranch() && "can't defer conditional cleanup");
524 LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
526 size_t OldSize = LifetimeExtendedCleanupStack.size();
527 LifetimeExtendedCleanupStack.resize(
528 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
530 static_assert(sizeof(Header) % alignof(T) == 0,
531 "Cleanup will be allocated on misaligned address");
532 char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
533 new (Buffer) LifetimeExtendedCleanupHeader(Header);
534 new (Buffer + sizeof(Header)) T(A...);
537 /// Set up the last cleaup that was pushed as a conditional
538 /// full-expression cleanup.
539 void initFullExprCleanup();
541 /// PushDestructorCleanup - Push a cleanup to call the
542 /// complete-object destructor of an object of the given type at the
543 /// given address. Does nothing if T is not a C++ class type with a
544 /// non-trivial destructor.
545 void PushDestructorCleanup(QualType T, Address Addr);
547 /// PushDestructorCleanup - Push a cleanup to call the
548 /// complete-object variant of the given destructor on the object at
549 /// the given address.
550 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, Address Addr);
552 /// PopCleanupBlock - Will pop the cleanup entry on the stack and
553 /// process all branch fixups.
554 void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
556 /// DeactivateCleanupBlock - Deactivates the given cleanup block.
557 /// The block cannot be reactivated. Pops it if it's the top of the
560 /// \param DominatingIP - An instruction which is known to
561 /// dominate the current IP (if set) and which lies along
562 /// all paths of execution between the current IP and the
563 /// the point at which the cleanup comes into scope.
564 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
565 llvm::Instruction *DominatingIP);
567 /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
568 /// Cannot be used to resurrect a deactivated cleanup.
570 /// \param DominatingIP - An instruction which is known to
571 /// dominate the current IP (if set) and which lies along
572 /// all paths of execution between the current IP and the
573 /// the point at which the cleanup comes into scope.
574 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
575 llvm::Instruction *DominatingIP);
577 /// \brief Enters a new scope for capturing cleanups, all of which
578 /// will be executed once the scope is exited.
579 class RunCleanupsScope {
580 EHScopeStack::stable_iterator CleanupStackDepth;
581 size_t LifetimeExtendedCleanupStackSize;
582 bool OldDidCallStackSave;
587 RunCleanupsScope(const RunCleanupsScope &) = delete;
588 void operator=(const RunCleanupsScope &) = delete;
591 CodeGenFunction& CGF;
594 /// \brief Enter a new cleanup scope.
595 explicit RunCleanupsScope(CodeGenFunction &CGF)
596 : PerformCleanup(true), CGF(CGF)
598 CleanupStackDepth = CGF.EHStack.stable_begin();
599 LifetimeExtendedCleanupStackSize =
600 CGF.LifetimeExtendedCleanupStack.size();
601 OldDidCallStackSave = CGF.DidCallStackSave;
602 CGF.DidCallStackSave = false;
605 /// \brief Exit this cleanup scope, emitting any accumulated cleanups.
606 ~RunCleanupsScope() {
611 /// \brief Determine whether this scope requires any cleanups.
612 bool requiresCleanups() const {
613 return CGF.EHStack.stable_begin() != CleanupStackDepth;
616 /// \brief Force the emission of cleanups now, instead of waiting
617 /// until this object is destroyed.
618 /// \param ValuesToReload - A list of values that need to be available at
619 /// the insertion point after cleanup emission. If cleanup emission created
620 /// a shared cleanup block, these value pointers will be rewritten.
621 /// Otherwise, they not will be modified.
622 void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) {
623 assert(PerformCleanup && "Already forced cleanup");
624 CGF.DidCallStackSave = OldDidCallStackSave;
625 CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize,
627 PerformCleanup = false;
631 class LexicalScope : public RunCleanupsScope {
633 SmallVector<const LabelDecl*, 4> Labels;
634 LexicalScope *ParentScope;
636 LexicalScope(const LexicalScope &) = delete;
637 void operator=(const LexicalScope &) = delete;
640 /// \brief Enter a new cleanup scope.
641 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
642 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
643 CGF.CurLexicalScope = this;
644 if (CGDebugInfo *DI = CGF.getDebugInfo())
645 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
648 void addLabel(const LabelDecl *label) {
649 assert(PerformCleanup && "adding label to dead scope?");
650 Labels.push_back(label);
653 /// \brief Exit this cleanup scope, emitting any accumulated
656 if (CGDebugInfo *DI = CGF.getDebugInfo())
657 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
659 // If we should perform a cleanup, force them now. Note that
660 // this ends the cleanup scope before rescoping any labels.
661 if (PerformCleanup) {
662 ApplyDebugLocation DL(CGF, Range.getEnd());
667 /// \brief Force the emission of cleanups now, instead of waiting
668 /// until this object is destroyed.
669 void ForceCleanup() {
670 CGF.CurLexicalScope = ParentScope;
671 RunCleanupsScope::ForceCleanup();
677 bool hasLabels() const {
678 return !Labels.empty();
681 void rescopeLabels();
684 typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
686 /// \brief The scope used to remap some variables as private in the OpenMP
687 /// loop body (or other captured region emitted without outlining), and to
688 /// restore old vars back on exit.
689 class OMPPrivateScope : public RunCleanupsScope {
690 DeclMapTy SavedLocals;
691 DeclMapTy SavedPrivates;
694 OMPPrivateScope(const OMPPrivateScope &) = delete;
695 void operator=(const OMPPrivateScope &) = delete;
698 /// \brief Enter a new OpenMP private scope.
699 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
701 /// \brief Registers \a LocalVD variable as a private and apply \a
702 /// PrivateGen function for it to generate corresponding private variable.
703 /// \a PrivateGen returns an address of the generated private variable.
704 /// \return true if the variable is registered as private, false if it has
705 /// been privatized already.
707 addPrivate(const VarDecl *LocalVD,
708 llvm::function_ref<Address()> PrivateGen) {
709 assert(PerformCleanup && "adding private to dead scope");
711 // Only save it once.
712 if (SavedLocals.count(LocalVD)) return false;
714 // Copy the existing local entry to SavedLocals.
715 auto it = CGF.LocalDeclMap.find(LocalVD);
716 if (it != CGF.LocalDeclMap.end()) {
717 SavedLocals.insert({LocalVD, it->second});
719 SavedLocals.insert({LocalVD, Address::invalid()});
722 // Generate the private entry.
723 Address Addr = PrivateGen();
724 QualType VarTy = LocalVD->getType();
725 if (VarTy->isReferenceType()) {
726 Address Temp = CGF.CreateMemTemp(VarTy);
727 CGF.Builder.CreateStore(Addr.getPointer(), Temp);
730 SavedPrivates.insert({LocalVD, Addr});
735 /// \brief Privatizes local variables previously registered as private.
736 /// Registration is separate from the actual privatization to allow
737 /// initializers use values of the original variables, not the private one.
738 /// This is important, for example, if the private variable is a class
739 /// variable initialized by a constructor that references other private
740 /// variables. But at initialization original variables must be used, not
742 /// \return true if at least one variable was privatized, false otherwise.
744 copyInto(SavedPrivates, CGF.LocalDeclMap);
745 SavedPrivates.clear();
746 return !SavedLocals.empty();
749 void ForceCleanup() {
750 RunCleanupsScope::ForceCleanup();
751 copyInto(SavedLocals, CGF.LocalDeclMap);
755 /// \brief Exit scope - all the mapped variables are restored.
761 /// Checks if the global variable is captured in current function.
762 bool isGlobalVarCaptured(const VarDecl *VD) const {
763 return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
767 /// Copy all the entries in the source map over the corresponding
768 /// entries in the destination, which must exist.
769 static void copyInto(const DeclMapTy &src, DeclMapTy &dest) {
770 for (auto &pair : src) {
771 if (!pair.second.isValid()) {
772 dest.erase(pair.first);
776 auto it = dest.find(pair.first);
777 if (it != dest.end()) {
778 it->second = pair.second;
786 /// \brief Takes the old cleanup stack size and emits the cleanup blocks
787 /// that have been added.
789 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
790 std::initializer_list<llvm::Value **> ValuesToReload = {});
792 /// \brief Takes the old cleanup stack size and emits the cleanup blocks
793 /// that have been added, then adds all lifetime-extended cleanups from
794 /// the given position to the stack.
796 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
797 size_t OldLifetimeExtendedStackSize,
798 std::initializer_list<llvm::Value **> ValuesToReload = {});
800 void ResolveBranchFixups(llvm::BasicBlock *Target);
802 /// The given basic block lies in the current EH scope, but may be a
803 /// target of a potentially scope-crossing jump; get a stable handle
804 /// to which we can perform this jump later.
805 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
806 return JumpDest(Target,
807 EHStack.getInnermostNormalCleanup(),
808 NextCleanupDestIndex++);
811 /// The given basic block lies in the current EH scope, but may be a
812 /// target of a potentially scope-crossing jump; get a stable handle
813 /// to which we can perform this jump later.
814 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
815 return getJumpDestInCurrentScope(createBasicBlock(Name));
818 /// EmitBranchThroughCleanup - Emit a branch from the current insert
819 /// block through the normal cleanup handling code (if any) and then
821 void EmitBranchThroughCleanup(JumpDest Dest);
823 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
824 /// specified destination obviously has no cleanups to run. 'false' is always
825 /// a conservatively correct answer for this method.
826 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
828 /// popCatchScope - Pops the catch scope at the top of the EHScope
829 /// stack, emitting any required code (other than the catch handlers
831 void popCatchScope();
833 llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
834 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
835 llvm::BasicBlock *getMSVCDispatchBlock(EHScopeStack::stable_iterator scope);
837 /// An object to manage conditionally-evaluated expressions.
838 class ConditionalEvaluation {
839 llvm::BasicBlock *StartBB;
842 ConditionalEvaluation(CodeGenFunction &CGF)
843 : StartBB(CGF.Builder.GetInsertBlock()) {}
845 void begin(CodeGenFunction &CGF) {
846 assert(CGF.OutermostConditional != this);
847 if (!CGF.OutermostConditional)
848 CGF.OutermostConditional = this;
851 void end(CodeGenFunction &CGF) {
852 assert(CGF.OutermostConditional != nullptr);
853 if (CGF.OutermostConditional == this)
854 CGF.OutermostConditional = nullptr;
857 /// Returns a block which will be executed prior to each
858 /// evaluation of the conditional code.
859 llvm::BasicBlock *getStartingBlock() const {
864 /// isInConditionalBranch - Return true if we're currently emitting
865 /// one branch or the other of a conditional expression.
866 bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
868 void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
869 assert(isInConditionalBranch());
870 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
871 auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
872 store->setAlignment(addr.getAlignment().getQuantity());
875 /// An RAII object to record that we're evaluating a statement
877 class StmtExprEvaluation {
878 CodeGenFunction &CGF;
880 /// We have to save the outermost conditional: cleanups in a
881 /// statement expression aren't conditional just because the
883 ConditionalEvaluation *SavedOutermostConditional;
886 StmtExprEvaluation(CodeGenFunction &CGF)
887 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
888 CGF.OutermostConditional = nullptr;
891 ~StmtExprEvaluation() {
892 CGF.OutermostConditional = SavedOutermostConditional;
893 CGF.EnsureInsertPoint();
897 /// An object which temporarily prevents a value from being
898 /// destroyed by aggressive peephole optimizations that assume that
899 /// all uses of a value have been realized in the IR.
900 class PeepholeProtection {
901 llvm::Instruction *Inst;
902 friend class CodeGenFunction;
905 PeepholeProtection() : Inst(nullptr) {}
908 /// A non-RAII class containing all the information about a bound
909 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
910 /// this which makes individual mappings very simple; using this
911 /// class directly is useful when you have a variable number of
912 /// opaque values or don't want the RAII functionality for some
914 class OpaqueValueMappingData {
915 const OpaqueValueExpr *OpaqueValue;
917 CodeGenFunction::PeepholeProtection Protection;
919 OpaqueValueMappingData(const OpaqueValueExpr *ov,
921 : OpaqueValue(ov), BoundLValue(boundLValue) {}
923 OpaqueValueMappingData() : OpaqueValue(nullptr) {}
925 static bool shouldBindAsLValue(const Expr *expr) {
926 // gl-values should be bound as l-values for obvious reasons.
927 // Records should be bound as l-values because IR generation
928 // always keeps them in memory. Expressions of function type
929 // act exactly like l-values but are formally required to be
931 return expr->isGLValue() ||
932 expr->getType()->isFunctionType() ||
933 hasAggregateEvaluationKind(expr->getType());
936 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
937 const OpaqueValueExpr *ov,
939 if (shouldBindAsLValue(ov))
940 return bind(CGF, ov, CGF.EmitLValue(e));
941 return bind(CGF, ov, CGF.EmitAnyExpr(e));
944 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
945 const OpaqueValueExpr *ov,
947 assert(shouldBindAsLValue(ov));
948 CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
949 return OpaqueValueMappingData(ov, true);
952 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
953 const OpaqueValueExpr *ov,
955 assert(!shouldBindAsLValue(ov));
956 CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
958 OpaqueValueMappingData data(ov, false);
960 // Work around an extremely aggressive peephole optimization in
961 // EmitScalarConversion which assumes that all other uses of a
963 data.Protection = CGF.protectFromPeepholes(rv);
968 bool isValid() const { return OpaqueValue != nullptr; }
969 void clear() { OpaqueValue = nullptr; }
971 void unbind(CodeGenFunction &CGF) {
972 assert(OpaqueValue && "no data to unbind!");
975 CGF.OpaqueLValues.erase(OpaqueValue);
977 CGF.OpaqueRValues.erase(OpaqueValue);
978 CGF.unprotectFromPeepholes(Protection);
983 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
984 class OpaqueValueMapping {
985 CodeGenFunction &CGF;
986 OpaqueValueMappingData Data;
989 static bool shouldBindAsLValue(const Expr *expr) {
990 return OpaqueValueMappingData::shouldBindAsLValue(expr);
993 /// Build the opaque value mapping for the given conditional
994 /// operator if it's the GNU ?: extension. This is a common
995 /// enough pattern that the convenience operator is really
998 OpaqueValueMapping(CodeGenFunction &CGF,
999 const AbstractConditionalOperator *op) : CGF(CGF) {
1000 if (isa<ConditionalOperator>(op))
1001 // Leave Data empty.
1004 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
1005 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
1009 /// Build the opaque value mapping for an OpaqueValueExpr whose source
1010 /// expression is set to the expression the OVE represents.
1011 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
1014 assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
1015 "for OVE with no source expression");
1016 Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
1020 OpaqueValueMapping(CodeGenFunction &CGF,
1021 const OpaqueValueExpr *opaqueValue,
1023 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
1026 OpaqueValueMapping(CodeGenFunction &CGF,
1027 const OpaqueValueExpr *opaqueValue,
1029 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
1037 ~OpaqueValueMapping() {
1038 if (Data.isValid()) Data.unbind(CGF);
1043 CGDebugInfo *DebugInfo;
1044 bool DisableDebugInfo;
1046 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
1047 /// calling llvm.stacksave for multiple VLAs in the same scope.
1048 bool DidCallStackSave;
1050 /// IndirectBranch - The first time an indirect goto is seen we create a block
1051 /// with an indirect branch. Every time we see the address of a label taken,
1052 /// we add the label to the indirect goto. Every subsequent indirect goto is
1053 /// codegen'd as a jump to the IndirectBranch's basic block.
1054 llvm::IndirectBrInst *IndirectBranch;
1056 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
1058 DeclMapTy LocalDeclMap;
1060 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
1061 /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
1063 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
1066 /// Track escaped local variables with auto storage. Used during SEH
1067 /// outlining to produce a call to llvm.localescape.
1068 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
1070 /// LabelMap - This keeps track of the LLVM basic block for each C label.
1071 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
1073 // BreakContinueStack - This keeps track of where break and continue
1074 // statements should jump to.
1075 struct BreakContinue {
1076 BreakContinue(JumpDest Break, JumpDest Continue)
1077 : BreakBlock(Break), ContinueBlock(Continue) {}
1079 JumpDest BreakBlock;
1080 JumpDest ContinueBlock;
1082 SmallVector<BreakContinue, 8> BreakContinueStack;
1084 /// Handles cancellation exit points in OpenMP-related constructs.
1085 class OpenMPCancelExitStack {
1086 /// Tracks cancellation exit point and join point for cancel-related exit
1087 /// and normal exit.
1089 CancelExit() = default;
1090 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
1092 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
1093 OpenMPDirectiveKind Kind = OMPD_unknown;
1094 /// true if the exit block has been emitted already by the special
1095 /// emitExit() call, false if the default codegen is used.
1096 bool HasBeenEmitted = false;
1101 SmallVector<CancelExit, 8> Stack;
1104 OpenMPCancelExitStack() : Stack(1) {}
1105 ~OpenMPCancelExitStack() = default;
1106 /// Fetches the exit block for the current OpenMP construct.
1107 JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
1108 /// Emits exit block with special codegen procedure specific for the related
1109 /// OpenMP construct + emits code for normal construct cleanup.
1110 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1111 const llvm::function_ref<void(CodeGenFunction &)> &CodeGen) {
1112 if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
1113 assert(CGF.getOMPCancelDestination(Kind).isValid());
1114 assert(CGF.HaveInsertPoint());
1115 assert(!Stack.back().HasBeenEmitted);
1116 auto IP = CGF.Builder.saveAndClearIP();
1117 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1119 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1120 CGF.Builder.restoreIP(IP);
1121 Stack.back().HasBeenEmitted = true;
1125 /// Enter the cancel supporting \a Kind construct.
1126 /// \param Kind OpenMP directive that supports cancel constructs.
1127 /// \param HasCancel true, if the construct has inner cancel directive,
1128 /// false otherwise.
1129 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
1130 Stack.push_back({Kind,
1131 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
1133 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
1136 /// Emits default exit point for the cancel construct (if the special one
1137 /// has not be used) + join point for cancel/normal exits.
1138 void exit(CodeGenFunction &CGF) {
1139 if (getExitBlock().isValid()) {
1140 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
1141 bool HaveIP = CGF.HaveInsertPoint();
1142 if (!Stack.back().HasBeenEmitted) {
1144 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1145 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1146 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1148 CGF.EmitBlock(Stack.back().ContBlock.getBlock());
1150 CGF.Builder.CreateUnreachable();
1151 CGF.Builder.ClearInsertionPoint();
1157 OpenMPCancelExitStack OMPCancelStack;
1159 /// Controls insertion of cancellation exit blocks in worksharing constructs.
1160 class OMPCancelStackRAII {
1161 CodeGenFunction &CGF;
1164 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1167 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
1169 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
1174 /// Calculate branch weights appropriate for PGO data
1175 llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
1176 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
1177 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1178 uint64_t LoopCount);
1181 /// Increment the profiler's counter for the given statement by \p StepV.
1182 /// If \p StepV is null, the default increment is 1.
1183 void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
1184 if (CGM.getCodeGenOpts().hasProfileClangInstr())
1185 PGO.emitCounterIncrement(Builder, S, StepV);
1186 PGO.setCurrentStmt(S);
1189 /// Get the profiler's count for the given statement.
1190 uint64_t getProfileCount(const Stmt *S) {
1191 Optional<uint64_t> Count = PGO.getStmtCount(S);
1192 if (!Count.hasValue())
1197 /// Set the profiler's current count.
1198 void setCurrentProfileCount(uint64_t Count) {
1199 PGO.setCurrentRegionCount(Count);
1202 /// Get the profiler's current count. This is generally the count for the most
1203 /// recently incremented counter.
1204 uint64_t getCurrentProfileCount() {
1205 return PGO.getCurrentRegionCount();
1210 /// SwitchInsn - This is nearest current switch instruction. It is null if
1211 /// current context is not in a switch.
1212 llvm::SwitchInst *SwitchInsn;
1213 /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1214 SmallVector<uint64_t, 16> *SwitchWeights;
1216 /// CaseRangeBlock - This block holds if condition check for last case
1217 /// statement range in current switch instruction.
1218 llvm::BasicBlock *CaseRangeBlock;
1220 /// OpaqueLValues - Keeps track of the current set of opaque value
1222 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1223 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1225 // VLASizeMap - This keeps track of the associated size for each VLA type.
1226 // We track this by the size expression rather than the type itself because
1227 // in certain situations, like a const qualifier applied to an VLA typedef,
1228 // multiple VLA types can share the same size expression.
1229 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1230 // enter/leave scopes.
1231 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
1233 /// A block containing a single 'unreachable' instruction. Created
1234 /// lazily by getUnreachableBlock().
1235 llvm::BasicBlock *UnreachableBlock;
1237 /// Counts of the number return expressions in the function.
1238 unsigned NumReturnExprs;
1240 /// Count the number of simple (constant) return expressions in the function.
1241 unsigned NumSimpleReturnExprs;
1243 /// The last regular (non-return) debug location (breakpoint) in the function.
1244 SourceLocation LastStopPoint;
1247 /// A scope within which we are constructing the fields of an object which
1248 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1249 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1250 class FieldConstructionScope {
1252 FieldConstructionScope(CodeGenFunction &CGF, Address This)
1253 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1254 CGF.CXXDefaultInitExprThis = This;
1256 ~FieldConstructionScope() {
1257 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1261 CodeGenFunction &CGF;
1262 Address OldCXXDefaultInitExprThis;
1265 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1266 /// is overridden to be the object under construction.
1267 class CXXDefaultInitExprScope {
1269 CXXDefaultInitExprScope(CodeGenFunction &CGF)
1270 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1271 OldCXXThisAlignment(CGF.CXXThisAlignment) {
1272 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
1273 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
1275 ~CXXDefaultInitExprScope() {
1276 CGF.CXXThisValue = OldCXXThisValue;
1277 CGF.CXXThisAlignment = OldCXXThisAlignment;
1281 CodeGenFunction &CGF;
1282 llvm::Value *OldCXXThisValue;
1283 CharUnits OldCXXThisAlignment;
1286 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1287 /// current loop index is overridden.
1288 class ArrayInitLoopExprScope {
1290 ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
1291 : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
1292 CGF.ArrayInitIndex = Index;
1294 ~ArrayInitLoopExprScope() {
1295 CGF.ArrayInitIndex = OldArrayInitIndex;
1299 CodeGenFunction &CGF;
1300 llvm::Value *OldArrayInitIndex;
1303 class InlinedInheritingConstructorScope {
1305 InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
1306 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1307 OldCurCodeDecl(CGF.CurCodeDecl),
1308 OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1309 OldCXXABIThisValue(CGF.CXXABIThisValue),
1310 OldCXXThisValue(CGF.CXXThisValue),
1311 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1312 OldCXXThisAlignment(CGF.CXXThisAlignment),
1313 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1314 OldCXXInheritedCtorInitExprArgs(
1315 std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1317 CGF.CurFuncDecl = CGF.CurCodeDecl =
1318 cast<CXXConstructorDecl>(GD.getDecl());
1319 CGF.CXXABIThisDecl = nullptr;
1320 CGF.CXXABIThisValue = nullptr;
1321 CGF.CXXThisValue = nullptr;
1322 CGF.CXXABIThisAlignment = CharUnits();
1323 CGF.CXXThisAlignment = CharUnits();
1324 CGF.ReturnValue = Address::invalid();
1325 CGF.FnRetTy = QualType();
1326 CGF.CXXInheritedCtorInitExprArgs.clear();
1328 ~InlinedInheritingConstructorScope() {
1329 CGF.CurGD = OldCurGD;
1330 CGF.CurFuncDecl = OldCurFuncDecl;
1331 CGF.CurCodeDecl = OldCurCodeDecl;
1332 CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1333 CGF.CXXABIThisValue = OldCXXABIThisValue;
1334 CGF.CXXThisValue = OldCXXThisValue;
1335 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1336 CGF.CXXThisAlignment = OldCXXThisAlignment;
1337 CGF.ReturnValue = OldReturnValue;
1338 CGF.FnRetTy = OldFnRetTy;
1339 CGF.CXXInheritedCtorInitExprArgs =
1340 std::move(OldCXXInheritedCtorInitExprArgs);
1344 CodeGenFunction &CGF;
1345 GlobalDecl OldCurGD;
1346 const Decl *OldCurFuncDecl;
1347 const Decl *OldCurCodeDecl;
1348 ImplicitParamDecl *OldCXXABIThisDecl;
1349 llvm::Value *OldCXXABIThisValue;
1350 llvm::Value *OldCXXThisValue;
1351 CharUnits OldCXXABIThisAlignment;
1352 CharUnits OldCXXThisAlignment;
1353 Address OldReturnValue;
1354 QualType OldFnRetTy;
1355 CallArgList OldCXXInheritedCtorInitExprArgs;
1359 /// CXXThisDecl - When generating code for a C++ member function,
1360 /// this will hold the implicit 'this' declaration.
1361 ImplicitParamDecl *CXXABIThisDecl;
1362 llvm::Value *CXXABIThisValue;
1363 llvm::Value *CXXThisValue;
1364 CharUnits CXXABIThisAlignment;
1365 CharUnits CXXThisAlignment;
1367 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1368 /// this expression.
1369 Address CXXDefaultInitExprThis = Address::invalid();
1371 /// The current array initialization index when evaluating an
1372 /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
1373 llvm::Value *ArrayInitIndex = nullptr;
1375 /// The values of function arguments to use when evaluating
1376 /// CXXInheritedCtorInitExprs within this context.
1377 CallArgList CXXInheritedCtorInitExprArgs;
1379 /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1380 /// destructor, this will hold the implicit argument (e.g. VTT).
1381 ImplicitParamDecl *CXXStructorImplicitParamDecl;
1382 llvm::Value *CXXStructorImplicitParamValue;
1384 /// OutermostConditional - Points to the outermost active
1385 /// conditional control. This is used so that we know if a
1386 /// temporary should be destroyed conditionally.
1387 ConditionalEvaluation *OutermostConditional;
1389 /// The current lexical scope.
1390 LexicalScope *CurLexicalScope;
1392 /// The current source location that should be used for exception
1394 SourceLocation CurEHLocation;
1396 /// BlockByrefInfos - For each __block variable, contains
1397 /// information about the layout of the variable.
1398 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
1400 /// Used by -fsanitize=nullability-return to determine whether the return
1401 /// value can be checked.
1402 llvm::Value *RetValNullabilityPrecondition = nullptr;
1404 /// Check if -fsanitize=nullability-return instrumentation is required for
1406 bool requiresReturnValueNullabilityCheck() const {
1407 return RetValNullabilityPrecondition;
1410 llvm::BasicBlock *TerminateLandingPad;
1411 llvm::BasicBlock *TerminateHandler;
1412 llvm::BasicBlock *TrapBB;
1414 /// True if we need emit the life-time markers.
1415 const bool ShouldEmitLifetimeMarkers;
1417 /// Add OpenCL kernel arg metadata and the kernel attribute meatadata to
1418 /// the function metadata.
1419 void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
1420 llvm::Function *Fn);
1423 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
1426 CodeGenTypes &getTypes() const { return CGM.getTypes(); }
1427 ASTContext &getContext() const { return CGM.getContext(); }
1428 CGDebugInfo *getDebugInfo() {
1429 if (DisableDebugInfo)
1433 void disableDebugInfo() { DisableDebugInfo = true; }
1434 void enableDebugInfo() { DisableDebugInfo = false; }
1436 bool shouldUseFusedARCCalls() {
1437 return CGM.getCodeGenOpts().OptimizationLevel == 0;
1440 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
1442 /// Returns a pointer to the function's exception object and selector slot,
1443 /// which is assigned in every landing pad.
1444 Address getExceptionSlot();
1445 Address getEHSelectorSlot();
1447 /// Returns the contents of the function's exception object and selector
1449 llvm::Value *getExceptionFromSlot();
1450 llvm::Value *getSelectorFromSlot();
1452 Address getNormalCleanupDestSlot();
1454 llvm::BasicBlock *getUnreachableBlock() {
1455 if (!UnreachableBlock) {
1456 UnreachableBlock = createBasicBlock("unreachable");
1457 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
1459 return UnreachableBlock;
1462 llvm::BasicBlock *getInvokeDest() {
1463 if (!EHStack.requiresLandingPad()) return nullptr;
1464 return getInvokeDestImpl();
1467 bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
1469 const TargetInfo &getTarget() const { return Target; }
1470 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
1472 //===--------------------------------------------------------------------===//
1474 //===--------------------------------------------------------------------===//
1476 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
1478 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1479 Address arrayEndPointer,
1480 QualType elementType,
1481 CharUnits elementAlignment,
1482 Destroyer *destroyer);
1483 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1484 llvm::Value *arrayEnd,
1485 QualType elementType,
1486 CharUnits elementAlignment,
1487 Destroyer *destroyer);
1489 void pushDestroy(QualType::DestructionKind dtorKind,
1490 Address addr, QualType type);
1491 void pushEHDestroy(QualType::DestructionKind dtorKind,
1492 Address addr, QualType type);
1493 void pushDestroy(CleanupKind kind, Address addr, QualType type,
1494 Destroyer *destroyer, bool useEHCleanupForArray);
1495 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
1496 QualType type, Destroyer *destroyer,
1497 bool useEHCleanupForArray);
1498 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1499 llvm::Value *CompletePtr,
1500 QualType ElementType);
1501 void pushStackRestore(CleanupKind kind, Address SPMem);
1502 void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
1503 bool useEHCleanupForArray);
1504 llvm::Function *generateDestroyHelper(Address addr, QualType type,
1505 Destroyer *destroyer,
1506 bool useEHCleanupForArray,
1508 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
1509 QualType elementType, CharUnits elementAlign,
1510 Destroyer *destroyer,
1511 bool checkZeroLength, bool useEHCleanup);
1513 Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
1515 /// Determines whether an EH cleanup is required to destroy a type
1516 /// with the given destruction kind.
1517 bool needsEHCleanup(QualType::DestructionKind kind) {
1519 case QualType::DK_none:
1521 case QualType::DK_cxx_destructor:
1522 case QualType::DK_objc_weak_lifetime:
1523 return getLangOpts().Exceptions;
1524 case QualType::DK_objc_strong_lifetime:
1525 return getLangOpts().Exceptions &&
1526 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1528 llvm_unreachable("bad destruction kind");
1531 CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1532 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1535 //===--------------------------------------------------------------------===//
1537 //===--------------------------------------------------------------------===//
1539 void GenerateObjCMethod(const ObjCMethodDecl *OMD);
1541 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
1543 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
1544 void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1545 const ObjCPropertyImplDecl *PID);
1546 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1547 const ObjCPropertyImplDecl *propImpl,
1548 const ObjCMethodDecl *GetterMothodDecl,
1549 llvm::Constant *AtomicHelperFn);
1551 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1552 ObjCMethodDecl *MD, bool ctor);
1554 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1555 /// for the given property.
1556 void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1557 const ObjCPropertyImplDecl *PID);
1558 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1559 const ObjCPropertyImplDecl *propImpl,
1560 llvm::Constant *AtomicHelperFn);
1562 //===--------------------------------------------------------------------===//
1564 //===--------------------------------------------------------------------===//
1566 llvm::Value *EmitBlockLiteral(const BlockExpr *);
1567 static void destroyBlockInfos(CGBlockInfo *info);
1569 llvm::Function *GenerateBlockFunction(GlobalDecl GD,
1570 const CGBlockInfo &Info,
1571 const DeclMapTy &ldm,
1572 bool IsLambdaConversionToBlock);
1574 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1575 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
1576 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
1577 const ObjCPropertyImplDecl *PID);
1578 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
1579 const ObjCPropertyImplDecl *PID);
1580 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
1582 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
1584 class AutoVarEmission;
1586 void emitByrefStructureInit(const AutoVarEmission &emission);
1587 void enterByrefCleanup(const AutoVarEmission &emission);
1589 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
1592 Address LoadBlockStruct();
1593 Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
1595 /// BuildBlockByrefAddress - Computes the location of the
1596 /// data in a variable which is declared as __block.
1597 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
1598 bool followForward = true);
1599 Address emitBlockByrefAddress(Address baseAddr,
1600 const BlockByrefInfo &info,
1602 const llvm::Twine &name);
1604 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
1606 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
1608 void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1609 const CGFunctionInfo &FnInfo);
1610 /// \brief Emit code for the start of a function.
1611 /// \param Loc The location to be associated with the function.
1612 /// \param StartLoc The location of the function body.
1613 void StartFunction(GlobalDecl GD,
1616 const CGFunctionInfo &FnInfo,
1617 const FunctionArgList &Args,
1618 SourceLocation Loc = SourceLocation(),
1619 SourceLocation StartLoc = SourceLocation());
1621 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
1623 void EmitConstructorBody(FunctionArgList &Args);
1624 void EmitDestructorBody(FunctionArgList &Args);
1625 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
1626 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
1627 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
1629 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
1630 CallArgList &CallArgs);
1631 void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
1632 void EmitLambdaBlockInvokeBody();
1633 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
1634 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
1635 void EmitAsanPrologueOrEpilogue(bool Prologue);
1637 /// \brief Emit the unified return block, trying to avoid its emission when
1639 /// \return The debug location of the user written return statement if the
1640 /// return block is is avoided.
1641 llvm::DebugLoc EmitReturnBlock();
1643 /// FinishFunction - Complete IR generation of the current function. It is
1644 /// legal to call this function even if there is no current insertion point.
1645 void FinishFunction(SourceLocation EndLoc=SourceLocation());
1647 void StartThunk(llvm::Function *Fn, GlobalDecl GD,
1648 const CGFunctionInfo &FnInfo);
1650 void EmitCallAndReturnForThunk(llvm::Constant *Callee,
1651 const ThunkInfo *Thunk);
1655 /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
1656 void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
1657 llvm::Value *Callee);
1659 /// Generate a thunk for the given method.
1660 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1661 GlobalDecl GD, const ThunkInfo &Thunk);
1663 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
1664 const CGFunctionInfo &FnInfo,
1665 GlobalDecl GD, const ThunkInfo &Thunk);
1667 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1668 FunctionArgList &Args);
1670 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
1672 /// Struct with all informations about dynamic [sub]class needed to set vptr.
1675 const CXXRecordDecl *NearestVBase;
1676 CharUnits OffsetFromNearestVBase;
1677 const CXXRecordDecl *VTableClass;
1680 /// Initialize the vtable pointer of the given subobject.
1681 void InitializeVTablePointer(const VPtr &vptr);
1683 typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
1685 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1686 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
1688 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
1689 CharUnits OffsetFromNearestVBase,
1690 bool BaseIsNonVirtualPrimaryBase,
1691 const CXXRecordDecl *VTableClass,
1692 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
1694 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1696 /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1698 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
1699 const CXXRecordDecl *VTableClass);
1701 enum CFITypeCheckKind {
1705 CFITCK_UnrelatedCast,
1709 /// \brief Derived is the presumed address of an object of type T after a
1710 /// cast. If T is a polymorphic class type, emit a check that the virtual
1711 /// table for Derived belongs to a class derived from T.
1712 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
1713 bool MayBeNull, CFITypeCheckKind TCK,
1714 SourceLocation Loc);
1716 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
1717 /// If vptr CFI is enabled, emit a check that VTable is valid.
1718 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
1719 CFITypeCheckKind TCK, SourceLocation Loc);
1721 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
1722 /// RD using llvm.type.test.
1723 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
1724 CFITypeCheckKind TCK, SourceLocation Loc);
1726 /// If whole-program virtual table optimization is enabled, emit an assumption
1727 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
1728 /// enabled, emit a check that VTable is a member of RD's type identifier.
1729 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
1730 llvm::Value *VTable, SourceLocation Loc);
1732 /// Returns whether we should perform a type checked load when loading a
1733 /// virtual function for virtual calls to members of RD. This is generally
1734 /// true when both vcall CFI and whole-program-vtables are enabled.
1735 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
1737 /// Emit a type checked load from the given vtable.
1738 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
1739 uint64_t VTableByteOffset);
1741 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
1742 /// expr can be devirtualized.
1743 bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
1744 const CXXMethodDecl *MD);
1746 /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1747 /// given phase of destruction for a destructor. The end result
1748 /// should call destructors on members and base classes in reverse
1749 /// order of their construction.
1750 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1752 /// ShouldInstrumentFunction - Return true if the current function should be
1753 /// instrumented with __cyg_profile_func_* calls
1754 bool ShouldInstrumentFunction();
1756 /// ShouldXRayInstrument - Return true if the current function should be
1757 /// instrumented with XRay nop sleds.
1758 bool ShouldXRayInstrumentFunction() const;
1760 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
1761 /// instrumentation function with the current function and the call site, if
1762 /// function instrumentation is enabled.
1763 void EmitFunctionInstrumentation(const char *Fn);
1765 /// EmitMCountInstrumentation - Emit call to .mcount.
1766 void EmitMCountInstrumentation();
1768 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
1769 /// arguments for the given function. This is also responsible for naming the
1770 /// LLVM function arguments.
1771 void EmitFunctionProlog(const CGFunctionInfo &FI,
1773 const FunctionArgList &Args);
1775 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
1776 /// given temporary.
1777 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
1778 SourceLocation EndLoc);
1780 /// Emit a test that checks if the return value \p RV is nonnull.
1781 void EmitReturnValueCheck(llvm::Value *RV, SourceLocation EndLoc);
1783 /// EmitStartEHSpec - Emit the start of the exception spec.
1784 void EmitStartEHSpec(const Decl *D);
1786 /// EmitEndEHSpec - Emit the end of the exception spec.
1787 void EmitEndEHSpec(const Decl *D);
1789 /// getTerminateLandingPad - Return a landing pad that just calls terminate.
1790 llvm::BasicBlock *getTerminateLandingPad();
1792 /// getTerminateHandler - Return a handler (not a landing pad, just
1793 /// a catch handler) that just calls terminate. This is used when
1794 /// a terminate scope encloses a try.
1795 llvm::BasicBlock *getTerminateHandler();
1797 llvm::Type *ConvertTypeForMem(QualType T);
1798 llvm::Type *ConvertType(QualType T);
1799 llvm::Type *ConvertType(const TypeDecl *T) {
1800 return ConvertType(getContext().getTypeDeclType(T));
1803 /// LoadObjCSelf - Load the value of self. This function is only valid while
1804 /// generating code for an Objective-C method.
1805 llvm::Value *LoadObjCSelf();
1807 /// TypeOfSelfObject - Return type of object that this self represents.
1808 QualType TypeOfSelfObject();
1810 /// hasAggregateLLVMType - Return true if the specified AST type will map into
1811 /// an aggregate LLVM type or is void.
1812 static TypeEvaluationKind getEvaluationKind(QualType T);
1814 static bool hasScalarEvaluationKind(QualType T) {
1815 return getEvaluationKind(T) == TEK_Scalar;
1818 static bool hasAggregateEvaluationKind(QualType T) {
1819 return getEvaluationKind(T) == TEK_Aggregate;
1822 /// createBasicBlock - Create an LLVM basic block.
1823 llvm::BasicBlock *createBasicBlock(const Twine &name = "",
1824 llvm::Function *parent = nullptr,
1825 llvm::BasicBlock *before = nullptr) {
1827 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
1829 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
1833 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
1835 JumpDest getJumpDestForLabel(const LabelDecl *S);
1837 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
1838 /// another basic block, simplify it. This assumes that no other code could
1839 /// potentially reference the basic block.
1840 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
1842 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
1843 /// adding a fall-through branch from the current insert block if
1844 /// necessary. It is legal to call this function even if there is no current
1845 /// insertion point.
1847 /// IsFinished - If true, indicates that the caller has finished emitting
1848 /// branches to the given block and does not expect to emit code into it. This
1849 /// means the block can be ignored if it is unreachable.
1850 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
1852 /// EmitBlockAfterUses - Emit the given block somewhere hopefully
1853 /// near its uses, and leave the insertion point in it.
1854 void EmitBlockAfterUses(llvm::BasicBlock *BB);
1856 /// EmitBranch - Emit a branch to the specified basic block from the current
1857 /// insert block, taking care to avoid creation of branches from dummy
1858 /// blocks. It is legal to call this function even if there is no current
1859 /// insertion point.
1861 /// This function clears the current insertion point. The caller should follow
1862 /// calls to this function with calls to Emit*Block prior to generation new
1864 void EmitBranch(llvm::BasicBlock *Block);
1866 /// HaveInsertPoint - True if an insertion point is defined. If not, this
1867 /// indicates that the current code being emitted is unreachable.
1868 bool HaveInsertPoint() const {
1869 return Builder.GetInsertBlock() != nullptr;
1872 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
1873 /// emitted IR has a place to go. Note that by definition, if this function
1874 /// creates a block then that block is unreachable; callers may do better to
1875 /// detect when no insertion point is defined and simply skip IR generation.
1876 void EnsureInsertPoint() {
1877 if (!HaveInsertPoint())
1878 EmitBlock(createBasicBlock());
1881 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1882 /// specified stmt yet.
1883 void ErrorUnsupported(const Stmt *S, const char *Type);
1885 //===--------------------------------------------------------------------===//
1887 //===--------------------------------------------------------------------===//
1889 LValue MakeAddrLValue(Address Addr, QualType T,
1890 LValueBaseInfo BaseInfo =
1891 LValueBaseInfo(AlignmentSource::Type)) {
1892 return LValue::MakeAddr(Addr, T, getContext(), BaseInfo,
1893 CGM.getTBAAInfo(T));
1896 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
1897 LValueBaseInfo BaseInfo =
1898 LValueBaseInfo(AlignmentSource::Type)) {
1899 return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
1900 BaseInfo, CGM.getTBAAInfo(T));
1903 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
1904 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
1905 CharUnits getNaturalTypeAlignment(QualType T,
1906 LValueBaseInfo *BaseInfo = nullptr,
1907 bool forPointeeType = false);
1908 CharUnits getNaturalPointeeTypeAlignment(QualType T,
1909 LValueBaseInfo *BaseInfo = nullptr);
1911 Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy,
1912 LValueBaseInfo *BaseInfo = nullptr);
1913 LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy);
1915 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
1916 LValueBaseInfo *BaseInfo = nullptr);
1917 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
1919 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
1920 /// block. The caller is responsible for setting an appropriate alignment on
1922 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
1923 const Twine &Name = "tmp");
1924 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
1925 const Twine &Name = "tmp");
1927 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
1928 /// default ABI alignment of the given LLVM type.
1930 /// IMPORTANT NOTE: This is *not* generally the right alignment for
1931 /// any given AST type that happens to have been lowered to the
1932 /// given IR type. This should only ever be used for function-local,
1933 /// IR-driven manipulations like saving and restoring a value. Do
1934 /// not hand this address off to arbitrary IRGen routines, and especially
1935 /// do not pass it as an argument to a function that might expect a
1936 /// properly ABI-aligned value.
1937 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
1938 const Twine &Name = "tmp");
1940 /// InitTempAlloca - Provide an initial value for the given alloca which
1941 /// will be observable at all locations in the function.
1943 /// The address should be something that was returned from one of
1944 /// the CreateTempAlloca or CreateMemTemp routines, and the
1945 /// initializer must be valid in the entry block (i.e. it must
1946 /// either be a constant or an argument value).
1947 void InitTempAlloca(Address Alloca, llvm::Value *Value);
1949 /// CreateIRTemp - Create a temporary IR object of the given type, with
1950 /// appropriate alignment. This routine should only be used when an temporary
1951 /// value needs to be stored into an alloca (for example, to avoid explicit
1952 /// PHI construction), but the type is the IR type, not the type appropriate
1953 /// for storing in memory.
1955 /// That is, this is exactly equivalent to CreateMemTemp, but calling
1956 /// ConvertType instead of ConvertTypeForMem.
1957 Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
1959 /// CreateMemTemp - Create a temporary memory object of the given type, with
1960 /// appropriate alignment.
1961 Address CreateMemTemp(QualType T, const Twine &Name = "tmp");
1962 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp");
1964 /// CreateAggTemp - Create a temporary memory object for the given
1966 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
1967 return AggValueSlot::forAddr(CreateMemTemp(T, Name),
1969 AggValueSlot::IsNotDestructed,
1970 AggValueSlot::DoesNotNeedGCBarriers,
1971 AggValueSlot::IsNotAliased);
1974 /// Emit a cast to void* in the appropriate address space.
1975 llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
1977 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1978 /// expression and compare the result against zero, returning an Int1Ty value.
1979 llvm::Value *EvaluateExprAsBool(const Expr *E);
1981 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1982 void EmitIgnoredExpr(const Expr *E);
1984 /// EmitAnyExpr - Emit code to compute the specified expression which can have
1985 /// any type. The result is returned as an RValue struct. If this is an
1986 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1987 /// the result should be returned.
1989 /// \param ignoreResult True if the resulting value isn't used.
1990 RValue EmitAnyExpr(const Expr *E,
1991 AggValueSlot aggSlot = AggValueSlot::ignored(),
1992 bool ignoreResult = false);
1994 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1995 // or the value of the expression, depending on how va_list is defined.
1996 Address EmitVAListRef(const Expr *E);
1998 /// Emit a "reference" to a __builtin_ms_va_list; this is
1999 /// always the value of the expression, because a __builtin_ms_va_list is a
2000 /// pointer to a char.
2001 Address EmitMSVAListRef(const Expr *E);
2003 /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
2004 /// always be accessible even if no aggregate location is provided.
2005 RValue EmitAnyExprToTemp(const Expr *E);
2007 /// EmitAnyExprToMem - Emits the code necessary to evaluate an
2008 /// arbitrary expression into the given memory location.
2009 void EmitAnyExprToMem(const Expr *E, Address Location,
2010 Qualifiers Quals, bool IsInitializer);
2012 void EmitAnyExprToExn(const Expr *E, Address Addr);
2014 /// EmitExprAsInit - Emits the code necessary to initialize a
2015 /// location in memory with the given initializer.
2016 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2017 bool capturedByInit);
2019 /// hasVolatileMember - returns true if aggregate type has a volatile
2021 bool hasVolatileMember(QualType T) {
2022 if (const RecordType *RT = T->getAs<RecordType>()) {
2023 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2024 return RD->hasVolatileMember();
2028 /// EmitAggregateCopy - Emit an aggregate assignment.
2030 /// The difference to EmitAggregateCopy is that tail padding is not copied.
2031 /// This is required for correctness when assigning non-POD structures in C++.
2032 void EmitAggregateAssign(Address DestPtr, Address SrcPtr,
2034 bool IsVolatile = hasVolatileMember(EltTy);
2035 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true);
2038 void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr,
2039 QualType DestTy, QualType SrcTy) {
2040 EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
2041 /*IsAssignment=*/false);
2044 /// EmitAggregateCopy - Emit an aggregate copy.
2046 /// \param isVolatile - True iff either the source or the destination is
2048 /// \param isAssignment - If false, allow padding to be copied. This often
2049 /// yields more efficient.
2050 void EmitAggregateCopy(Address DestPtr, Address SrcPtr,
2051 QualType EltTy, bool isVolatile=false,
2052 bool isAssignment = false);
2054 /// GetAddrOfLocalVar - Return the address of a local variable.
2055 Address GetAddrOfLocalVar(const VarDecl *VD) {
2056 auto it = LocalDeclMap.find(VD);
2057 assert(it != LocalDeclMap.end() &&
2058 "Invalid argument to GetAddrOfLocalVar(), no decl!");
2062 /// getOpaqueLValueMapping - Given an opaque value expression (which
2063 /// must be mapped to an l-value), return its mapping.
2064 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
2065 assert(OpaqueValueMapping::shouldBindAsLValue(e));
2067 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
2068 it = OpaqueLValues.find(e);
2069 assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
2073 /// getOpaqueRValueMapping - Given an opaque value expression (which
2074 /// must be mapped to an r-value), return its mapping.
2075 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
2076 assert(!OpaqueValueMapping::shouldBindAsLValue(e));
2078 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
2079 it = OpaqueRValues.find(e);
2080 assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
2084 /// Get the index of the current ArrayInitLoopExpr, if any.
2085 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2087 /// getAccessedFieldNo - Given an encoded value and a result number, return
2088 /// the input field number being accessed.
2089 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2091 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
2092 llvm::BasicBlock *GetIndirectGotoBlock();
2094 /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
2095 static bool IsWrappedCXXThis(const Expr *E);
2097 /// EmitNullInitialization - Generate code to set a value of the given type to
2098 /// null, If the type contains data member pointers, they will be initialized
2099 /// to -1 in accordance with the Itanium C++ ABI.
2100 void EmitNullInitialization(Address DestPtr, QualType Ty);
2102 /// Emits a call to an LLVM variable-argument intrinsic, either
2103 /// \c llvm.va_start or \c llvm.va_end.
2104 /// \param ArgValue A reference to the \c va_list as emitted by either
2105 /// \c EmitVAListRef or \c EmitMSVAListRef.
2106 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2107 /// calls \c llvm.va_end.
2108 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2110 /// Generate code to get an argument from the passed in pointer
2111 /// and update it accordingly.
2112 /// \param VE The \c VAArgExpr for which to generate code.
2113 /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2114 /// either \c EmitVAListRef or \c EmitMSVAListRef.
2115 /// \returns A pointer to the argument.
2116 // FIXME: We should be able to get rid of this method and use the va_arg
2117 // instruction in LLVM instead once it works well enough.
2118 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
2120 /// emitArrayLength - Compute the length of an array, even if it's a
2121 /// VLA, and drill down to the base element type.
2122 llvm::Value *emitArrayLength(const ArrayType *arrayType,
2126 /// EmitVLASize - Capture all the sizes for the VLA expressions in
2127 /// the given variably-modified type and store them in the VLASizeMap.
2129 /// This function can be called with a null (unreachable) insert point.
2130 void EmitVariablyModifiedType(QualType Ty);
2132 /// getVLASize - Returns an LLVM value that corresponds to the size,
2133 /// in non-variably-sized elements, of a variable length array type,
2134 /// plus that largest non-variably-sized element type. Assumes that
2135 /// the type has already been emitted with EmitVariablyModifiedType.
2136 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
2137 std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
2139 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2140 /// generating code for an C++ member function.
2141 llvm::Value *LoadCXXThis() {
2142 assert(CXXThisValue && "no 'this' value for this function");
2143 return CXXThisValue;
2145 Address LoadCXXThisAddress();
2147 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2149 // FIXME: Every place that calls LoadCXXVTT is something
2150 // that needs to be abstracted properly.
2151 llvm::Value *LoadCXXVTT() {
2152 assert(CXXStructorImplicitParamValue && "no VTT value for this function");
2153 return CXXStructorImplicitParamValue;
2156 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
2157 /// complete class to the given direct base.
2159 GetAddressOfDirectBaseInCompleteClass(Address Value,
2160 const CXXRecordDecl *Derived,
2161 const CXXRecordDecl *Base,
2162 bool BaseIsVirtual);
2164 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2166 /// GetAddressOfBaseClass - This function will add the necessary delta to the
2167 /// load of 'this' and returns address of the base class.
2168 Address GetAddressOfBaseClass(Address Value,
2169 const CXXRecordDecl *Derived,
2170 CastExpr::path_const_iterator PathBegin,
2171 CastExpr::path_const_iterator PathEnd,
2172 bool NullCheckValue, SourceLocation Loc);
2174 Address GetAddressOfDerivedClass(Address Value,
2175 const CXXRecordDecl *Derived,
2176 CastExpr::path_const_iterator PathBegin,
2177 CastExpr::path_const_iterator PathEnd,
2178 bool NullCheckValue);
2180 /// GetVTTParameter - Return the VTT parameter that should be passed to a
2181 /// base constructor/destructor with virtual bases.
2182 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2183 /// to ItaniumCXXABI.cpp together with all the references to VTT.
2184 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2187 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2188 CXXCtorType CtorType,
2189 const FunctionArgList &Args,
2190 SourceLocation Loc);
2191 // It's important not to confuse this and the previous function. Delegating
2192 // constructors are the C++0x feature. The constructor delegate optimization
2193 // is used to reduce duplication in the base and complete consturctors where
2194 // they are substantially the same.
2195 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2196 const FunctionArgList &Args);
2198 /// Emit a call to an inheriting constructor (that is, one that invokes a
2199 /// constructor inherited from a base class) by inlining its definition. This
2200 /// is necessary if the ABI does not support forwarding the arguments to the
2201 /// base class constructor (because they're variadic or similar).
2202 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2203 CXXCtorType CtorType,
2204 bool ForVirtualBase,
2208 /// Emit a call to a constructor inherited from a base class, passing the
2209 /// current constructor's arguments along unmodified (without even making
2211 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
2212 bool ForVirtualBase, Address This,
2213 bool InheritedFromVBase,
2214 const CXXInheritedCtorInitExpr *E);
2216 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2217 bool ForVirtualBase, bool Delegating,
2218 Address This, const CXXConstructExpr *E);
2220 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2221 bool ForVirtualBase, bool Delegating,
2222 Address This, CallArgList &Args);
2224 /// Emit assumption load for all bases. Requires to be be called only on
2225 /// most-derived class and not under construction of the object.
2226 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2228 /// Emit assumption that vptr load == global vtable.
2229 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2231 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2232 Address This, Address Src,
2233 const CXXConstructExpr *E);
2235 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2236 const ArrayType *ArrayTy,
2238 const CXXConstructExpr *E,
2239 bool ZeroInitialization = false);
2241 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2242 llvm::Value *NumElements,
2244 const CXXConstructExpr *E,
2245 bool ZeroInitialization = false);
2247 static Destroyer destroyCXXObject;
2249 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
2250 bool ForVirtualBase, bool Delegating,
2253 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2254 llvm::Type *ElementTy, Address NewPtr,
2255 llvm::Value *NumElements,
2256 llvm::Value *AllocSizeWithoutCookie);
2258 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2261 llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
2262 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2264 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
2265 void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
2267 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
2268 QualType DeleteTy, llvm::Value *NumElements = nullptr,
2269 CharUnits CookieSize = CharUnits());
2271 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
2272 const Expr *Arg, bool IsDelete);
2274 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2275 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2276 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
2278 /// \brief Situations in which we might emit a check for the suitability of a
2279 /// pointer or glvalue.
2280 enum TypeCheckKind {
2281 /// Checking the operand of a load. Must be suitably sized and aligned.
2283 /// Checking the destination of a store. Must be suitably sized and aligned.
2285 /// Checking the bound value in a reference binding. Must be suitably sized
2286 /// and aligned, but is not required to refer to an object (until the
2287 /// reference is used), per core issue 453.
2288 TCK_ReferenceBinding,
2289 /// Checking the object expression in a non-static data member access. Must
2290 /// be an object within its lifetime.
2292 /// Checking the 'this' pointer for a call to a non-static member function.
2293 /// Must be an object within its lifetime.
2295 /// Checking the 'this' pointer for a constructor call.
2296 TCK_ConstructorCall,
2297 /// Checking the operand of a static_cast to a derived pointer type. Must be
2298 /// null or an object within its lifetime.
2299 TCK_DowncastPointer,
2300 /// Checking the operand of a static_cast to a derived reference type. Must
2301 /// be an object within its lifetime.
2302 TCK_DowncastReference,
2303 /// Checking the operand of a cast to a base object. Must be suitably sized
2306 /// Checking the operand of a cast to a virtual base object. Must be an
2307 /// object within its lifetime.
2308 TCK_UpcastToVirtualBase,
2309 /// Checking the value assigned to a _Nonnull pointer. Must not be null.
2313 /// \brief Whether any type-checking sanitizers are enabled. If \c false,
2314 /// calls to EmitTypeCheck can be skipped.
2315 bool sanitizePerformTypeCheck() const;
2317 /// \brief Emit a check that \p V is the address of storage of the
2318 /// appropriate size and alignment for an object of type \p Type.
2319 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
2320 QualType Type, CharUnits Alignment = CharUnits::Zero(),
2321 SanitizerSet SkippedChecks = SanitizerSet());
2323 /// \brief Emit a check that \p Base points into an array object, which
2324 /// we can access at index \p Index. \p Accessed should be \c false if we
2325 /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
2326 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
2327 QualType IndexType, bool Accessed);
2329 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2330 bool isInc, bool isPre);
2331 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
2332 bool isInc, bool isPre);
2334 void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
2335 llvm::Value *OffsetValue = nullptr) {
2336 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2340 /// Converts Location to a DebugLoc, if debug information is enabled.
2341 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
2344 //===--------------------------------------------------------------------===//
2345 // Declaration Emission
2346 //===--------------------------------------------------------------------===//
2348 /// EmitDecl - Emit a declaration.
2350 /// This function can be called with a null (unreachable) insert point.
2351 void EmitDecl(const Decl &D);
2353 /// EmitVarDecl - Emit a local variable declaration.
2355 /// This function can be called with a null (unreachable) insert point.
2356 void EmitVarDecl(const VarDecl &D);
2358 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2359 bool capturedByInit);
2361 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
2362 llvm::Value *Address);
2364 /// \brief Determine whether the given initializer is trivial in the sense
2365 /// that it requires no code to be generated.
2366 bool isTrivialInitializer(const Expr *Init);
2368 /// EmitAutoVarDecl - Emit an auto variable declaration.
2370 /// This function can be called with a null (unreachable) insert point.
2371 void EmitAutoVarDecl(const VarDecl &D);
2373 class AutoVarEmission {
2374 friend class CodeGenFunction;
2376 const VarDecl *Variable;
2378 /// The address of the alloca. Invalid if the variable was emitted
2379 /// as a global constant.
2382 llvm::Value *NRVOFlag;
2384 /// True if the variable is a __block variable.
2387 /// True if the variable is of aggregate type and has a constant
2389 bool IsConstantAggregate;
2391 /// Non-null if we should use lifetime annotations.
2392 llvm::Value *SizeForLifetimeMarkers;
2395 AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {}
2397 AutoVarEmission(const VarDecl &variable)
2398 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
2399 IsByRef(false), IsConstantAggregate(false),
2400 SizeForLifetimeMarkers(nullptr) {}
2402 bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
2405 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
2407 bool useLifetimeMarkers() const {
2408 return SizeForLifetimeMarkers != nullptr;
2410 llvm::Value *getSizeForLifetimeMarkers() const {
2411 assert(useLifetimeMarkers());
2412 return SizeForLifetimeMarkers;
2415 /// Returns the raw, allocated address, which is not necessarily
2416 /// the address of the object itself.
2417 Address getAllocatedAddress() const {
2421 /// Returns the address of the object within this declaration.
2422 /// Note that this does not chase the forwarding pointer for
2424 Address getObjectAddress(CodeGenFunction &CGF) const {
2425 if (!IsByRef) return Addr;
2427 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
2430 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
2431 void EmitAutoVarInit(const AutoVarEmission &emission);
2432 void EmitAutoVarCleanups(const AutoVarEmission &emission);
2433 void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
2434 QualType::DestructionKind dtorKind);
2436 void EmitStaticVarDecl(const VarDecl &D,
2437 llvm::GlobalValue::LinkageTypes Linkage);
2442 ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
2444 static ParamValue forDirect(llvm::Value *value) {
2445 return ParamValue(value, 0);
2447 static ParamValue forIndirect(Address addr) {
2448 assert(!addr.getAlignment().isZero());
2449 return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
2452 bool isIndirect() const { return Alignment != 0; }
2453 llvm::Value *getAnyValue() const { return Value; }
2455 llvm::Value *getDirectValue() const {
2456 assert(!isIndirect());
2460 Address getIndirectAddress() const {
2461 assert(isIndirect());
2462 return Address(Value, CharUnits::fromQuantity(Alignment));
2466 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
2467 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
2469 /// protectFromPeepholes - Protect a value that we're intending to
2470 /// store to the side, but which will probably be used later, from
2471 /// aggressive peepholing optimizations that might delete it.
2473 /// Pass the result to unprotectFromPeepholes to declare that
2474 /// protection is no longer required.
2476 /// There's no particular reason why this shouldn't apply to
2477 /// l-values, it's just that no existing peepholes work on pointers.
2478 PeepholeProtection protectFromPeepholes(RValue rvalue);
2479 void unprotectFromPeepholes(PeepholeProtection protection);
2481 void EmitAlignmentAssumption(llvm::Value *PtrValue, llvm::Value *Alignment,
2482 llvm::Value *OffsetValue = nullptr) {
2483 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2487 //===--------------------------------------------------------------------===//
2488 // Statement Emission
2489 //===--------------------------------------------------------------------===//
2491 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
2492 void EmitStopPoint(const Stmt *S);
2494 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
2495 /// this function even if there is no current insertion point.
2497 /// This function may clear the current insertion point; callers should use
2498 /// EnsureInsertPoint if they wish to subsequently generate code without first
2499 /// calling EmitBlock, EmitBranch, or EmitStmt.
2500 void EmitStmt(const Stmt *S);
2502 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
2503 /// necessarily require an insertion point or debug information; typically
2504 /// because the statement amounts to a jump or a container of other
2507 /// \return True if the statement was handled.
2508 bool EmitSimpleStmt(const Stmt *S);
2510 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
2511 AggValueSlot AVS = AggValueSlot::ignored());
2512 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
2513 bool GetLast = false,
2515 AggValueSlot::ignored());
2517 /// EmitLabel - Emit the block for the given label. It is legal to call this
2518 /// function even if there is no current insertion point.
2519 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
2521 void EmitLabelStmt(const LabelStmt &S);
2522 void EmitAttributedStmt(const AttributedStmt &S);
2523 void EmitGotoStmt(const GotoStmt &S);
2524 void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
2525 void EmitIfStmt(const IfStmt &S);
2527 void EmitWhileStmt(const WhileStmt &S,
2528 ArrayRef<const Attr *> Attrs = None);
2529 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
2530 void EmitForStmt(const ForStmt &S,
2531 ArrayRef<const Attr *> Attrs = None);
2532 void EmitReturnStmt(const ReturnStmt &S);
2533 void EmitDeclStmt(const DeclStmt &S);
2534 void EmitBreakStmt(const BreakStmt &S);
2535 void EmitContinueStmt(const ContinueStmt &S);
2536 void EmitSwitchStmt(const SwitchStmt &S);
2537 void EmitDefaultStmt(const DefaultStmt &S);
2538 void EmitCaseStmt(const CaseStmt &S);
2539 void EmitCaseStmtRange(const CaseStmt &S);
2540 void EmitAsmStmt(const AsmStmt &S);
2542 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
2543 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
2544 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
2545 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
2546 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
2548 void EmitCoroutineBody(const CoroutineBodyStmt &S);
2549 void EmitCoreturnStmt(const CoreturnStmt &S);
2550 RValue EmitCoawaitExpr(const CoawaitExpr &E,
2551 AggValueSlot aggSlot = AggValueSlot::ignored(),
2552 bool ignoreResult = false);
2553 RValue EmitCoyieldExpr(const CoyieldExpr &E,
2554 AggValueSlot aggSlot = AggValueSlot::ignored(),
2555 bool ignoreResult = false);
2556 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
2558 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2559 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2561 void EmitCXXTryStmt(const CXXTryStmt &S);
2562 void EmitSEHTryStmt(const SEHTryStmt &S);
2563 void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
2564 void EnterSEHTryStmt(const SEHTryStmt &S);
2565 void ExitSEHTryStmt(const SEHTryStmt &S);
2567 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
2568 const Stmt *OutlinedStmt);
2570 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2571 const SEHExceptStmt &Except);
2573 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2574 const SEHFinallyStmt &Finally);
2576 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
2577 llvm::Value *ParentFP,
2578 llvm::Value *EntryEBP);
2579 llvm::Value *EmitSEHExceptionCode();
2580 llvm::Value *EmitSEHExceptionInfo();
2581 llvm::Value *EmitSEHAbnormalTermination();
2583 /// Scan the outlined statement for captures from the parent function. For
2584 /// each capture, mark the capture as escaped and emit a call to
2585 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
2586 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
2589 /// Recovers the address of a local in a parent function. ParentVar is the
2590 /// address of the variable used in the immediate parent function. It can
2591 /// either be an alloca or a call to llvm.localrecover if there are nested
2592 /// outlined functions. ParentFP is the frame pointer of the outermost parent
2594 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
2596 llvm::Value *ParentFP);
2598 void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
2599 ArrayRef<const Attr *> Attrs = None);
2601 /// Returns calculated size of the specified type.
2602 llvm::Value *getTypeSize(QualType Ty);
2603 LValue InitCapturedStruct(const CapturedStmt &S);
2604 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
2605 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
2606 Address GenerateCapturedStmtArgument(const CapturedStmt &S);
2607 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
2608 void GenerateOpenMPCapturedVars(const CapturedStmt &S,
2609 SmallVectorImpl<llvm::Value *> &CapturedVars);
2610 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
2611 SourceLocation Loc);
2612 /// \brief Perform element by element copying of arrays with type \a
2613 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
2614 /// generated by \a CopyGen.
2616 /// \param DestAddr Address of the destination array.
2617 /// \param SrcAddr Address of the source array.
2618 /// \param OriginalType Type of destination and source arrays.
2619 /// \param CopyGen Copying procedure that copies value of single array element
2620 /// to another single array element.
2621 void EmitOMPAggregateAssign(
2622 Address DestAddr, Address SrcAddr, QualType OriginalType,
2623 const llvm::function_ref<void(Address, Address)> &CopyGen);
2624 /// \brief Emit proper copying of data from one variable to another.
2626 /// \param OriginalType Original type of the copied variables.
2627 /// \param DestAddr Destination address.
2628 /// \param SrcAddr Source address.
2629 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
2630 /// type of the base array element).
2631 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
2632 /// the base array element).
2633 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
2635 void EmitOMPCopy(QualType OriginalType,
2636 Address DestAddr, Address SrcAddr,
2637 const VarDecl *DestVD, const VarDecl *SrcVD,
2639 /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
2640 /// \a X = \a E \a BO \a E.
2642 /// \param X Value to be updated.
2643 /// \param E Update value.
2644 /// \param BO Binary operation for update operation.
2645 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
2646 /// expression, false otherwise.
2647 /// \param AO Atomic ordering of the generated atomic instructions.
2648 /// \param CommonGen Code generator for complex expressions that cannot be
2649 /// expressed through atomicrmw instruction.
2650 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
2651 /// generated, <false, RValue::get(nullptr)> otherwise.
2652 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
2653 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2654 llvm::AtomicOrdering AO, SourceLocation Loc,
2655 const llvm::function_ref<RValue(RValue)> &CommonGen);
2656 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
2657 OMPPrivateScope &PrivateScope);
2658 void EmitOMPPrivateClause(const OMPExecutableDirective &D,
2659 OMPPrivateScope &PrivateScope);
2660 void EmitOMPUseDevicePtrClause(
2661 const OMPClause &C, OMPPrivateScope &PrivateScope,
2662 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
2663 /// \brief Emit code for copyin clause in \a D directive. The next code is
2664 /// generated at the start of outlined functions for directives:
2666 /// threadprivate_var1 = master_threadprivate_var1;
2667 /// operator=(threadprivate_var2, master_threadprivate_var2);
2669 /// __kmpc_barrier(&loc, global_tid);
2672 /// \param D OpenMP directive possibly with 'copyin' clause(s).
2673 /// \returns true if at least one copyin variable is found, false otherwise.
2674 bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
2675 /// \brief Emit initial code for lastprivate variables. If some variable is
2676 /// not also firstprivate, then the default initialization is used. Otherwise
2677 /// initialization of this variable is performed by EmitOMPFirstprivateClause
2680 /// \param D Directive that may have 'lastprivate' directives.
2681 /// \param PrivateScope Private scope for capturing lastprivate variables for
2682 /// proper codegen in internal captured statement.
2684 /// \returns true if there is at least one lastprivate variable, false
2686 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
2687 OMPPrivateScope &PrivateScope);
2688 /// \brief Emit final copying of lastprivate values to original variables at
2689 /// the end of the worksharing or simd directive.
2691 /// \param D Directive that has at least one 'lastprivate' directives.
2692 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
2693 /// it is the last iteration of the loop code in associated directive, or to
2694 /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
2695 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
2697 llvm::Value *IsLastIterCond = nullptr);
2698 /// Emit initial code for linear clauses.
2699 void EmitOMPLinearClause(const OMPLoopDirective &D,
2700 CodeGenFunction::OMPPrivateScope &PrivateScope);
2701 /// Emit final code for linear clauses.
2702 /// \param CondGen Optional conditional code for final part of codegen for
2704 void EmitOMPLinearClauseFinal(
2705 const OMPLoopDirective &D,
2706 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2707 /// \brief Emit initial code for reduction variables. Creates reduction copies
2708 /// and initializes them with the values according to OpenMP standard.
2710 /// \param D Directive (possibly) with the 'reduction' clause.
2711 /// \param PrivateScope Private scope for capturing reduction variables for
2712 /// proper codegen in internal captured statement.
2714 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
2715 OMPPrivateScope &PrivateScope);
2716 /// \brief Emit final update of reduction values to original variables at
2717 /// the end of the directive.
2719 /// \param D Directive that has at least one 'reduction' directives.
2720 /// \param ReductionKind The kind of reduction to perform.
2721 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
2722 const OpenMPDirectiveKind ReductionKind);
2723 /// \brief Emit initial code for linear variables. Creates private copies
2724 /// and initializes them with the values according to OpenMP standard.
2726 /// \param D Directive (possibly) with the 'linear' clause.
2727 void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
2729 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
2730 llvm::Value * /*OutlinedFn*/,
2731 const OMPTaskDataTy & /*Data*/)>
2733 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2734 const RegionCodeGenTy &BodyGen,
2735 const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
2737 void EmitOMPParallelDirective(const OMPParallelDirective &S);
2738 void EmitOMPSimdDirective(const OMPSimdDirective &S);
2739 void EmitOMPForDirective(const OMPForDirective &S);
2740 void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
2741 void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
2742 void EmitOMPSectionDirective(const OMPSectionDirective &S);
2743 void EmitOMPSingleDirective(const OMPSingleDirective &S);
2744 void EmitOMPMasterDirective(const OMPMasterDirective &S);
2745 void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
2746 void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
2747 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
2748 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
2749 void EmitOMPTaskDirective(const OMPTaskDirective &S);
2750 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
2751 void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
2752 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
2753 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
2754 void EmitOMPFlushDirective(const OMPFlushDirective &S);
2755 void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
2756 void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
2757 void EmitOMPTargetDirective(const OMPTargetDirective &S);
2758 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
2759 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
2760 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
2761 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
2762 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
2764 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
2765 void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
2767 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
2768 void EmitOMPCancelDirective(const OMPCancelDirective &S);
2769 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
2770 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
2771 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
2772 void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
2773 void EmitOMPDistributeParallelForDirective(
2774 const OMPDistributeParallelForDirective &S);
2775 void EmitOMPDistributeParallelForSimdDirective(
2776 const OMPDistributeParallelForSimdDirective &S);
2777 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
2778 void EmitOMPTargetParallelForSimdDirective(
2779 const OMPTargetParallelForSimdDirective &S);
2780 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
2781 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
2783 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
2784 void EmitOMPTeamsDistributeParallelForSimdDirective(
2785 const OMPTeamsDistributeParallelForSimdDirective &S);
2786 void EmitOMPTeamsDistributeParallelForDirective(
2787 const OMPTeamsDistributeParallelForDirective &S);
2788 void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
2789 void EmitOMPTargetTeamsDistributeDirective(
2790 const OMPTargetTeamsDistributeDirective &S);
2791 void EmitOMPTargetTeamsDistributeParallelForDirective(
2792 const OMPTargetTeamsDistributeParallelForDirective &S);
2793 void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2794 const OMPTargetTeamsDistributeParallelForSimdDirective &S);
2795 void EmitOMPTargetTeamsDistributeSimdDirective(
2796 const OMPTargetTeamsDistributeSimdDirective &S);
2798 /// Emit device code for the target directive.
2799 static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
2800 StringRef ParentName,
2801 const OMPTargetDirective &S);
2803 EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
2804 const OMPTargetParallelDirective &S);
2806 EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
2807 const OMPTargetTeamsDirective &S);
2808 /// \brief Emit inner loop of the worksharing/simd construct.
2810 /// \param S Directive, for which the inner loop must be emitted.
2811 /// \param RequiresCleanup true, if directive has some associated private
2813 /// \param LoopCond Bollean condition for loop continuation.
2814 /// \param IncExpr Increment expression for loop control variable.
2815 /// \param BodyGen Generator for the inner body of the inner loop.
2816 /// \param PostIncGen Genrator for post-increment code (required for ordered
2817 /// loop directvies).
2818 void EmitOMPInnerLoop(
2819 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
2820 const Expr *IncExpr,
2821 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
2822 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
2824 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
2825 /// Emit initial code for loop counters of loop-based directives.
2826 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
2827 OMPPrivateScope &LoopScope);
2829 /// Helper for the OpenMP loop directives.
2830 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
2832 /// \brief Emit code for the worksharing loop-based directive.
2833 /// \return true, if this construct has any lastprivate clause, false -
2835 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB,
2836 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2837 const CodeGenDispatchBoundsTy &CGDispatchBounds);
2840 /// Helpers for blocks
2841 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
2843 /// Helpers for the OpenMP loop directives.
2844 void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
2845 void EmitOMPSimdFinal(
2846 const OMPLoopDirective &D,
2847 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2849 void EmitOMPDistributeLoop(const OMPLoopDirective &S,
2850 const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
2852 /// struct with the values to be passed to the OpenMP loop-related functions
2853 struct OMPLoopArguments {
2854 /// loop lower bound
2855 Address LB = Address::invalid();
2856 /// loop upper bound
2857 Address UB = Address::invalid();
2859 Address ST = Address::invalid();
2860 /// isLastIteration argument for runtime functions
2861 Address IL = Address::invalid();
2862 /// Chunk value generated by sema
2863 llvm::Value *Chunk = nullptr;
2864 /// EnsureUpperBound
2865 Expr *EUB = nullptr;
2866 /// IncrementExpression
2867 Expr *IncExpr = nullptr;
2868 /// Loop initialization
2869 Expr *Init = nullptr;
2870 /// Loop exit condition
2871 Expr *Cond = nullptr;
2872 /// Update of LB after a whole chunk has been executed
2873 Expr *NextLB = nullptr;
2874 /// Update of UB after a whole chunk has been executed
2875 Expr *NextUB = nullptr;
2876 OMPLoopArguments() = default;
2877 OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
2878 llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
2879 Expr *IncExpr = nullptr, Expr *Init = nullptr,
2880 Expr *Cond = nullptr, Expr *NextLB = nullptr,
2881 Expr *NextUB = nullptr)
2882 : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
2883 IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
2886 void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
2887 const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
2888 const OMPLoopArguments &LoopArgs,
2889 const CodeGenLoopTy &CodeGenLoop,
2890 const CodeGenOrderedTy &CodeGenOrdered);
2891 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
2892 bool IsMonotonic, const OMPLoopDirective &S,
2893 OMPPrivateScope &LoopScope, bool Ordered,
2894 const OMPLoopArguments &LoopArgs,
2895 const CodeGenDispatchBoundsTy &CGDispatchBounds);
2896 void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
2897 const OMPLoopDirective &S,
2898 OMPPrivateScope &LoopScope,
2899 const OMPLoopArguments &LoopArgs,
2900 const CodeGenLoopTy &CodeGenLoopContent);
2901 /// \brief Emit code for sections directive.
2902 void EmitSections(const OMPExecutableDirective &S);
2906 //===--------------------------------------------------------------------===//
2907 // LValue Expression Emission
2908 //===--------------------------------------------------------------------===//
2910 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
2911 RValue GetUndefRValue(QualType Ty);
2913 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
2914 /// and issue an ErrorUnsupported style diagnostic (using the
2916 RValue EmitUnsupportedRValue(const Expr *E,
2919 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
2920 /// an ErrorUnsupported style diagnostic (using the provided Name).
2921 LValue EmitUnsupportedLValue(const Expr *E,
2924 /// EmitLValue - Emit code to compute a designator that specifies the location
2925 /// of the expression.
2927 /// This can return one of two things: a simple address or a bitfield
2928 /// reference. In either case, the LLVM Value* in the LValue structure is
2929 /// guaranteed to be an LLVM pointer type.
2931 /// If this returns a bitfield reference, nothing about the pointee type of
2932 /// the LLVM value is known: For example, it may not be a pointer to an
2935 /// If this returns a normal address, and if the lvalue's C type is fixed
2936 /// size, this method guarantees that the returned pointer type will point to
2937 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
2938 /// variable length type, this is not possible.
2940 LValue EmitLValue(const Expr *E);
2942 /// \brief Same as EmitLValue but additionally we generate checking code to
2943 /// guard against undefined behavior. This is only suitable when we know
2944 /// that the address will be used to access the object.
2945 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
2947 RValue convertTempToRValue(Address addr, QualType type,
2948 SourceLocation Loc);
2950 void EmitAtomicInit(Expr *E, LValue lvalue);
2952 bool LValueIsSuitableForInlineAtomic(LValue Src);
2954 RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
2955 AggValueSlot Slot = AggValueSlot::ignored());
2957 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
2958 llvm::AtomicOrdering AO, bool IsVolatile = false,
2959 AggValueSlot slot = AggValueSlot::ignored());
2961 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
2963 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
2964 bool IsVolatile, bool isInit);
2966 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
2967 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2968 llvm::AtomicOrdering Success =
2969 llvm::AtomicOrdering::SequentiallyConsistent,
2970 llvm::AtomicOrdering Failure =
2971 llvm::AtomicOrdering::SequentiallyConsistent,
2972 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
2974 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
2975 const llvm::function_ref<RValue(RValue)> &UpdateOp,
2978 /// EmitToMemory - Change a scalar value from its value
2979 /// representation to its in-memory representation.
2980 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
2982 /// EmitFromMemory - Change a scalar value from its memory
2983 /// representation to its value representation.
2984 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
2986 /// Check if the scalar \p Value is within the valid range for the given
2989 /// Returns true if a check is needed (even if the range is unknown).
2990 bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
2991 SourceLocation Loc);
2993 /// EmitLoadOfScalar - Load a scalar value from an address, taking
2994 /// care to appropriately convert from the memory representation to
2995 /// the LLVM value representation.
2996 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
2998 LValueBaseInfo BaseInfo =
2999 LValueBaseInfo(AlignmentSource::Type),
3000 llvm::MDNode *TBAAInfo = nullptr,
3001 QualType TBAABaseTy = QualType(),
3002 uint64_t TBAAOffset = 0,
3003 bool isNontemporal = false);
3005 /// EmitLoadOfScalar - Load a scalar value from an address, taking
3006 /// care to appropriately convert from the memory representation to
3007 /// the LLVM value representation. The l-value must be a simple
3009 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
3011 /// EmitStoreOfScalar - Store a scalar value to an address, taking
3012 /// care to appropriately convert from the memory representation to
3013 /// the LLVM value representation.
3014 void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3015 bool Volatile, QualType Ty,
3016 LValueBaseInfo BaseInfo =
3017 LValueBaseInfo(AlignmentSource::Type),
3018 llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
3019 QualType TBAABaseTy = QualType(),
3020 uint64_t TBAAOffset = 0, bool isNontemporal = false);
3022 /// EmitStoreOfScalar - Store a scalar value to an address, taking
3023 /// care to appropriately convert from the memory representation to
3024 /// the LLVM value representation. The l-value must be a simple
3025 /// l-value. The isInit flag indicates whether this is an initialization.
3026 /// If so, atomic qualifiers are ignored and the store is always non-atomic.
3027 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
3029 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
3030 /// this method emits the address of the lvalue, then loads the result as an
3031 /// rvalue, returning the rvalue.
3032 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
3033 RValue EmitLoadOfExtVectorElementLValue(LValue V);
3034 RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc);
3035 RValue EmitLoadOfGlobalRegLValue(LValue LV);
3037 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
3038 /// lvalue, where both are guaranteed to the have the same type, and that type
3040 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
3041 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
3042 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
3044 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
3045 /// as EmitStoreThroughLValue.
3047 /// \param Result [out] - If non-null, this will be set to a Value* for the
3048 /// bit-field contents after the store, appropriate for use as the result of
3049 /// an assignment to the bit-field.
3050 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
3051 llvm::Value **Result=nullptr);
3053 /// Emit an l-value for an assignment (simple or compound) of complex type.
3054 LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
3055 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
3056 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
3057 llvm::Value *&Result);
3059 // Note: only available for agg return types
3060 LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
3061 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
3062 // Note: only available for agg return types
3063 LValue EmitCallExprLValue(const CallExpr *E);
3064 // Note: only available for agg return types
3065 LValue EmitVAArgExprLValue(const VAArgExpr *E);
3066 LValue EmitDeclRefLValue(const DeclRefExpr *E);
3067 LValue EmitStringLiteralLValue(const StringLiteral *E);
3068 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
3069 LValue EmitPredefinedLValue(const PredefinedExpr *E);
3070 LValue EmitUnaryOpLValue(const UnaryOperator *E);
3071 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3072 bool Accessed = false);
3073 LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3074 bool IsLowerBound = true);
3075 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
3076 LValue EmitMemberExpr(const MemberExpr *E);
3077 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
3078 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
3079 LValue EmitInitListLValue(const InitListExpr *E);
3080 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
3081 LValue EmitCastLValue(const CastExpr *E);
3082 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
3083 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
3085 Address EmitExtVectorElementLValue(LValue V);
3087 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
3089 Address EmitArrayToPointerDecay(const Expr *Array,
3090 LValueBaseInfo *BaseInfo = nullptr);
3092 class ConstantEmission {
3093 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
3094 ConstantEmission(llvm::Constant *C, bool isReference)
3095 : ValueAndIsReference(C, isReference) {}
3097 ConstantEmission() {}
3098 static ConstantEmission forReference(llvm::Constant *C) {
3099 return ConstantEmission(C, true);
3101 static ConstantEmission forValue(llvm::Constant *C) {
3102 return ConstantEmission(C, false);
3105 explicit operator bool() const {
3106 return ValueAndIsReference.getOpaqueValue() != nullptr;
3109 bool isReference() const { return ValueAndIsReference.getInt(); }
3110 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
3111 assert(isReference());
3112 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
3113 refExpr->getType());
3116 llvm::Constant *getValue() const {
3117 assert(!isReference());
3118 return ValueAndIsReference.getPointer();
3122 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
3124 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
3125 AggValueSlot slot = AggValueSlot::ignored());
3126 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
3128 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
3129 const ObjCIvarDecl *Ivar);
3130 LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
3131 LValue EmitLValueForLambdaField(const FieldDecl *Field);
3133 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
3134 /// if the Field is a reference, this will return the address of the reference
3135 /// and not the address of the value stored in the reference.
3136 LValue EmitLValueForFieldInitialization(LValue Base,
3137 const FieldDecl* Field);
3139 LValue EmitLValueForIvar(QualType ObjectTy,
3140 llvm::Value* Base, const ObjCIvarDecl *Ivar,
3141 unsigned CVRQualifiers);
3143 LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
3144 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
3145 LValue EmitLambdaLValue(const LambdaExpr *E);
3146 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
3147 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
3149 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
3150 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
3151 LValue EmitStmtExprLValue(const StmtExpr *E);
3152 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
3153 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
3154 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
3156 //===--------------------------------------------------------------------===//
3157 // Scalar Expression Emission
3158 //===--------------------------------------------------------------------===//
3160 /// EmitCall - Generate a call of the given function, expecting the given
3161 /// result type, and using the given argument list which specifies both the
3162 /// LLVM arguments and the types they were derived from.
3163 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
3164 ReturnValueSlot ReturnValue, const CallArgList &Args,
3165 llvm::Instruction **callOrInvoke = nullptr);
3167 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
3168 ReturnValueSlot ReturnValue,
3169 llvm::Value *Chain = nullptr);
3170 RValue EmitCallExpr(const CallExpr *E,
3171 ReturnValueSlot ReturnValue = ReturnValueSlot());
3172 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3173 CGCallee EmitCallee(const Expr *E);
3175 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
3177 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3178 const Twine &name = "");
3179 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3180 ArrayRef<llvm::Value*> args,
3181 const Twine &name = "");
3182 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3183 const Twine &name = "");
3184 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3185 ArrayRef<llvm::Value*> args,
3186 const Twine &name = "");
3188 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
3189 ArrayRef<llvm::Value *> Args,
3190 const Twine &Name = "");
3191 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3192 ArrayRef<llvm::Value*> args,
3193 const Twine &name = "");
3194 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3195 const Twine &name = "");
3196 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3197 ArrayRef<llvm::Value*> args);
3199 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
3200 NestedNameSpecifier *Qual,
3203 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
3205 const CXXRecordDecl *RD);
3208 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
3209 const CGCallee &Callee,
3210 ReturnValueSlot ReturnValue, llvm::Value *This,
3211 llvm::Value *ImplicitParam,
3212 QualType ImplicitParamTy, const CallExpr *E,
3213 CallArgList *RtlArgs);
3214 RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD,
3215 const CGCallee &Callee,
3216 llvm::Value *This, llvm::Value *ImplicitParam,
3217 QualType ImplicitParamTy, const CallExpr *E,
3219 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
3220 ReturnValueSlot ReturnValue);
3221 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
3222 const CXXMethodDecl *MD,
3223 ReturnValueSlot ReturnValue,
3225 NestedNameSpecifier *Qualifier,
3226 bool IsArrow, const Expr *Base);
3227 // Compute the object pointer.
3228 Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
3229 llvm::Value *memberPtr,
3230 const MemberPointerType *memberPtrType,
3231 LValueBaseInfo *BaseInfo = nullptr);
3232 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
3233 ReturnValueSlot ReturnValue);
3235 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
3236 const CXXMethodDecl *MD,
3237 ReturnValueSlot ReturnValue);
3238 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
3240 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
3241 ReturnValueSlot ReturnValue);
3243 RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E,
3244 ReturnValueSlot ReturnValue);
3246 RValue EmitBuiltinExpr(const FunctionDecl *FD,
3247 unsigned BuiltinID, const CallExpr *E,
3248 ReturnValueSlot ReturnValue);
3250 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3252 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
3253 /// is unhandled by the current target.
3254 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3256 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
3257 const llvm::CmpInst::Predicate Fp,
3258 const llvm::CmpInst::Predicate Ip,
3259 const llvm::Twine &Name = "");
3260 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3262 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
3263 unsigned LLVMIntrinsic,
3264 unsigned AltLLVMIntrinsic,
3265 const char *NameHint,
3268 SmallVectorImpl<llvm::Value *> &Ops,
3269 Address PtrOp0, Address PtrOp1);
3270 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
3271 unsigned Modifier, llvm::Type *ArgTy,
3273 llvm::Value *EmitNeonCall(llvm::Function *F,
3274 SmallVectorImpl<llvm::Value*> &O,
3276 unsigned shift = 0, bool rightshift = false);
3277 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
3278 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
3279 bool negateForRightShift);
3280 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
3281 llvm::Type *Ty, bool usgn, const char *name);
3282 llvm::Value *vectorWrapScalar16(llvm::Value *Op);
3283 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3285 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
3286 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3287 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3288 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3289 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3290 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3291 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
3295 enum class MSVCIntrin;
3298 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
3300 llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args);
3302 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
3303 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
3304 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
3305 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
3306 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
3307 llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
3308 const ObjCMethodDecl *MethodWithObjects);
3309 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
3310 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
3311 ReturnValueSlot Return = ReturnValueSlot());
3313 /// Retrieves the default cleanup kind for an ARC cleanup.
3314 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
3315 CleanupKind getARCCleanupKind() {
3316 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
3317 ? NormalAndEHCleanup : NormalCleanup;
3321 void EmitARCInitWeak(Address addr, llvm::Value *value);
3322 void EmitARCDestroyWeak(Address addr);
3323 llvm::Value *EmitARCLoadWeak(Address addr);
3324 llvm::Value *EmitARCLoadWeakRetained(Address addr);
3325 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
3326 void EmitARCCopyWeak(Address dst, Address src);
3327 void EmitARCMoveWeak(Address dst, Address src);
3328 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
3329 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
3330 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
3331 bool resultIgnored);
3332 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
3333 bool resultIgnored);
3334 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
3335 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
3336 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
3337 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
3338 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
3339 llvm::Value *EmitARCAutorelease(llvm::Value *value);
3340 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
3341 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
3342 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
3343 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
3345 std::pair<LValue,llvm::Value*>
3346 EmitARCStoreAutoreleasing(const BinaryOperator *e);
3347 std::pair<LValue,llvm::Value*>
3348 EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
3349 std::pair<LValue,llvm::Value*>
3350 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
3352 llvm::Value *EmitObjCThrowOperand(const Expr *expr);
3353 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
3354 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
3356 llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
3357 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
3358 bool allowUnsafeClaim);
3359 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
3360 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
3361 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
3363 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
3365 static Destroyer destroyARCStrongImprecise;
3366 static Destroyer destroyARCStrongPrecise;
3367 static Destroyer destroyARCWeak;
3368 static Destroyer emitARCIntrinsicUse;
3370 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
3371 llvm::Value *EmitObjCAutoreleasePoolPush();
3372 llvm::Value *EmitObjCMRRAutoreleasePoolPush();
3373 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
3374 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
3376 /// \brief Emits a reference binding to the passed in expression.
3377 RValue EmitReferenceBindingToExpr(const Expr *E);
3379 //===--------------------------------------------------------------------===//
3380 // Expression Emission
3381 //===--------------------------------------------------------------------===//
3383 // Expressions are broken into three classes: scalar, complex, aggregate.
3385 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
3386 /// scalar type, returning the result.
3387 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
3389 /// Emit a conversion from the specified type to the specified destination
3390 /// type, both of which are LLVM scalar types.
3391 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
3392 QualType DstTy, SourceLocation Loc);
3394 /// Emit a conversion from the specified complex type to the specified
3395 /// destination type, where the destination type is an LLVM scalar type.
3396 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
3398 SourceLocation Loc);
3400 /// EmitAggExpr - Emit the computation of the specified expression
3401 /// of aggregate type. The result is computed into the given slot,
3402 /// which may be null to indicate that the value is not needed.
3403 void EmitAggExpr(const Expr *E, AggValueSlot AS);
3405 /// EmitAggExprToLValue - Emit the computation of the specified expression of
3406 /// aggregate type into a temporary LValue.
3407 LValue EmitAggExprToLValue(const Expr *E);
3409 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3410 /// make sure it survives garbage collection until this point.
3411 void EmitExtendGCLifetime(llvm::Value *object);
3413 /// EmitComplexExpr - Emit the computation of the specified expression of
3414 /// complex type, returning the result.
3415 ComplexPairTy EmitComplexExpr(const Expr *E,
3416 bool IgnoreReal = false,
3417 bool IgnoreImag = false);
3419 /// EmitComplexExprIntoLValue - Emit the given expression of complex
3420 /// type and place its result into the specified l-value.
3421 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
3423 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
3424 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
3426 /// EmitLoadOfComplex - Load a complex number from the specified l-value.
3427 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
3429 Address emitAddrOfRealComponent(Address complex, QualType complexType);
3430 Address emitAddrOfImagComponent(Address complex, QualType complexType);
3432 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
3433 /// global variable that has already been created for it. If the initializer
3434 /// has a different type than GV does, this may free GV and return a different
3435 /// one. Otherwise it just returns GV.
3436 llvm::GlobalVariable *
3437 AddInitializerToStaticVarDecl(const VarDecl &D,
3438 llvm::GlobalVariable *GV);
3441 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
3442 /// variable with global storage.
3443 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
3446 llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
3447 llvm::Constant *Addr);
3449 /// Call atexit() with a function that passes the given argument to
3450 /// the given function.
3451 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
3452 llvm::Constant *addr);
3454 /// Emit code in this function to perform a guarded variable
3455 /// initialization. Guarded initializations are used when it's not
3456 /// possible to prove that an initialization will be done exactly
3457 /// once, e.g. with a static local variable or a static data member
3458 /// of a class template.
3459 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
3462 /// GenerateCXXGlobalInitFunc - Generates code for initializing global
3464 void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
3465 ArrayRef<llvm::Function *> CXXThreadLocals,
3466 Address Guard = Address::invalid());
3468 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
3470 void GenerateCXXGlobalDtorsFunc(
3472 const std::vector<std::pair<llvm::WeakTrackingVH, llvm::Constant *>>
3475 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
3477 llvm::GlobalVariable *Addr,
3480 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
3482 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
3484 void enterFullExpression(const ExprWithCleanups *E) {
3485 if (E->getNumObjects() == 0) return;
3486 enterNonTrivialFullExpression(E);
3488 void enterNonTrivialFullExpression(const ExprWithCleanups *E);
3490 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
3492 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
3494 RValue EmitAtomicExpr(AtomicExpr *E);
3496 //===--------------------------------------------------------------------===//
3497 // Annotations Emission
3498 //===--------------------------------------------------------------------===//
3500 /// Emit an annotation call (intrinsic or builtin).
3501 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
3502 llvm::Value *AnnotatedVal,
3503 StringRef AnnotationStr,
3504 SourceLocation Location);
3506 /// Emit local annotations for the local variable V, declared by D.
3507 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
3509 /// Emit field annotations for the given field & value. Returns the
3510 /// annotation result.
3511 Address EmitFieldAnnotations(const FieldDecl *D, Address V);
3513 //===--------------------------------------------------------------------===//
3515 //===--------------------------------------------------------------------===//
3517 /// ContainsLabel - Return true if the statement contains a label in it. If
3518 /// this statement is not executed normally, it not containing a label means
3519 /// that we can just remove the code.
3520 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
3522 /// containsBreak - Return true if the statement contains a break out of it.
3523 /// If the statement (recursively) contains a switch or loop with a break
3524 /// inside of it, this is fine.
3525 static bool containsBreak(const Stmt *S);
3527 /// Determine if the given statement might introduce a declaration into the
3528 /// current scope, by being a (possibly-labelled) DeclStmt.
3529 static bool mightAddDeclToScope(const Stmt *S);
3531 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3532 /// to a constant, or if it does but contains a label, return false. If it
3533 /// constant folds return true and set the boolean result in Result.
3534 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
3535 bool AllowLabels = false);
3537 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3538 /// to a constant, or if it does but contains a label, return false. If it
3539 /// constant folds return true and set the folded value.
3540 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
3541 bool AllowLabels = false);
3543 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
3544 /// if statement) to the specified blocks. Based on the condition, this might
3545 /// try to simplify the codegen of the conditional based on the branch.
3546 /// TrueCount should be the number of times we expect the condition to
3547 /// evaluate to true based on PGO data.
3548 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
3549 llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
3551 /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is
3552 /// nonnull, if \p LHS is marked _Nonnull.
3553 void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc);
3555 /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to
3556 /// detect undefined behavior when the pointer overflow sanitizer is enabled.
3557 llvm::Value *EmitCheckedInBoundsGEP(llvm::Value *Ptr,
3558 ArrayRef<llvm::Value *> IdxList,
3560 const Twine &Name = "");
3562 /// \brief Emit a description of a type in a format suitable for passing to
3563 /// a runtime sanitizer handler.
3564 llvm::Constant *EmitCheckTypeDescriptor(QualType T);
3566 /// \brief Convert a value into a format suitable for passing to a runtime
3567 /// sanitizer handler.
3568 llvm::Value *EmitCheckValue(llvm::Value *V);
3570 /// \brief Emit a description of a source location in a format suitable for
3571 /// passing to a runtime sanitizer handler.
3572 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
3574 /// \brief Create a basic block that will call a handler function in a
3575 /// sanitizer runtime with the provided arguments, and create a conditional
3577 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3578 SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
3579 ArrayRef<llvm::Value *> DynamicArgs);
3581 /// \brief Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
3582 /// if Cond if false.
3583 void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
3584 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
3585 ArrayRef<llvm::Constant *> StaticArgs);
3587 /// \brief Create a basic block that will call the trap intrinsic, and emit a
3588 /// conditional branch to it, for the -ftrapv checks.
3589 void EmitTrapCheck(llvm::Value *Checked);
3591 /// \brief Emit a call to trap or debugtrap and attach function attribute
3592 /// "trap-func-name" if specified.
3593 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
3595 /// \brief Emit a stub for the cross-DSO CFI check function.
3596 void EmitCfiCheckStub();
3598 /// \brief Emit a cross-DSO CFI failure handling function.
3599 void EmitCfiCheckFail();
3601 /// \brief Create a check for a function parameter that may potentially be
3602 /// declared as non-null.
3603 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
3604 AbstractCallee AC, unsigned ParmNum);
3606 /// EmitCallArg - Emit a single call argument.
3607 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
3609 /// EmitDelegateCallArg - We are performing a delegate call; that
3610 /// is, the current function is delegating to another one. Produce
3611 /// a r-value suitable for passing the given parameter.
3612 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
3613 SourceLocation loc);
3615 /// SetFPAccuracy - Set the minimum required accuracy of the given floating
3616 /// point operation, expressed as the maximum relative error in ulp.
3617 void SetFPAccuracy(llvm::Value *Val, float Accuracy);
3620 llvm::MDNode *getRangeForLoadFromType(QualType Ty);
3621 void EmitReturnOfRValue(RValue RV, QualType Ty);
3623 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
3625 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
3626 DeferredReplacements;
3628 /// Set the address of a local variable.
3629 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
3630 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
3631 LocalDeclMap.insert({VD, Addr});
3634 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
3635 /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
3637 /// \param AI - The first function argument of the expansion.
3638 void ExpandTypeFromArgs(QualType Ty, LValue Dst,
3639 SmallVectorImpl<llvm::Value *>::iterator &AI);
3641 /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
3642 /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
3643 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
3644 void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
3645 SmallVectorImpl<llvm::Value *> &IRCallArgs,
3646 unsigned &IRCallArgPos);
3648 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
3649 const Expr *InputExpr, std::string &ConstraintStr);
3651 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
3652 LValue InputValue, QualType InputType,
3653 std::string &ConstraintStr,
3654 SourceLocation Loc);
3656 /// \brief Attempts to statically evaluate the object size of E. If that
3657 /// fails, emits code to figure the size of E out for us. This is
3658 /// pass_object_size aware.
3660 /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
3661 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
3662 llvm::IntegerType *ResType,
3663 llvm::Value *EmittedE);
3665 /// \brief Emits the size of E, as required by __builtin_object_size. This
3666 /// function is aware of pass_object_size parameters, and will act accordingly
3667 /// if E is a parameter with the pass_object_size attribute.
3668 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
3669 llvm::IntegerType *ResType,
3670 llvm::Value *EmittedE);
3674 // Determine whether the given argument is an Objective-C method
3675 // that may have type parameters in its signature.
3676 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
3677 const DeclContext *dc = method->getDeclContext();
3678 if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
3679 return classDecl->getTypeParamListAsWritten();
3682 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
3683 return catDecl->getTypeParamList();
3689 template<typename T>
3690 static bool isObjCMethodWithTypeParams(const T *) { return false; }
3693 enum class EvaluationOrder {
3694 ///! No language constraints on evaluation order.
3696 ///! Language semantics require left-to-right evaluation.
3698 ///! Language semantics require right-to-left evaluation.
3702 /// EmitCallArgs - Emit call arguments for a function.
3703 template <typename T>
3704 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
3705 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3706 AbstractCallee AC = AbstractCallee(),
3707 unsigned ParamsToSkip = 0,
3708 EvaluationOrder Order = EvaluationOrder::Default) {
3709 SmallVector<QualType, 16> ArgTypes;
3710 CallExpr::const_arg_iterator Arg = ArgRange.begin();
3712 assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
3713 "Can't skip parameters if type info is not provided");
3714 if (CallArgTypeInfo) {
3716 bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
3719 // First, use the argument types that the type info knows about
3720 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
3721 E = CallArgTypeInfo->param_type_end();
3722 I != E; ++I, ++Arg) {
3723 assert(Arg != ArgRange.end() && "Running over edge of argument list!");
3724 assert((isGenericMethod ||
3725 ((*I)->isVariablyModifiedType() ||
3726 (*I).getNonReferenceType()->isObjCRetainableType() ||
3728 .getCanonicalType((*I).getNonReferenceType())
3731 .getCanonicalType((*Arg)->getType())
3733 "type mismatch in call argument!");
3734 ArgTypes.push_back(*I);
3738 // Either we've emitted all the call args, or we have a call to variadic
3740 assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
3741 CallArgTypeInfo->isVariadic()) &&
3742 "Extra arguments in non-variadic function!");
3744 // If we still have any arguments, emit them using the type of the argument.
3745 for (auto *A : llvm::make_range(Arg, ArgRange.end()))
3746 ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType());
3748 EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order);
3751 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
3752 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3753 AbstractCallee AC = AbstractCallee(),
3754 unsigned ParamsToSkip = 0,
3755 EvaluationOrder Order = EvaluationOrder::Default);
3757 /// EmitPointerWithAlignment - Given an expression with a pointer type,
3758 /// emit the value and compute our best estimate of the alignment of the
3761 /// \param BaseInfo - If non-null, this will be initialized with
3762 /// information about the source of the alignment and the may-alias
3763 /// attribute. Note that this function will conservatively fall back on
3764 /// the type when it doesn't recognize the expression and may-alias will
3765 /// be set to false.
3767 /// One reasonable way to use this information is when there's a language
3768 /// guarantee that the pointer must be aligned to some stricter value, and
3769 /// we're simply trying to ensure that sufficiently obvious uses of under-
3770 /// aligned objects don't get miscompiled; for example, a placement new
3771 /// into the address of a local variable. In such a case, it's quite
3772 /// reasonable to just ignore the returned alignment when it isn't from an
3773 /// explicit source.
3774 Address EmitPointerWithAlignment(const Expr *Addr,
3775 LValueBaseInfo *BaseInfo = nullptr);
3777 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
3780 QualType getVarArgType(const Expr *Arg);
3782 const TargetCodeGenInfo &getTargetHooks() const {
3783 return CGM.getTargetCodeGenInfo();
3786 void EmitDeclMetadata();
3788 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
3789 const AutoVarEmission &emission);
3791 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
3793 llvm::Value *GetValueForARMHint(unsigned BuiltinID);
3796 /// Helper class with most of the code for saving a value for a
3797 /// conditional expression cleanup.
3798 struct DominatingLLVMValue {
3799 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
3801 /// Answer whether the given value needs extra work to be saved.
3802 static bool needsSaving(llvm::Value *value) {
3803 // If it's not an instruction, we don't need to save.
3804 if (!isa<llvm::Instruction>(value)) return false;
3806 // If it's an instruction in the entry block, we don't need to save.
3807 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
3808 return (block != &block->getParent()->getEntryBlock());
3811 /// Try to save the given value.
3812 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
3813 if (!needsSaving(value)) return saved_type(value, false);
3815 // Otherwise, we need an alloca.
3816 auto align = CharUnits::fromQuantity(
3817 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
3819 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
3820 CGF.Builder.CreateStore(value, alloca);
3822 return saved_type(alloca.getPointer(), true);
3825 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
3826 // If the value says it wasn't saved, trust that it's still dominating.
3827 if (!value.getInt()) return value.getPointer();
3829 // Otherwise, it should be an alloca instruction, as set up in save().
3830 auto alloca = cast<llvm::AllocaInst>(value.getPointer());
3831 return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
3835 /// A partial specialization of DominatingValue for llvm::Values that
3836 /// might be llvm::Instructions.
3837 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
3839 static type restore(CodeGenFunction &CGF, saved_type value) {
3840 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
3844 /// A specialization of DominatingValue for Address.
3845 template <> struct DominatingValue<Address> {
3846 typedef Address type;
3849 DominatingLLVMValue::saved_type SavedValue;
3850 CharUnits Alignment;
3853 static bool needsSaving(type value) {
3854 return DominatingLLVMValue::needsSaving(value.getPointer());
3856 static saved_type save(CodeGenFunction &CGF, type value) {
3857 return { DominatingLLVMValue::save(CGF, value.getPointer()),
3858 value.getAlignment() };
3860 static type restore(CodeGenFunction &CGF, saved_type value) {
3861 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
3866 /// A specialization of DominatingValue for RValue.
3867 template <> struct DominatingValue<RValue> {
3868 typedef RValue type;
3870 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
3871 AggregateAddress, ComplexAddress };
3875 unsigned Align : 29;
3876 saved_type(llvm::Value *v, Kind k, unsigned a = 0)
3877 : Value(v), K(k), Align(a) {}
3880 static bool needsSaving(RValue value);
3881 static saved_type save(CodeGenFunction &CGF, RValue value);
3882 RValue restore(CodeGenFunction &CGF);
3884 // implementations in CGCleanup.cpp
3887 static bool needsSaving(type value) {
3888 return saved_type::needsSaving(value);
3890 static saved_type save(CodeGenFunction &CGF, type value) {
3891 return saved_type::save(CGF, value);
3893 static type restore(CodeGenFunction &CGF, saved_type value) {
3894 return value.restore(CGF);
3898 } // end namespace CodeGen
3899 } // end namespace clang