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(ShiftOutOfBounds, shift_out_of_bounds, 0) \
124 SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \
125 SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \
126 SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
128 enum SanitizerHandler {
129 #define SANITIZER_CHECK(Enum, Name, Version) Enum,
130 LIST_SANITIZER_CHECKS
131 #undef SANITIZER_CHECK
134 /// CodeGenFunction - This class organizes the per-function state that is used
135 /// while generating LLVM code.
136 class CodeGenFunction : public CodeGenTypeCache {
137 CodeGenFunction(const CodeGenFunction &) = delete;
138 void operator=(const CodeGenFunction &) = delete;
140 friend class CGCXXABI;
142 /// A jump destination is an abstract label, branching to which may
143 /// require a jump out through normal cleanups.
145 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
146 JumpDest(llvm::BasicBlock *Block,
147 EHScopeStack::stable_iterator Depth,
149 : Block(Block), ScopeDepth(Depth), Index(Index) {}
151 bool isValid() const { return Block != nullptr; }
152 llvm::BasicBlock *getBlock() const { return Block; }
153 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
154 unsigned getDestIndex() const { return Index; }
156 // This should be used cautiously.
157 void setScopeDepth(EHScopeStack::stable_iterator depth) {
162 llvm::BasicBlock *Block;
163 EHScopeStack::stable_iterator ScopeDepth;
167 CodeGenModule &CGM; // Per-module state.
168 const TargetInfo &Target;
170 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
171 LoopInfoStack LoopStack;
174 // Stores variables for which we can't generate correct lifetime markers
176 VarBypassDetector Bypasses;
178 /// \brief CGBuilder insert helper. This function is called after an
179 /// instruction is created using Builder.
180 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
181 llvm::BasicBlock *BB,
182 llvm::BasicBlock::iterator InsertPt) const;
184 /// CurFuncDecl - Holds the Decl for the current outermost
185 /// non-closure context.
186 const Decl *CurFuncDecl;
187 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
188 const Decl *CurCodeDecl;
189 const CGFunctionInfo *CurFnInfo;
191 llvm::Function *CurFn;
193 // Holds coroutine data if the current function is a coroutine. We use a
194 // wrapper to manage its lifetime, so that we don't have to define CGCoroData
197 std::unique_ptr<CGCoroData> Data;
203 /// CurGD - The GlobalDecl for the current function being compiled.
206 /// PrologueCleanupDepth - The cleanup depth enclosing all the
207 /// cleanups associated with the parameters.
208 EHScopeStack::stable_iterator PrologueCleanupDepth;
210 /// ReturnBlock - Unified return block.
211 JumpDest ReturnBlock;
213 /// ReturnValue - The temporary alloca to hold the return
214 /// value. This is invalid iff the function has no return value.
217 /// Return true if a label was seen in the current scope.
218 bool hasLabelBeenSeenInCurrentScope() const {
220 return CurLexicalScope->hasLabels();
221 return !LabelMap.empty();
224 /// AllocaInsertPoint - This is an instruction in the entry block before which
225 /// we prefer to insert allocas.
226 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
228 /// \brief API for captured statement code generation.
229 class CGCapturedStmtInfo {
231 explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
232 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
233 explicit CGCapturedStmtInfo(const CapturedStmt &S,
234 CapturedRegionKind K = CR_Default)
235 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
237 RecordDecl::field_iterator Field =
238 S.getCapturedRecordDecl()->field_begin();
239 for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
241 I != E; ++I, ++Field) {
242 if (I->capturesThis())
243 CXXThisFieldDecl = *Field;
244 else if (I->capturesVariable())
245 CaptureFields[I->getCapturedVar()] = *Field;
246 else if (I->capturesVariableByCopy())
247 CaptureFields[I->getCapturedVar()] = *Field;
251 virtual ~CGCapturedStmtInfo();
253 CapturedRegionKind getKind() const { return Kind; }
255 virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
256 // \brief Retrieve the value of the context parameter.
257 virtual llvm::Value *getContextValue() const { return ThisValue; }
259 /// \brief Lookup the captured field decl for a variable.
260 virtual const FieldDecl *lookup(const VarDecl *VD) const {
261 return CaptureFields.lookup(VD);
264 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
265 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
267 static bool classof(const CGCapturedStmtInfo *) {
271 /// \brief Emit the captured statement body.
272 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
273 CGF.incrementProfileCounter(S);
277 /// \brief Get the name of the capture helper.
278 virtual StringRef getHelperName() const { return "__captured_stmt"; }
281 /// \brief The kind of captured statement being generated.
282 CapturedRegionKind Kind;
284 /// \brief Keep the map between VarDecl and FieldDecl.
285 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
287 /// \brief The base address of the captured record, passed in as the first
288 /// argument of the parallel region function.
289 llvm::Value *ThisValue;
291 /// \brief Captured 'this' type.
292 FieldDecl *CXXThisFieldDecl;
294 CGCapturedStmtInfo *CapturedStmtInfo;
296 /// \brief RAII for correct setting/restoring of CapturedStmtInfo.
297 class CGCapturedStmtRAII {
299 CodeGenFunction &CGF;
300 CGCapturedStmtInfo *PrevCapturedStmtInfo;
302 CGCapturedStmtRAII(CodeGenFunction &CGF,
303 CGCapturedStmtInfo *NewCapturedStmtInfo)
304 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
305 CGF.CapturedStmtInfo = NewCapturedStmtInfo;
307 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
310 /// An abstract representation of regular/ObjC call/message targets.
311 class AbstractCallee {
312 /// The function declaration of the callee.
313 const Decl *CalleeDecl;
316 AbstractCallee() : CalleeDecl(nullptr) {}
317 AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
318 AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
319 bool hasFunctionDecl() const {
320 return dyn_cast_or_null<FunctionDecl>(CalleeDecl);
322 const Decl *getDecl() const { return CalleeDecl; }
323 unsigned getNumParams() const {
324 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
325 return FD->getNumParams();
326 return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
328 const ParmVarDecl *getParamDecl(unsigned I) const {
329 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
330 return FD->getParamDecl(I);
331 return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
335 /// \brief Sanitizers enabled for this function.
336 SanitizerSet SanOpts;
338 /// \brief True if CodeGen currently emits code implementing sanitizer checks.
339 bool IsSanitizerScope;
341 /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope.
342 class SanitizerScope {
343 CodeGenFunction *CGF;
345 SanitizerScope(CodeGenFunction *CGF);
349 /// In C++, whether we are code generating a thunk. This controls whether we
350 /// should emit cleanups.
353 /// In ARC, whether we should autorelease the return value.
354 bool AutoreleaseResult;
356 /// Whether we processed a Microsoft-style asm block during CodeGen. These can
357 /// potentially set the return value.
360 const FunctionDecl *CurSEHParent = nullptr;
362 /// True if the current function is an outlined SEH helper. This can be a
363 /// finally block or filter expression.
364 bool IsOutlinedSEHHelper;
366 const CodeGen::CGBlockInfo *BlockInfo;
367 llvm::Value *BlockPointer;
369 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
370 FieldDecl *LambdaThisCaptureField;
372 /// \brief A mapping from NRVO variables to the flags used to indicate
373 /// when the NRVO has been applied to this variable.
374 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
376 EHScopeStack EHStack;
377 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
378 llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
380 llvm::Instruction *CurrentFuncletPad = nullptr;
382 class CallLifetimeEnd final : public EHScopeStack::Cleanup {
387 CallLifetimeEnd(Address addr, llvm::Value *size)
388 : Addr(addr.getPointer()), Size(size) {}
390 void Emit(CodeGenFunction &CGF, Flags flags) override {
391 CGF.EmitLifetimeEnd(Size, Addr);
395 /// Header for data within LifetimeExtendedCleanupStack.
396 struct LifetimeExtendedCleanupHeader {
397 /// The size of the following cleanup object.
399 /// The kind of cleanup to push: a value from the CleanupKind enumeration.
402 size_t getSize() const { return Size; }
403 CleanupKind getKind() const { return Kind; }
406 /// i32s containing the indexes of the cleanup destinations.
407 llvm::AllocaInst *NormalCleanupDest;
409 unsigned NextCleanupDestIndex;
411 /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
412 CGBlockInfo *FirstBlockInfo;
414 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
415 llvm::BasicBlock *EHResumeBlock;
417 /// The exception slot. All landing pads write the current exception pointer
418 /// into this alloca.
419 llvm::Value *ExceptionSlot;
421 /// The selector slot. Under the MandatoryCleanup model, all landing pads
422 /// write the current selector value into this alloca.
423 llvm::AllocaInst *EHSelectorSlot;
425 /// A stack of exception code slots. Entering an __except block pushes a slot
426 /// on the stack and leaving pops one. The __exception_code() intrinsic loads
427 /// a value from the top of the stack.
428 SmallVector<Address, 1> SEHCodeSlotStack;
430 /// Value returned by __exception_info intrinsic.
431 llvm::Value *SEHInfo = nullptr;
433 /// Emits a landing pad for the current EH stack.
434 llvm::BasicBlock *EmitLandingPad();
436 llvm::BasicBlock *getInvokeDestImpl();
439 typename DominatingValue<T>::saved_type saveValueInCond(T value) {
440 return DominatingValue<T>::save(*this, value);
444 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
446 SmallVector<llvm::Value*, 8> ObjCEHValueStack;
448 /// A class controlling the emission of a finally block.
450 /// Where the catchall's edge through the cleanup should go.
451 JumpDest RethrowDest;
453 /// A function to call to enter the catch.
454 llvm::Constant *BeginCatchFn;
456 /// An i1 variable indicating whether or not the @finally is
457 /// running for an exception.
458 llvm::AllocaInst *ForEHVar;
460 /// An i8* variable into which the exception pointer to rethrow
462 llvm::AllocaInst *SavedExnVar;
465 void enter(CodeGenFunction &CGF, const Stmt *Finally,
466 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
467 llvm::Constant *rethrowFn);
468 void exit(CodeGenFunction &CGF);
471 /// Returns true inside SEH __try blocks.
472 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
474 /// Returns true while emitting a cleanuppad.
475 bool isCleanupPadScope() const {
476 return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
479 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
480 /// current full-expression. Safe against the possibility that
481 /// we're currently inside a conditionally-evaluated expression.
482 template <class T, class... As>
483 void pushFullExprCleanup(CleanupKind kind, As... A) {
484 // If we're not in a conditional branch, or if none of the
485 // arguments requires saving, then use the unconditional cleanup.
486 if (!isInConditionalBranch())
487 return EHStack.pushCleanup<T>(kind, A...);
489 // Stash values in a tuple so we can guarantee the order of saves.
490 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
491 SavedTuple Saved{saveValueInCond(A)...};
493 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
494 EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
495 initFullExprCleanup();
498 /// \brief Queue a cleanup to be pushed after finishing the current
500 template <class T, class... As>
501 void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
502 assert(!isInConditionalBranch() && "can't defer conditional cleanup");
504 LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
506 size_t OldSize = LifetimeExtendedCleanupStack.size();
507 LifetimeExtendedCleanupStack.resize(
508 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
510 static_assert(sizeof(Header) % alignof(T) == 0,
511 "Cleanup will be allocated on misaligned address");
512 char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
513 new (Buffer) LifetimeExtendedCleanupHeader(Header);
514 new (Buffer + sizeof(Header)) T(A...);
517 /// Set up the last cleaup that was pushed as a conditional
518 /// full-expression cleanup.
519 void initFullExprCleanup();
521 /// PushDestructorCleanup - Push a cleanup to call the
522 /// complete-object destructor of an object of the given type at the
523 /// given address. Does nothing if T is not a C++ class type with a
524 /// non-trivial destructor.
525 void PushDestructorCleanup(QualType T, Address Addr);
527 /// PushDestructorCleanup - Push a cleanup to call the
528 /// complete-object variant of the given destructor on the object at
529 /// the given address.
530 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, Address Addr);
532 /// PopCleanupBlock - Will pop the cleanup entry on the stack and
533 /// process all branch fixups.
534 void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
536 /// DeactivateCleanupBlock - Deactivates the given cleanup block.
537 /// The block cannot be reactivated. Pops it if it's the top of the
540 /// \param DominatingIP - An instruction which is known to
541 /// dominate the current IP (if set) and which lies along
542 /// all paths of execution between the current IP and the
543 /// the point at which the cleanup comes into scope.
544 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
545 llvm::Instruction *DominatingIP);
547 /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
548 /// Cannot be used to resurrect a deactivated cleanup.
550 /// \param DominatingIP - An instruction which is known to
551 /// dominate the current IP (if set) and which lies along
552 /// all paths of execution between the current IP and the
553 /// the point at which the cleanup comes into scope.
554 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
555 llvm::Instruction *DominatingIP);
557 /// \brief Enters a new scope for capturing cleanups, all of which
558 /// will be executed once the scope is exited.
559 class RunCleanupsScope {
560 EHScopeStack::stable_iterator CleanupStackDepth;
561 size_t LifetimeExtendedCleanupStackSize;
562 bool OldDidCallStackSave;
567 RunCleanupsScope(const RunCleanupsScope &) = delete;
568 void operator=(const RunCleanupsScope &) = delete;
571 CodeGenFunction& CGF;
574 /// \brief Enter a new cleanup scope.
575 explicit RunCleanupsScope(CodeGenFunction &CGF)
576 : PerformCleanup(true), CGF(CGF)
578 CleanupStackDepth = CGF.EHStack.stable_begin();
579 LifetimeExtendedCleanupStackSize =
580 CGF.LifetimeExtendedCleanupStack.size();
581 OldDidCallStackSave = CGF.DidCallStackSave;
582 CGF.DidCallStackSave = false;
585 /// \brief Exit this cleanup scope, emitting any accumulated cleanups.
586 ~RunCleanupsScope() {
591 /// \brief Determine whether this scope requires any cleanups.
592 bool requiresCleanups() const {
593 return CGF.EHStack.stable_begin() != CleanupStackDepth;
596 /// \brief Force the emission of cleanups now, instead of waiting
597 /// until this object is destroyed.
598 /// \param ValuesToReload - A list of values that need to be available at
599 /// the insertion point after cleanup emission. If cleanup emission created
600 /// a shared cleanup block, these value pointers will be rewritten.
601 /// Otherwise, they not will be modified.
602 void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) {
603 assert(PerformCleanup && "Already forced cleanup");
604 CGF.DidCallStackSave = OldDidCallStackSave;
605 CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize,
607 PerformCleanup = false;
611 class LexicalScope : public RunCleanupsScope {
613 SmallVector<const LabelDecl*, 4> Labels;
614 LexicalScope *ParentScope;
616 LexicalScope(const LexicalScope &) = delete;
617 void operator=(const LexicalScope &) = delete;
620 /// \brief Enter a new cleanup scope.
621 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
622 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
623 CGF.CurLexicalScope = this;
624 if (CGDebugInfo *DI = CGF.getDebugInfo())
625 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
628 void addLabel(const LabelDecl *label) {
629 assert(PerformCleanup && "adding label to dead scope?");
630 Labels.push_back(label);
633 /// \brief Exit this cleanup scope, emitting any accumulated
636 if (CGDebugInfo *DI = CGF.getDebugInfo())
637 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
639 // If we should perform a cleanup, force them now. Note that
640 // this ends the cleanup scope before rescoping any labels.
641 if (PerformCleanup) {
642 ApplyDebugLocation DL(CGF, Range.getEnd());
647 /// \brief Force the emission of cleanups now, instead of waiting
648 /// until this object is destroyed.
649 void ForceCleanup() {
650 CGF.CurLexicalScope = ParentScope;
651 RunCleanupsScope::ForceCleanup();
657 bool hasLabels() const {
658 return !Labels.empty();
661 void rescopeLabels();
664 typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
666 /// \brief The scope used to remap some variables as private in the OpenMP
667 /// loop body (or other captured region emitted without outlining), and to
668 /// restore old vars back on exit.
669 class OMPPrivateScope : public RunCleanupsScope {
670 DeclMapTy SavedLocals;
671 DeclMapTy SavedPrivates;
674 OMPPrivateScope(const OMPPrivateScope &) = delete;
675 void operator=(const OMPPrivateScope &) = delete;
678 /// \brief Enter a new OpenMP private scope.
679 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
681 /// \brief Registers \a LocalVD variable as a private and apply \a
682 /// PrivateGen function for it to generate corresponding private variable.
683 /// \a PrivateGen returns an address of the generated private variable.
684 /// \return true if the variable is registered as private, false if it has
685 /// been privatized already.
687 addPrivate(const VarDecl *LocalVD,
688 llvm::function_ref<Address()> PrivateGen) {
689 assert(PerformCleanup && "adding private to dead scope");
691 // Only save it once.
692 if (SavedLocals.count(LocalVD)) return false;
694 // Copy the existing local entry to SavedLocals.
695 auto it = CGF.LocalDeclMap.find(LocalVD);
696 if (it != CGF.LocalDeclMap.end()) {
697 SavedLocals.insert({LocalVD, it->second});
699 SavedLocals.insert({LocalVD, Address::invalid()});
702 // Generate the private entry.
703 Address Addr = PrivateGen();
704 QualType VarTy = LocalVD->getType();
705 if (VarTy->isReferenceType()) {
706 Address Temp = CGF.CreateMemTemp(VarTy);
707 CGF.Builder.CreateStore(Addr.getPointer(), Temp);
710 SavedPrivates.insert({LocalVD, Addr});
715 /// \brief Privatizes local variables previously registered as private.
716 /// Registration is separate from the actual privatization to allow
717 /// initializers use values of the original variables, not the private one.
718 /// This is important, for example, if the private variable is a class
719 /// variable initialized by a constructor that references other private
720 /// variables. But at initialization original variables must be used, not
722 /// \return true if at least one variable was privatized, false otherwise.
724 copyInto(SavedPrivates, CGF.LocalDeclMap);
725 SavedPrivates.clear();
726 return !SavedLocals.empty();
729 void ForceCleanup() {
730 RunCleanupsScope::ForceCleanup();
731 copyInto(SavedLocals, CGF.LocalDeclMap);
735 /// \brief Exit scope - all the mapped variables are restored.
741 /// Checks if the global variable is captured in current function.
742 bool isGlobalVarCaptured(const VarDecl *VD) const {
743 return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
747 /// Copy all the entries in the source map over the corresponding
748 /// entries in the destination, which must exist.
749 static void copyInto(const DeclMapTy &src, DeclMapTy &dest) {
750 for (auto &pair : src) {
751 if (!pair.second.isValid()) {
752 dest.erase(pair.first);
756 auto it = dest.find(pair.first);
757 if (it != dest.end()) {
758 it->second = pair.second;
766 /// \brief Takes the old cleanup stack size and emits the cleanup blocks
767 /// that have been added.
769 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
770 std::initializer_list<llvm::Value **> ValuesToReload = {});
772 /// \brief Takes the old cleanup stack size and emits the cleanup blocks
773 /// that have been added, then adds all lifetime-extended cleanups from
774 /// the given position to the stack.
776 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
777 size_t OldLifetimeExtendedStackSize,
778 std::initializer_list<llvm::Value **> ValuesToReload = {});
780 void ResolveBranchFixups(llvm::BasicBlock *Target);
782 /// The given basic block lies in the current EH scope, but may be a
783 /// target of a potentially scope-crossing jump; get a stable handle
784 /// to which we can perform this jump later.
785 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
786 return JumpDest(Target,
787 EHStack.getInnermostNormalCleanup(),
788 NextCleanupDestIndex++);
791 /// The given basic block lies in the current EH scope, but may be a
792 /// target of a potentially scope-crossing jump; get a stable handle
793 /// to which we can perform this jump later.
794 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
795 return getJumpDestInCurrentScope(createBasicBlock(Name));
798 /// EmitBranchThroughCleanup - Emit a branch from the current insert
799 /// block through the normal cleanup handling code (if any) and then
801 void EmitBranchThroughCleanup(JumpDest Dest);
803 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
804 /// specified destination obviously has no cleanups to run. 'false' is always
805 /// a conservatively correct answer for this method.
806 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
808 /// popCatchScope - Pops the catch scope at the top of the EHScope
809 /// stack, emitting any required code (other than the catch handlers
811 void popCatchScope();
813 llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
814 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
815 llvm::BasicBlock *getMSVCDispatchBlock(EHScopeStack::stable_iterator scope);
817 /// An object to manage conditionally-evaluated expressions.
818 class ConditionalEvaluation {
819 llvm::BasicBlock *StartBB;
822 ConditionalEvaluation(CodeGenFunction &CGF)
823 : StartBB(CGF.Builder.GetInsertBlock()) {}
825 void begin(CodeGenFunction &CGF) {
826 assert(CGF.OutermostConditional != this);
827 if (!CGF.OutermostConditional)
828 CGF.OutermostConditional = this;
831 void end(CodeGenFunction &CGF) {
832 assert(CGF.OutermostConditional != nullptr);
833 if (CGF.OutermostConditional == this)
834 CGF.OutermostConditional = nullptr;
837 /// Returns a block which will be executed prior to each
838 /// evaluation of the conditional code.
839 llvm::BasicBlock *getStartingBlock() const {
844 /// isInConditionalBranch - Return true if we're currently emitting
845 /// one branch or the other of a conditional expression.
846 bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
848 void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
849 assert(isInConditionalBranch());
850 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
851 auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
852 store->setAlignment(addr.getAlignment().getQuantity());
855 /// An RAII object to record that we're evaluating a statement
857 class StmtExprEvaluation {
858 CodeGenFunction &CGF;
860 /// We have to save the outermost conditional: cleanups in a
861 /// statement expression aren't conditional just because the
863 ConditionalEvaluation *SavedOutermostConditional;
866 StmtExprEvaluation(CodeGenFunction &CGF)
867 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
868 CGF.OutermostConditional = nullptr;
871 ~StmtExprEvaluation() {
872 CGF.OutermostConditional = SavedOutermostConditional;
873 CGF.EnsureInsertPoint();
877 /// An object which temporarily prevents a value from being
878 /// destroyed by aggressive peephole optimizations that assume that
879 /// all uses of a value have been realized in the IR.
880 class PeepholeProtection {
881 llvm::Instruction *Inst;
882 friend class CodeGenFunction;
885 PeepholeProtection() : Inst(nullptr) {}
888 /// A non-RAII class containing all the information about a bound
889 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
890 /// this which makes individual mappings very simple; using this
891 /// class directly is useful when you have a variable number of
892 /// opaque values or don't want the RAII functionality for some
894 class OpaqueValueMappingData {
895 const OpaqueValueExpr *OpaqueValue;
897 CodeGenFunction::PeepholeProtection Protection;
899 OpaqueValueMappingData(const OpaqueValueExpr *ov,
901 : OpaqueValue(ov), BoundLValue(boundLValue) {}
903 OpaqueValueMappingData() : OpaqueValue(nullptr) {}
905 static bool shouldBindAsLValue(const Expr *expr) {
906 // gl-values should be bound as l-values for obvious reasons.
907 // Records should be bound as l-values because IR generation
908 // always keeps them in memory. Expressions of function type
909 // act exactly like l-values but are formally required to be
911 return expr->isGLValue() ||
912 expr->getType()->isFunctionType() ||
913 hasAggregateEvaluationKind(expr->getType());
916 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
917 const OpaqueValueExpr *ov,
919 if (shouldBindAsLValue(ov))
920 return bind(CGF, ov, CGF.EmitLValue(e));
921 return bind(CGF, ov, CGF.EmitAnyExpr(e));
924 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
925 const OpaqueValueExpr *ov,
927 assert(shouldBindAsLValue(ov));
928 CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
929 return OpaqueValueMappingData(ov, true);
932 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
933 const OpaqueValueExpr *ov,
935 assert(!shouldBindAsLValue(ov));
936 CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
938 OpaqueValueMappingData data(ov, false);
940 // Work around an extremely aggressive peephole optimization in
941 // EmitScalarConversion which assumes that all other uses of a
943 data.Protection = CGF.protectFromPeepholes(rv);
948 bool isValid() const { return OpaqueValue != nullptr; }
949 void clear() { OpaqueValue = nullptr; }
951 void unbind(CodeGenFunction &CGF) {
952 assert(OpaqueValue && "no data to unbind!");
955 CGF.OpaqueLValues.erase(OpaqueValue);
957 CGF.OpaqueRValues.erase(OpaqueValue);
958 CGF.unprotectFromPeepholes(Protection);
963 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
964 class OpaqueValueMapping {
965 CodeGenFunction &CGF;
966 OpaqueValueMappingData Data;
969 static bool shouldBindAsLValue(const Expr *expr) {
970 return OpaqueValueMappingData::shouldBindAsLValue(expr);
973 /// Build the opaque value mapping for the given conditional
974 /// operator if it's the GNU ?: extension. This is a common
975 /// enough pattern that the convenience operator is really
978 OpaqueValueMapping(CodeGenFunction &CGF,
979 const AbstractConditionalOperator *op) : CGF(CGF) {
980 if (isa<ConditionalOperator>(op))
984 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
985 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
989 /// Build the opaque value mapping for an OpaqueValueExpr whose source
990 /// expression is set to the expression the OVE represents.
991 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
994 assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
995 "for OVE with no source expression");
996 Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
1000 OpaqueValueMapping(CodeGenFunction &CGF,
1001 const OpaqueValueExpr *opaqueValue,
1003 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
1006 OpaqueValueMapping(CodeGenFunction &CGF,
1007 const OpaqueValueExpr *opaqueValue,
1009 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
1017 ~OpaqueValueMapping() {
1018 if (Data.isValid()) Data.unbind(CGF);
1023 CGDebugInfo *DebugInfo;
1024 bool DisableDebugInfo;
1026 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
1027 /// calling llvm.stacksave for multiple VLAs in the same scope.
1028 bool DidCallStackSave;
1030 /// IndirectBranch - The first time an indirect goto is seen we create a block
1031 /// with an indirect branch. Every time we see the address of a label taken,
1032 /// we add the label to the indirect goto. Every subsequent indirect goto is
1033 /// codegen'd as a jump to the IndirectBranch's basic block.
1034 llvm::IndirectBrInst *IndirectBranch;
1036 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
1038 DeclMapTy LocalDeclMap;
1040 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
1041 /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
1043 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
1046 /// Track escaped local variables with auto storage. Used during SEH
1047 /// outlining to produce a call to llvm.localescape.
1048 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
1050 /// LabelMap - This keeps track of the LLVM basic block for each C label.
1051 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
1053 // BreakContinueStack - This keeps track of where break and continue
1054 // statements should jump to.
1055 struct BreakContinue {
1056 BreakContinue(JumpDest Break, JumpDest Continue)
1057 : BreakBlock(Break), ContinueBlock(Continue) {}
1059 JumpDest BreakBlock;
1060 JumpDest ContinueBlock;
1062 SmallVector<BreakContinue, 8> BreakContinueStack;
1064 /// Handles cancellation exit points in OpenMP-related constructs.
1065 class OpenMPCancelExitStack {
1066 /// Tracks cancellation exit point and join point for cancel-related exit
1067 /// and normal exit.
1069 CancelExit() = default;
1070 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
1072 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
1073 OpenMPDirectiveKind Kind = OMPD_unknown;
1074 /// true if the exit block has been emitted already by the special
1075 /// emitExit() call, false if the default codegen is used.
1076 bool HasBeenEmitted = false;
1081 SmallVector<CancelExit, 8> Stack;
1084 OpenMPCancelExitStack() : Stack(1) {}
1085 ~OpenMPCancelExitStack() = default;
1086 /// Fetches the exit block for the current OpenMP construct.
1087 JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
1088 /// Emits exit block with special codegen procedure specific for the related
1089 /// OpenMP construct + emits code for normal construct cleanup.
1090 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1091 const llvm::function_ref<void(CodeGenFunction &)> &CodeGen) {
1092 if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
1093 assert(CGF.getOMPCancelDestination(Kind).isValid());
1094 assert(CGF.HaveInsertPoint());
1095 assert(!Stack.back().HasBeenEmitted);
1096 auto IP = CGF.Builder.saveAndClearIP();
1097 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1099 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1100 CGF.Builder.restoreIP(IP);
1101 Stack.back().HasBeenEmitted = true;
1105 /// Enter the cancel supporting \a Kind construct.
1106 /// \param Kind OpenMP directive that supports cancel constructs.
1107 /// \param HasCancel true, if the construct has inner cancel directive,
1108 /// false otherwise.
1109 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
1110 Stack.push_back({Kind,
1111 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
1113 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
1116 /// Emits default exit point for the cancel construct (if the special one
1117 /// has not be used) + join point for cancel/normal exits.
1118 void exit(CodeGenFunction &CGF) {
1119 if (getExitBlock().isValid()) {
1120 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
1121 bool HaveIP = CGF.HaveInsertPoint();
1122 if (!Stack.back().HasBeenEmitted) {
1124 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1125 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1126 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1128 CGF.EmitBlock(Stack.back().ContBlock.getBlock());
1130 CGF.Builder.CreateUnreachable();
1131 CGF.Builder.ClearInsertionPoint();
1137 OpenMPCancelExitStack OMPCancelStack;
1139 /// Controls insertion of cancellation exit blocks in worksharing constructs.
1140 class OMPCancelStackRAII {
1141 CodeGenFunction &CGF;
1144 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1147 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
1149 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
1154 /// Calculate branch weights appropriate for PGO data
1155 llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
1156 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
1157 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1158 uint64_t LoopCount);
1161 /// Increment the profiler's counter for the given statement by \p StepV.
1162 /// If \p StepV is null, the default increment is 1.
1163 void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
1164 if (CGM.getCodeGenOpts().hasProfileClangInstr())
1165 PGO.emitCounterIncrement(Builder, S, StepV);
1166 PGO.setCurrentStmt(S);
1169 /// Get the profiler's count for the given statement.
1170 uint64_t getProfileCount(const Stmt *S) {
1171 Optional<uint64_t> Count = PGO.getStmtCount(S);
1172 if (!Count.hasValue())
1177 /// Set the profiler's current count.
1178 void setCurrentProfileCount(uint64_t Count) {
1179 PGO.setCurrentRegionCount(Count);
1182 /// Get the profiler's current count. This is generally the count for the most
1183 /// recently incremented counter.
1184 uint64_t getCurrentProfileCount() {
1185 return PGO.getCurrentRegionCount();
1190 /// SwitchInsn - This is nearest current switch instruction. It is null if
1191 /// current context is not in a switch.
1192 llvm::SwitchInst *SwitchInsn;
1193 /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1194 SmallVector<uint64_t, 16> *SwitchWeights;
1196 /// CaseRangeBlock - This block holds if condition check for last case
1197 /// statement range in current switch instruction.
1198 llvm::BasicBlock *CaseRangeBlock;
1200 /// OpaqueLValues - Keeps track of the current set of opaque value
1202 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1203 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1205 // VLASizeMap - This keeps track of the associated size for each VLA type.
1206 // We track this by the size expression rather than the type itself because
1207 // in certain situations, like a const qualifier applied to an VLA typedef,
1208 // multiple VLA types can share the same size expression.
1209 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1210 // enter/leave scopes.
1211 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
1213 /// A block containing a single 'unreachable' instruction. Created
1214 /// lazily by getUnreachableBlock().
1215 llvm::BasicBlock *UnreachableBlock;
1217 /// Counts of the number return expressions in the function.
1218 unsigned NumReturnExprs;
1220 /// Count the number of simple (constant) return expressions in the function.
1221 unsigned NumSimpleReturnExprs;
1223 /// The last regular (non-return) debug location (breakpoint) in the function.
1224 SourceLocation LastStopPoint;
1227 /// A scope within which we are constructing the fields of an object which
1228 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1229 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1230 class FieldConstructionScope {
1232 FieldConstructionScope(CodeGenFunction &CGF, Address This)
1233 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1234 CGF.CXXDefaultInitExprThis = This;
1236 ~FieldConstructionScope() {
1237 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1241 CodeGenFunction &CGF;
1242 Address OldCXXDefaultInitExprThis;
1245 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1246 /// is overridden to be the object under construction.
1247 class CXXDefaultInitExprScope {
1249 CXXDefaultInitExprScope(CodeGenFunction &CGF)
1250 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1251 OldCXXThisAlignment(CGF.CXXThisAlignment) {
1252 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
1253 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
1255 ~CXXDefaultInitExprScope() {
1256 CGF.CXXThisValue = OldCXXThisValue;
1257 CGF.CXXThisAlignment = OldCXXThisAlignment;
1261 CodeGenFunction &CGF;
1262 llvm::Value *OldCXXThisValue;
1263 CharUnits OldCXXThisAlignment;
1266 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1267 /// current loop index is overridden.
1268 class ArrayInitLoopExprScope {
1270 ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
1271 : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
1272 CGF.ArrayInitIndex = Index;
1274 ~ArrayInitLoopExprScope() {
1275 CGF.ArrayInitIndex = OldArrayInitIndex;
1279 CodeGenFunction &CGF;
1280 llvm::Value *OldArrayInitIndex;
1283 class InlinedInheritingConstructorScope {
1285 InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
1286 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1287 OldCurCodeDecl(CGF.CurCodeDecl),
1288 OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1289 OldCXXABIThisValue(CGF.CXXABIThisValue),
1290 OldCXXThisValue(CGF.CXXThisValue),
1291 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1292 OldCXXThisAlignment(CGF.CXXThisAlignment),
1293 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1294 OldCXXInheritedCtorInitExprArgs(
1295 std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1297 CGF.CurFuncDecl = CGF.CurCodeDecl =
1298 cast<CXXConstructorDecl>(GD.getDecl());
1299 CGF.CXXABIThisDecl = nullptr;
1300 CGF.CXXABIThisValue = nullptr;
1301 CGF.CXXThisValue = nullptr;
1302 CGF.CXXABIThisAlignment = CharUnits();
1303 CGF.CXXThisAlignment = CharUnits();
1304 CGF.ReturnValue = Address::invalid();
1305 CGF.FnRetTy = QualType();
1306 CGF.CXXInheritedCtorInitExprArgs.clear();
1308 ~InlinedInheritingConstructorScope() {
1309 CGF.CurGD = OldCurGD;
1310 CGF.CurFuncDecl = OldCurFuncDecl;
1311 CGF.CurCodeDecl = OldCurCodeDecl;
1312 CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1313 CGF.CXXABIThisValue = OldCXXABIThisValue;
1314 CGF.CXXThisValue = OldCXXThisValue;
1315 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1316 CGF.CXXThisAlignment = OldCXXThisAlignment;
1317 CGF.ReturnValue = OldReturnValue;
1318 CGF.FnRetTy = OldFnRetTy;
1319 CGF.CXXInheritedCtorInitExprArgs =
1320 std::move(OldCXXInheritedCtorInitExprArgs);
1324 CodeGenFunction &CGF;
1325 GlobalDecl OldCurGD;
1326 const Decl *OldCurFuncDecl;
1327 const Decl *OldCurCodeDecl;
1328 ImplicitParamDecl *OldCXXABIThisDecl;
1329 llvm::Value *OldCXXABIThisValue;
1330 llvm::Value *OldCXXThisValue;
1331 CharUnits OldCXXABIThisAlignment;
1332 CharUnits OldCXXThisAlignment;
1333 Address OldReturnValue;
1334 QualType OldFnRetTy;
1335 CallArgList OldCXXInheritedCtorInitExprArgs;
1339 /// CXXThisDecl - When generating code for a C++ member function,
1340 /// this will hold the implicit 'this' declaration.
1341 ImplicitParamDecl *CXXABIThisDecl;
1342 llvm::Value *CXXABIThisValue;
1343 llvm::Value *CXXThisValue;
1344 CharUnits CXXABIThisAlignment;
1345 CharUnits CXXThisAlignment;
1347 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1348 /// this expression.
1349 Address CXXDefaultInitExprThis = Address::invalid();
1351 /// The current array initialization index when evaluating an
1352 /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
1353 llvm::Value *ArrayInitIndex = nullptr;
1355 /// The values of function arguments to use when evaluating
1356 /// CXXInheritedCtorInitExprs within this context.
1357 CallArgList CXXInheritedCtorInitExprArgs;
1359 /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1360 /// destructor, this will hold the implicit argument (e.g. VTT).
1361 ImplicitParamDecl *CXXStructorImplicitParamDecl;
1362 llvm::Value *CXXStructorImplicitParamValue;
1364 /// OutermostConditional - Points to the outermost active
1365 /// conditional control. This is used so that we know if a
1366 /// temporary should be destroyed conditionally.
1367 ConditionalEvaluation *OutermostConditional;
1369 /// The current lexical scope.
1370 LexicalScope *CurLexicalScope;
1372 /// The current source location that should be used for exception
1374 SourceLocation CurEHLocation;
1376 /// BlockByrefInfos - For each __block variable, contains
1377 /// information about the layout of the variable.
1378 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
1380 /// Used by -fsanitize=nullability-return to determine whether the return
1381 /// value can be checked.
1382 llvm::Value *RetValNullabilityPrecondition = nullptr;
1384 /// Check if -fsanitize=nullability-return instrumentation is required for
1386 bool requiresReturnValueNullabilityCheck() const {
1387 return RetValNullabilityPrecondition;
1390 llvm::BasicBlock *TerminateLandingPad;
1391 llvm::BasicBlock *TerminateHandler;
1392 llvm::BasicBlock *TrapBB;
1394 /// True if we need emit the life-time markers.
1395 const bool ShouldEmitLifetimeMarkers;
1397 /// Add a kernel metadata node to the named metadata node 'opencl.kernels'.
1398 /// In the kernel metadata node, reference the kernel function and metadata
1399 /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2):
1400 /// - A node for the vec_type_hint(<type>) qualifier contains string
1401 /// "vec_type_hint", an undefined value of the <type> data type,
1402 /// and a Boolean that is true if the <type> is integer and signed.
1403 /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string
1404 /// "work_group_size_hint", and three 32-bit integers X, Y and Z.
1405 /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string
1406 /// "reqd_work_group_size", and three 32-bit integers X, Y and Z.
1407 void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
1408 llvm::Function *Fn);
1411 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
1414 CodeGenTypes &getTypes() const { return CGM.getTypes(); }
1415 ASTContext &getContext() const { return CGM.getContext(); }
1416 CGDebugInfo *getDebugInfo() {
1417 if (DisableDebugInfo)
1421 void disableDebugInfo() { DisableDebugInfo = true; }
1422 void enableDebugInfo() { DisableDebugInfo = false; }
1424 bool shouldUseFusedARCCalls() {
1425 return CGM.getCodeGenOpts().OptimizationLevel == 0;
1428 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
1430 /// Returns a pointer to the function's exception object and selector slot,
1431 /// which is assigned in every landing pad.
1432 Address getExceptionSlot();
1433 Address getEHSelectorSlot();
1435 /// Returns the contents of the function's exception object and selector
1437 llvm::Value *getExceptionFromSlot();
1438 llvm::Value *getSelectorFromSlot();
1440 Address getNormalCleanupDestSlot();
1442 llvm::BasicBlock *getUnreachableBlock() {
1443 if (!UnreachableBlock) {
1444 UnreachableBlock = createBasicBlock("unreachable");
1445 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
1447 return UnreachableBlock;
1450 llvm::BasicBlock *getInvokeDest() {
1451 if (!EHStack.requiresLandingPad()) return nullptr;
1452 return getInvokeDestImpl();
1455 bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
1457 const TargetInfo &getTarget() const { return Target; }
1458 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
1460 //===--------------------------------------------------------------------===//
1462 //===--------------------------------------------------------------------===//
1464 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
1466 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1467 Address arrayEndPointer,
1468 QualType elementType,
1469 CharUnits elementAlignment,
1470 Destroyer *destroyer);
1471 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1472 llvm::Value *arrayEnd,
1473 QualType elementType,
1474 CharUnits elementAlignment,
1475 Destroyer *destroyer);
1477 void pushDestroy(QualType::DestructionKind dtorKind,
1478 Address addr, QualType type);
1479 void pushEHDestroy(QualType::DestructionKind dtorKind,
1480 Address addr, QualType type);
1481 void pushDestroy(CleanupKind kind, Address addr, QualType type,
1482 Destroyer *destroyer, bool useEHCleanupForArray);
1483 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
1484 QualType type, Destroyer *destroyer,
1485 bool useEHCleanupForArray);
1486 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1487 llvm::Value *CompletePtr,
1488 QualType ElementType);
1489 void pushStackRestore(CleanupKind kind, Address SPMem);
1490 void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
1491 bool useEHCleanupForArray);
1492 llvm::Function *generateDestroyHelper(Address addr, QualType type,
1493 Destroyer *destroyer,
1494 bool useEHCleanupForArray,
1496 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
1497 QualType elementType, CharUnits elementAlign,
1498 Destroyer *destroyer,
1499 bool checkZeroLength, bool useEHCleanup);
1501 Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
1503 /// Determines whether an EH cleanup is required to destroy a type
1504 /// with the given destruction kind.
1505 bool needsEHCleanup(QualType::DestructionKind kind) {
1507 case QualType::DK_none:
1509 case QualType::DK_cxx_destructor:
1510 case QualType::DK_objc_weak_lifetime:
1511 return getLangOpts().Exceptions;
1512 case QualType::DK_objc_strong_lifetime:
1513 return getLangOpts().Exceptions &&
1514 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1516 llvm_unreachable("bad destruction kind");
1519 CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1520 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1523 //===--------------------------------------------------------------------===//
1525 //===--------------------------------------------------------------------===//
1527 void GenerateObjCMethod(const ObjCMethodDecl *OMD);
1529 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
1531 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
1532 void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1533 const ObjCPropertyImplDecl *PID);
1534 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1535 const ObjCPropertyImplDecl *propImpl,
1536 const ObjCMethodDecl *GetterMothodDecl,
1537 llvm::Constant *AtomicHelperFn);
1539 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1540 ObjCMethodDecl *MD, bool ctor);
1542 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1543 /// for the given property.
1544 void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1545 const ObjCPropertyImplDecl *PID);
1546 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1547 const ObjCPropertyImplDecl *propImpl,
1548 llvm::Constant *AtomicHelperFn);
1550 //===--------------------------------------------------------------------===//
1552 //===--------------------------------------------------------------------===//
1554 llvm::Value *EmitBlockLiteral(const BlockExpr *);
1555 static void destroyBlockInfos(CGBlockInfo *info);
1557 llvm::Function *GenerateBlockFunction(GlobalDecl GD,
1558 const CGBlockInfo &Info,
1559 const DeclMapTy &ldm,
1560 bool IsLambdaConversionToBlock);
1562 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1563 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
1564 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
1565 const ObjCPropertyImplDecl *PID);
1566 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
1567 const ObjCPropertyImplDecl *PID);
1568 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
1570 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
1572 class AutoVarEmission;
1574 void emitByrefStructureInit(const AutoVarEmission &emission);
1575 void enterByrefCleanup(const AutoVarEmission &emission);
1577 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
1580 Address LoadBlockStruct();
1581 Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
1583 /// BuildBlockByrefAddress - Computes the location of the
1584 /// data in a variable which is declared as __block.
1585 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
1586 bool followForward = true);
1587 Address emitBlockByrefAddress(Address baseAddr,
1588 const BlockByrefInfo &info,
1590 const llvm::Twine &name);
1592 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
1594 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
1596 void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1597 const CGFunctionInfo &FnInfo);
1598 /// \brief Emit code for the start of a function.
1599 /// \param Loc The location to be associated with the function.
1600 /// \param StartLoc The location of the function body.
1601 void StartFunction(GlobalDecl GD,
1604 const CGFunctionInfo &FnInfo,
1605 const FunctionArgList &Args,
1606 SourceLocation Loc = SourceLocation(),
1607 SourceLocation StartLoc = SourceLocation());
1609 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
1611 void EmitConstructorBody(FunctionArgList &Args);
1612 void EmitDestructorBody(FunctionArgList &Args);
1613 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
1614 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
1615 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
1617 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
1618 CallArgList &CallArgs);
1619 void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
1620 void EmitLambdaBlockInvokeBody();
1621 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
1622 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
1623 void EmitAsanPrologueOrEpilogue(bool Prologue);
1625 /// \brief Emit the unified return block, trying to avoid its emission when
1627 /// \return The debug location of the user written return statement if the
1628 /// return block is is avoided.
1629 llvm::DebugLoc EmitReturnBlock();
1631 /// FinishFunction - Complete IR generation of the current function. It is
1632 /// legal to call this function even if there is no current insertion point.
1633 void FinishFunction(SourceLocation EndLoc=SourceLocation());
1635 void StartThunk(llvm::Function *Fn, GlobalDecl GD,
1636 const CGFunctionInfo &FnInfo);
1638 void EmitCallAndReturnForThunk(llvm::Constant *Callee,
1639 const ThunkInfo *Thunk);
1643 /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
1644 void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
1645 llvm::Value *Callee);
1647 /// Generate a thunk for the given method.
1648 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1649 GlobalDecl GD, const ThunkInfo &Thunk);
1651 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
1652 const CGFunctionInfo &FnInfo,
1653 GlobalDecl GD, const ThunkInfo &Thunk);
1655 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1656 FunctionArgList &Args);
1658 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
1660 /// Struct with all informations about dynamic [sub]class needed to set vptr.
1663 const CXXRecordDecl *NearestVBase;
1664 CharUnits OffsetFromNearestVBase;
1665 const CXXRecordDecl *VTableClass;
1668 /// Initialize the vtable pointer of the given subobject.
1669 void InitializeVTablePointer(const VPtr &vptr);
1671 typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
1673 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1674 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
1676 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
1677 CharUnits OffsetFromNearestVBase,
1678 bool BaseIsNonVirtualPrimaryBase,
1679 const CXXRecordDecl *VTableClass,
1680 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
1682 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1684 /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1686 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
1687 const CXXRecordDecl *VTableClass);
1689 enum CFITypeCheckKind {
1693 CFITCK_UnrelatedCast,
1697 /// \brief Derived is the presumed address of an object of type T after a
1698 /// cast. If T is a polymorphic class type, emit a check that the virtual
1699 /// table for Derived belongs to a class derived from T.
1700 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
1701 bool MayBeNull, CFITypeCheckKind TCK,
1702 SourceLocation Loc);
1704 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
1705 /// If vptr CFI is enabled, emit a check that VTable is valid.
1706 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
1707 CFITypeCheckKind TCK, SourceLocation Loc);
1709 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
1710 /// RD using llvm.type.test.
1711 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
1712 CFITypeCheckKind TCK, SourceLocation Loc);
1714 /// If whole-program virtual table optimization is enabled, emit an assumption
1715 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
1716 /// enabled, emit a check that VTable is a member of RD's type identifier.
1717 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
1718 llvm::Value *VTable, SourceLocation Loc);
1720 /// Returns whether we should perform a type checked load when loading a
1721 /// virtual function for virtual calls to members of RD. This is generally
1722 /// true when both vcall CFI and whole-program-vtables are enabled.
1723 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
1725 /// Emit a type checked load from the given vtable.
1726 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
1727 uint64_t VTableByteOffset);
1729 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
1730 /// expr can be devirtualized.
1731 bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
1732 const CXXMethodDecl *MD);
1734 /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1735 /// given phase of destruction for a destructor. The end result
1736 /// should call destructors on members and base classes in reverse
1737 /// order of their construction.
1738 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1740 /// ShouldInstrumentFunction - Return true if the current function should be
1741 /// instrumented with __cyg_profile_func_* calls
1742 bool ShouldInstrumentFunction();
1744 /// ShouldXRayInstrument - Return true if the current function should be
1745 /// instrumented with XRay nop sleds.
1746 bool ShouldXRayInstrumentFunction() const;
1748 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
1749 /// instrumentation function with the current function and the call site, if
1750 /// function instrumentation is enabled.
1751 void EmitFunctionInstrumentation(const char *Fn);
1753 /// EmitMCountInstrumentation - Emit call to .mcount.
1754 void EmitMCountInstrumentation();
1756 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
1757 /// arguments for the given function. This is also responsible for naming the
1758 /// LLVM function arguments.
1759 void EmitFunctionProlog(const CGFunctionInfo &FI,
1761 const FunctionArgList &Args);
1763 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
1764 /// given temporary.
1765 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
1766 SourceLocation EndLoc);
1768 /// Emit a test that checks if the return value \p RV is nonnull.
1769 void EmitReturnValueCheck(llvm::Value *RV, SourceLocation EndLoc);
1771 /// EmitStartEHSpec - Emit the start of the exception spec.
1772 void EmitStartEHSpec(const Decl *D);
1774 /// EmitEndEHSpec - Emit the end of the exception spec.
1775 void EmitEndEHSpec(const Decl *D);
1777 /// getTerminateLandingPad - Return a landing pad that just calls terminate.
1778 llvm::BasicBlock *getTerminateLandingPad();
1780 /// getTerminateHandler - Return a handler (not a landing pad, just
1781 /// a catch handler) that just calls terminate. This is used when
1782 /// a terminate scope encloses a try.
1783 llvm::BasicBlock *getTerminateHandler();
1785 llvm::Type *ConvertTypeForMem(QualType T);
1786 llvm::Type *ConvertType(QualType T);
1787 llvm::Type *ConvertType(const TypeDecl *T) {
1788 return ConvertType(getContext().getTypeDeclType(T));
1791 /// LoadObjCSelf - Load the value of self. This function is only valid while
1792 /// generating code for an Objective-C method.
1793 llvm::Value *LoadObjCSelf();
1795 /// TypeOfSelfObject - Return type of object that this self represents.
1796 QualType TypeOfSelfObject();
1798 /// hasAggregateLLVMType - Return true if the specified AST type will map into
1799 /// an aggregate LLVM type or is void.
1800 static TypeEvaluationKind getEvaluationKind(QualType T);
1802 static bool hasScalarEvaluationKind(QualType T) {
1803 return getEvaluationKind(T) == TEK_Scalar;
1806 static bool hasAggregateEvaluationKind(QualType T) {
1807 return getEvaluationKind(T) == TEK_Aggregate;
1810 /// createBasicBlock - Create an LLVM basic block.
1811 llvm::BasicBlock *createBasicBlock(const Twine &name = "",
1812 llvm::Function *parent = nullptr,
1813 llvm::BasicBlock *before = nullptr) {
1815 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
1817 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
1821 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
1823 JumpDest getJumpDestForLabel(const LabelDecl *S);
1825 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
1826 /// another basic block, simplify it. This assumes that no other code could
1827 /// potentially reference the basic block.
1828 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
1830 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
1831 /// adding a fall-through branch from the current insert block if
1832 /// necessary. It is legal to call this function even if there is no current
1833 /// insertion point.
1835 /// IsFinished - If true, indicates that the caller has finished emitting
1836 /// branches to the given block and does not expect to emit code into it. This
1837 /// means the block can be ignored if it is unreachable.
1838 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
1840 /// EmitBlockAfterUses - Emit the given block somewhere hopefully
1841 /// near its uses, and leave the insertion point in it.
1842 void EmitBlockAfterUses(llvm::BasicBlock *BB);
1844 /// EmitBranch - Emit a branch to the specified basic block from the current
1845 /// insert block, taking care to avoid creation of branches from dummy
1846 /// blocks. It is legal to call this function even if there is no current
1847 /// insertion point.
1849 /// This function clears the current insertion point. The caller should follow
1850 /// calls to this function with calls to Emit*Block prior to generation new
1852 void EmitBranch(llvm::BasicBlock *Block);
1854 /// HaveInsertPoint - True if an insertion point is defined. If not, this
1855 /// indicates that the current code being emitted is unreachable.
1856 bool HaveInsertPoint() const {
1857 return Builder.GetInsertBlock() != nullptr;
1860 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
1861 /// emitted IR has a place to go. Note that by definition, if this function
1862 /// creates a block then that block is unreachable; callers may do better to
1863 /// detect when no insertion point is defined and simply skip IR generation.
1864 void EnsureInsertPoint() {
1865 if (!HaveInsertPoint())
1866 EmitBlock(createBasicBlock());
1869 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1870 /// specified stmt yet.
1871 void ErrorUnsupported(const Stmt *S, const char *Type);
1873 //===--------------------------------------------------------------------===//
1875 //===--------------------------------------------------------------------===//
1877 LValue MakeAddrLValue(Address Addr, QualType T,
1878 AlignmentSource AlignSource = AlignmentSource::Type) {
1879 return LValue::MakeAddr(Addr, T, getContext(), AlignSource,
1880 CGM.getTBAAInfo(T));
1883 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
1884 AlignmentSource AlignSource = AlignmentSource::Type) {
1885 return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
1886 AlignSource, CGM.getTBAAInfo(T));
1889 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
1890 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
1891 CharUnits getNaturalTypeAlignment(QualType T,
1892 AlignmentSource *Source = nullptr,
1893 bool forPointeeType = false);
1894 CharUnits getNaturalPointeeTypeAlignment(QualType T,
1895 AlignmentSource *Source = nullptr);
1897 Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy,
1898 AlignmentSource *Source = nullptr);
1899 LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy);
1901 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
1902 AlignmentSource *Source = nullptr);
1903 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
1905 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
1906 /// block. The caller is responsible for setting an appropriate alignment on
1908 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
1909 const Twine &Name = "tmp");
1910 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
1911 const Twine &Name = "tmp");
1913 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
1914 /// default ABI alignment of the given LLVM type.
1916 /// IMPORTANT NOTE: This is *not* generally the right alignment for
1917 /// any given AST type that happens to have been lowered to the
1918 /// given IR type. This should only ever be used for function-local,
1919 /// IR-driven manipulations like saving and restoring a value. Do
1920 /// not hand this address off to arbitrary IRGen routines, and especially
1921 /// do not pass it as an argument to a function that might expect a
1922 /// properly ABI-aligned value.
1923 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
1924 const Twine &Name = "tmp");
1926 /// InitTempAlloca - Provide an initial value for the given alloca which
1927 /// will be observable at all locations in the function.
1929 /// The address should be something that was returned from one of
1930 /// the CreateTempAlloca or CreateMemTemp routines, and the
1931 /// initializer must be valid in the entry block (i.e. it must
1932 /// either be a constant or an argument value).
1933 void InitTempAlloca(Address Alloca, llvm::Value *Value);
1935 /// CreateIRTemp - Create a temporary IR object of the given type, with
1936 /// appropriate alignment. This routine should only be used when an temporary
1937 /// value needs to be stored into an alloca (for example, to avoid explicit
1938 /// PHI construction), but the type is the IR type, not the type appropriate
1939 /// for storing in memory.
1941 /// That is, this is exactly equivalent to CreateMemTemp, but calling
1942 /// ConvertType instead of ConvertTypeForMem.
1943 Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
1945 /// CreateMemTemp - Create a temporary memory object of the given type, with
1946 /// appropriate alignment.
1947 Address CreateMemTemp(QualType T, const Twine &Name = "tmp");
1948 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp");
1950 /// CreateAggTemp - Create a temporary memory object for the given
1952 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
1953 return AggValueSlot::forAddr(CreateMemTemp(T, Name),
1955 AggValueSlot::IsNotDestructed,
1956 AggValueSlot::DoesNotNeedGCBarriers,
1957 AggValueSlot::IsNotAliased);
1960 /// Emit a cast to void* in the appropriate address space.
1961 llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
1963 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1964 /// expression and compare the result against zero, returning an Int1Ty value.
1965 llvm::Value *EvaluateExprAsBool(const Expr *E);
1967 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1968 void EmitIgnoredExpr(const Expr *E);
1970 /// EmitAnyExpr - Emit code to compute the specified expression which can have
1971 /// any type. The result is returned as an RValue struct. If this is an
1972 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1973 /// the result should be returned.
1975 /// \param ignoreResult True if the resulting value isn't used.
1976 RValue EmitAnyExpr(const Expr *E,
1977 AggValueSlot aggSlot = AggValueSlot::ignored(),
1978 bool ignoreResult = false);
1980 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1981 // or the value of the expression, depending on how va_list is defined.
1982 Address EmitVAListRef(const Expr *E);
1984 /// Emit a "reference" to a __builtin_ms_va_list; this is
1985 /// always the value of the expression, because a __builtin_ms_va_list is a
1986 /// pointer to a char.
1987 Address EmitMSVAListRef(const Expr *E);
1989 /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
1990 /// always be accessible even if no aggregate location is provided.
1991 RValue EmitAnyExprToTemp(const Expr *E);
1993 /// EmitAnyExprToMem - Emits the code necessary to evaluate an
1994 /// arbitrary expression into the given memory location.
1995 void EmitAnyExprToMem(const Expr *E, Address Location,
1996 Qualifiers Quals, bool IsInitializer);
1998 void EmitAnyExprToExn(const Expr *E, Address Addr);
2000 /// EmitExprAsInit - Emits the code necessary to initialize a
2001 /// location in memory with the given initializer.
2002 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2003 bool capturedByInit);
2005 /// hasVolatileMember - returns true if aggregate type has a volatile
2007 bool hasVolatileMember(QualType T) {
2008 if (const RecordType *RT = T->getAs<RecordType>()) {
2009 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2010 return RD->hasVolatileMember();
2014 /// EmitAggregateCopy - Emit an aggregate assignment.
2016 /// The difference to EmitAggregateCopy is that tail padding is not copied.
2017 /// This is required for correctness when assigning non-POD structures in C++.
2018 void EmitAggregateAssign(Address DestPtr, Address SrcPtr,
2020 bool IsVolatile = hasVolatileMember(EltTy);
2021 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true);
2024 void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr,
2025 QualType DestTy, QualType SrcTy) {
2026 EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
2027 /*IsAssignment=*/false);
2030 /// EmitAggregateCopy - Emit an aggregate copy.
2032 /// \param isVolatile - True iff either the source or the destination is
2034 /// \param isAssignment - If false, allow padding to be copied. This often
2035 /// yields more efficient.
2036 void EmitAggregateCopy(Address DestPtr, Address SrcPtr,
2037 QualType EltTy, bool isVolatile=false,
2038 bool isAssignment = false);
2040 /// GetAddrOfLocalVar - Return the address of a local variable.
2041 Address GetAddrOfLocalVar(const VarDecl *VD) {
2042 auto it = LocalDeclMap.find(VD);
2043 assert(it != LocalDeclMap.end() &&
2044 "Invalid argument to GetAddrOfLocalVar(), no decl!");
2048 /// getOpaqueLValueMapping - Given an opaque value expression (which
2049 /// must be mapped to an l-value), return its mapping.
2050 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
2051 assert(OpaqueValueMapping::shouldBindAsLValue(e));
2053 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
2054 it = OpaqueLValues.find(e);
2055 assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
2059 /// getOpaqueRValueMapping - Given an opaque value expression (which
2060 /// must be mapped to an r-value), return its mapping.
2061 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
2062 assert(!OpaqueValueMapping::shouldBindAsLValue(e));
2064 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
2065 it = OpaqueRValues.find(e);
2066 assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
2070 /// Get the index of the current ArrayInitLoopExpr, if any.
2071 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2073 /// getAccessedFieldNo - Given an encoded value and a result number, return
2074 /// the input field number being accessed.
2075 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2077 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
2078 llvm::BasicBlock *GetIndirectGotoBlock();
2080 /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
2081 static bool IsWrappedCXXThis(const Expr *E);
2083 /// EmitNullInitialization - Generate code to set a value of the given type to
2084 /// null, If the type contains data member pointers, they will be initialized
2085 /// to -1 in accordance with the Itanium C++ ABI.
2086 void EmitNullInitialization(Address DestPtr, QualType Ty);
2088 /// Emits a call to an LLVM variable-argument intrinsic, either
2089 /// \c llvm.va_start or \c llvm.va_end.
2090 /// \param ArgValue A reference to the \c va_list as emitted by either
2091 /// \c EmitVAListRef or \c EmitMSVAListRef.
2092 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2093 /// calls \c llvm.va_end.
2094 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2096 /// Generate code to get an argument from the passed in pointer
2097 /// and update it accordingly.
2098 /// \param VE The \c VAArgExpr for which to generate code.
2099 /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2100 /// either \c EmitVAListRef or \c EmitMSVAListRef.
2101 /// \returns A pointer to the argument.
2102 // FIXME: We should be able to get rid of this method and use the va_arg
2103 // instruction in LLVM instead once it works well enough.
2104 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
2106 /// emitArrayLength - Compute the length of an array, even if it's a
2107 /// VLA, and drill down to the base element type.
2108 llvm::Value *emitArrayLength(const ArrayType *arrayType,
2112 /// EmitVLASize - Capture all the sizes for the VLA expressions in
2113 /// the given variably-modified type and store them in the VLASizeMap.
2115 /// This function can be called with a null (unreachable) insert point.
2116 void EmitVariablyModifiedType(QualType Ty);
2118 /// getVLASize - Returns an LLVM value that corresponds to the size,
2119 /// in non-variably-sized elements, of a variable length array type,
2120 /// plus that largest non-variably-sized element type. Assumes that
2121 /// the type has already been emitted with EmitVariablyModifiedType.
2122 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
2123 std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
2125 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2126 /// generating code for an C++ member function.
2127 llvm::Value *LoadCXXThis() {
2128 assert(CXXThisValue && "no 'this' value for this function");
2129 return CXXThisValue;
2131 Address LoadCXXThisAddress();
2133 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2135 // FIXME: Every place that calls LoadCXXVTT is something
2136 // that needs to be abstracted properly.
2137 llvm::Value *LoadCXXVTT() {
2138 assert(CXXStructorImplicitParamValue && "no VTT value for this function");
2139 return CXXStructorImplicitParamValue;
2142 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
2143 /// complete class to the given direct base.
2145 GetAddressOfDirectBaseInCompleteClass(Address Value,
2146 const CXXRecordDecl *Derived,
2147 const CXXRecordDecl *Base,
2148 bool BaseIsVirtual);
2150 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2152 /// GetAddressOfBaseClass - This function will add the necessary delta to the
2153 /// load of 'this' and returns address of the base class.
2154 Address GetAddressOfBaseClass(Address Value,
2155 const CXXRecordDecl *Derived,
2156 CastExpr::path_const_iterator PathBegin,
2157 CastExpr::path_const_iterator PathEnd,
2158 bool NullCheckValue, SourceLocation Loc);
2160 Address GetAddressOfDerivedClass(Address Value,
2161 const CXXRecordDecl *Derived,
2162 CastExpr::path_const_iterator PathBegin,
2163 CastExpr::path_const_iterator PathEnd,
2164 bool NullCheckValue);
2166 /// GetVTTParameter - Return the VTT parameter that should be passed to a
2167 /// base constructor/destructor with virtual bases.
2168 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2169 /// to ItaniumCXXABI.cpp together with all the references to VTT.
2170 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2173 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2174 CXXCtorType CtorType,
2175 const FunctionArgList &Args,
2176 SourceLocation Loc);
2177 // It's important not to confuse this and the previous function. Delegating
2178 // constructors are the C++0x feature. The constructor delegate optimization
2179 // is used to reduce duplication in the base and complete consturctors where
2180 // they are substantially the same.
2181 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2182 const FunctionArgList &Args);
2184 /// Emit a call to an inheriting constructor (that is, one that invokes a
2185 /// constructor inherited from a base class) by inlining its definition. This
2186 /// is necessary if the ABI does not support forwarding the arguments to the
2187 /// base class constructor (because they're variadic or similar).
2188 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2189 CXXCtorType CtorType,
2190 bool ForVirtualBase,
2194 /// Emit a call to a constructor inherited from a base class, passing the
2195 /// current constructor's arguments along unmodified (without even making
2197 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
2198 bool ForVirtualBase, Address This,
2199 bool InheritedFromVBase,
2200 const CXXInheritedCtorInitExpr *E);
2202 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2203 bool ForVirtualBase, bool Delegating,
2204 Address This, const CXXConstructExpr *E);
2206 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2207 bool ForVirtualBase, bool Delegating,
2208 Address This, CallArgList &Args);
2210 /// Emit assumption load for all bases. Requires to be be called only on
2211 /// most-derived class and not under construction of the object.
2212 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2214 /// Emit assumption that vptr load == global vtable.
2215 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2217 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2218 Address This, Address Src,
2219 const CXXConstructExpr *E);
2221 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2222 const ArrayType *ArrayTy,
2224 const CXXConstructExpr *E,
2225 bool ZeroInitialization = false);
2227 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2228 llvm::Value *NumElements,
2230 const CXXConstructExpr *E,
2231 bool ZeroInitialization = false);
2233 static Destroyer destroyCXXObject;
2235 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
2236 bool ForVirtualBase, bool Delegating,
2239 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2240 llvm::Type *ElementTy, Address NewPtr,
2241 llvm::Value *NumElements,
2242 llvm::Value *AllocSizeWithoutCookie);
2244 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2247 llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
2248 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2250 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
2251 void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
2253 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
2254 QualType DeleteTy, llvm::Value *NumElements = nullptr,
2255 CharUnits CookieSize = CharUnits());
2257 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
2258 const Expr *Arg, bool IsDelete);
2260 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2261 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2262 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
2264 /// \brief Situations in which we might emit a check for the suitability of a
2265 /// pointer or glvalue.
2266 enum TypeCheckKind {
2267 /// Checking the operand of a load. Must be suitably sized and aligned.
2269 /// Checking the destination of a store. Must be suitably sized and aligned.
2271 /// Checking the bound value in a reference binding. Must be suitably sized
2272 /// and aligned, but is not required to refer to an object (until the
2273 /// reference is used), per core issue 453.
2274 TCK_ReferenceBinding,
2275 /// Checking the object expression in a non-static data member access. Must
2276 /// be an object within its lifetime.
2278 /// Checking the 'this' pointer for a call to a non-static member function.
2279 /// Must be an object within its lifetime.
2281 /// Checking the 'this' pointer for a constructor call.
2282 TCK_ConstructorCall,
2283 /// Checking the operand of a static_cast to a derived pointer type. Must be
2284 /// null or an object within its lifetime.
2285 TCK_DowncastPointer,
2286 /// Checking the operand of a static_cast to a derived reference type. Must
2287 /// be an object within its lifetime.
2288 TCK_DowncastReference,
2289 /// Checking the operand of a cast to a base object. Must be suitably sized
2292 /// Checking the operand of a cast to a virtual base object. Must be an
2293 /// object within its lifetime.
2294 TCK_UpcastToVirtualBase,
2295 /// Checking the value assigned to a _Nonnull pointer. Must not be null.
2299 /// \brief Whether any type-checking sanitizers are enabled. If \c false,
2300 /// calls to EmitTypeCheck can be skipped.
2301 bool sanitizePerformTypeCheck() const;
2303 /// \brief Emit a check that \p V is the address of storage of the
2304 /// appropriate size and alignment for an object of type \p Type.
2305 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
2306 QualType Type, CharUnits Alignment = CharUnits::Zero(),
2307 SanitizerSet SkippedChecks = SanitizerSet());
2309 /// \brief Emit a check that \p Base points into an array object, which
2310 /// we can access at index \p Index. \p Accessed should be \c false if we
2311 /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
2312 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
2313 QualType IndexType, bool Accessed);
2315 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2316 bool isInc, bool isPre);
2317 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
2318 bool isInc, bool isPre);
2320 void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
2321 llvm::Value *OffsetValue = nullptr) {
2322 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2326 /// Converts Location to a DebugLoc, if debug information is enabled.
2327 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
2330 //===--------------------------------------------------------------------===//
2331 // Declaration Emission
2332 //===--------------------------------------------------------------------===//
2334 /// EmitDecl - Emit a declaration.
2336 /// This function can be called with a null (unreachable) insert point.
2337 void EmitDecl(const Decl &D);
2339 /// EmitVarDecl - Emit a local variable declaration.
2341 /// This function can be called with a null (unreachable) insert point.
2342 void EmitVarDecl(const VarDecl &D);
2344 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2345 bool capturedByInit);
2347 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
2348 llvm::Value *Address);
2350 /// \brief Determine whether the given initializer is trivial in the sense
2351 /// that it requires no code to be generated.
2352 bool isTrivialInitializer(const Expr *Init);
2354 /// EmitAutoVarDecl - Emit an auto variable declaration.
2356 /// This function can be called with a null (unreachable) insert point.
2357 void EmitAutoVarDecl(const VarDecl &D);
2359 class AutoVarEmission {
2360 friend class CodeGenFunction;
2362 const VarDecl *Variable;
2364 /// The address of the alloca. Invalid if the variable was emitted
2365 /// as a global constant.
2368 llvm::Value *NRVOFlag;
2370 /// True if the variable is a __block variable.
2373 /// True if the variable is of aggregate type and has a constant
2375 bool IsConstantAggregate;
2377 /// Non-null if we should use lifetime annotations.
2378 llvm::Value *SizeForLifetimeMarkers;
2381 AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {}
2383 AutoVarEmission(const VarDecl &variable)
2384 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
2385 IsByRef(false), IsConstantAggregate(false),
2386 SizeForLifetimeMarkers(nullptr) {}
2388 bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
2391 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
2393 bool useLifetimeMarkers() const {
2394 return SizeForLifetimeMarkers != nullptr;
2396 llvm::Value *getSizeForLifetimeMarkers() const {
2397 assert(useLifetimeMarkers());
2398 return SizeForLifetimeMarkers;
2401 /// Returns the raw, allocated address, which is not necessarily
2402 /// the address of the object itself.
2403 Address getAllocatedAddress() const {
2407 /// Returns the address of the object within this declaration.
2408 /// Note that this does not chase the forwarding pointer for
2410 Address getObjectAddress(CodeGenFunction &CGF) const {
2411 if (!IsByRef) return Addr;
2413 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
2416 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
2417 void EmitAutoVarInit(const AutoVarEmission &emission);
2418 void EmitAutoVarCleanups(const AutoVarEmission &emission);
2419 void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
2420 QualType::DestructionKind dtorKind);
2422 void EmitStaticVarDecl(const VarDecl &D,
2423 llvm::GlobalValue::LinkageTypes Linkage);
2428 ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
2430 static ParamValue forDirect(llvm::Value *value) {
2431 return ParamValue(value, 0);
2433 static ParamValue forIndirect(Address addr) {
2434 assert(!addr.getAlignment().isZero());
2435 return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
2438 bool isIndirect() const { return Alignment != 0; }
2439 llvm::Value *getAnyValue() const { return Value; }
2441 llvm::Value *getDirectValue() const {
2442 assert(!isIndirect());
2446 Address getIndirectAddress() const {
2447 assert(isIndirect());
2448 return Address(Value, CharUnits::fromQuantity(Alignment));
2452 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
2453 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
2455 /// protectFromPeepholes - Protect a value that we're intending to
2456 /// store to the side, but which will probably be used later, from
2457 /// aggressive peepholing optimizations that might delete it.
2459 /// Pass the result to unprotectFromPeepholes to declare that
2460 /// protection is no longer required.
2462 /// There's no particular reason why this shouldn't apply to
2463 /// l-values, it's just that no existing peepholes work on pointers.
2464 PeepholeProtection protectFromPeepholes(RValue rvalue);
2465 void unprotectFromPeepholes(PeepholeProtection protection);
2467 void EmitAlignmentAssumption(llvm::Value *PtrValue, llvm::Value *Alignment,
2468 llvm::Value *OffsetValue = nullptr) {
2469 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2473 //===--------------------------------------------------------------------===//
2474 // Statement Emission
2475 //===--------------------------------------------------------------------===//
2477 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
2478 void EmitStopPoint(const Stmt *S);
2480 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
2481 /// this function even if there is no current insertion point.
2483 /// This function may clear the current insertion point; callers should use
2484 /// EnsureInsertPoint if they wish to subsequently generate code without first
2485 /// calling EmitBlock, EmitBranch, or EmitStmt.
2486 void EmitStmt(const Stmt *S);
2488 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
2489 /// necessarily require an insertion point or debug information; typically
2490 /// because the statement amounts to a jump or a container of other
2493 /// \return True if the statement was handled.
2494 bool EmitSimpleStmt(const Stmt *S);
2496 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
2497 AggValueSlot AVS = AggValueSlot::ignored());
2498 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
2499 bool GetLast = false,
2501 AggValueSlot::ignored());
2503 /// EmitLabel - Emit the block for the given label. It is legal to call this
2504 /// function even if there is no current insertion point.
2505 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
2507 void EmitLabelStmt(const LabelStmt &S);
2508 void EmitAttributedStmt(const AttributedStmt &S);
2509 void EmitGotoStmt(const GotoStmt &S);
2510 void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
2511 void EmitIfStmt(const IfStmt &S);
2513 void EmitWhileStmt(const WhileStmt &S,
2514 ArrayRef<const Attr *> Attrs = None);
2515 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
2516 void EmitForStmt(const ForStmt &S,
2517 ArrayRef<const Attr *> Attrs = None);
2518 void EmitReturnStmt(const ReturnStmt &S);
2519 void EmitDeclStmt(const DeclStmt &S);
2520 void EmitBreakStmt(const BreakStmt &S);
2521 void EmitContinueStmt(const ContinueStmt &S);
2522 void EmitSwitchStmt(const SwitchStmt &S);
2523 void EmitDefaultStmt(const DefaultStmt &S);
2524 void EmitCaseStmt(const CaseStmt &S);
2525 void EmitCaseStmtRange(const CaseStmt &S);
2526 void EmitAsmStmt(const AsmStmt &S);
2528 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
2529 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
2530 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
2531 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
2532 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
2534 void EmitCoroutineBody(const CoroutineBodyStmt &S);
2535 void EmitCoreturnStmt(const CoreturnStmt &S);
2536 RValue EmitCoawaitExpr(const CoawaitExpr &E,
2537 AggValueSlot aggSlot = AggValueSlot::ignored(),
2538 bool ignoreResult = false);
2539 RValue EmitCoyieldExpr(const CoyieldExpr &E,
2540 AggValueSlot aggSlot = AggValueSlot::ignored(),
2541 bool ignoreResult = false);
2542 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
2544 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2545 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2547 void EmitCXXTryStmt(const CXXTryStmt &S);
2548 void EmitSEHTryStmt(const SEHTryStmt &S);
2549 void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
2550 void EnterSEHTryStmt(const SEHTryStmt &S);
2551 void ExitSEHTryStmt(const SEHTryStmt &S);
2553 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
2554 const Stmt *OutlinedStmt);
2556 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2557 const SEHExceptStmt &Except);
2559 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2560 const SEHFinallyStmt &Finally);
2562 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
2563 llvm::Value *ParentFP,
2564 llvm::Value *EntryEBP);
2565 llvm::Value *EmitSEHExceptionCode();
2566 llvm::Value *EmitSEHExceptionInfo();
2567 llvm::Value *EmitSEHAbnormalTermination();
2569 /// Scan the outlined statement for captures from the parent function. For
2570 /// each capture, mark the capture as escaped and emit a call to
2571 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
2572 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
2575 /// Recovers the address of a local in a parent function. ParentVar is the
2576 /// address of the variable used in the immediate parent function. It can
2577 /// either be an alloca or a call to llvm.localrecover if there are nested
2578 /// outlined functions. ParentFP is the frame pointer of the outermost parent
2580 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
2582 llvm::Value *ParentFP);
2584 void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
2585 ArrayRef<const Attr *> Attrs = None);
2587 /// Returns calculated size of the specified type.
2588 llvm::Value *getTypeSize(QualType Ty);
2589 LValue InitCapturedStruct(const CapturedStmt &S);
2590 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
2591 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
2592 Address GenerateCapturedStmtArgument(const CapturedStmt &S);
2593 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
2594 void GenerateOpenMPCapturedVars(const CapturedStmt &S,
2595 SmallVectorImpl<llvm::Value *> &CapturedVars);
2596 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
2597 SourceLocation Loc);
2598 /// \brief Perform element by element copying of arrays with type \a
2599 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
2600 /// generated by \a CopyGen.
2602 /// \param DestAddr Address of the destination array.
2603 /// \param SrcAddr Address of the source array.
2604 /// \param OriginalType Type of destination and source arrays.
2605 /// \param CopyGen Copying procedure that copies value of single array element
2606 /// to another single array element.
2607 void EmitOMPAggregateAssign(
2608 Address DestAddr, Address SrcAddr, QualType OriginalType,
2609 const llvm::function_ref<void(Address, Address)> &CopyGen);
2610 /// \brief Emit proper copying of data from one variable to another.
2612 /// \param OriginalType Original type of the copied variables.
2613 /// \param DestAddr Destination address.
2614 /// \param SrcAddr Source address.
2615 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
2616 /// type of the base array element).
2617 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
2618 /// the base array element).
2619 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
2621 void EmitOMPCopy(QualType OriginalType,
2622 Address DestAddr, Address SrcAddr,
2623 const VarDecl *DestVD, const VarDecl *SrcVD,
2625 /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
2626 /// \a X = \a E \a BO \a E.
2628 /// \param X Value to be updated.
2629 /// \param E Update value.
2630 /// \param BO Binary operation for update operation.
2631 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
2632 /// expression, false otherwise.
2633 /// \param AO Atomic ordering of the generated atomic instructions.
2634 /// \param CommonGen Code generator for complex expressions that cannot be
2635 /// expressed through atomicrmw instruction.
2636 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
2637 /// generated, <false, RValue::get(nullptr)> otherwise.
2638 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
2639 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2640 llvm::AtomicOrdering AO, SourceLocation Loc,
2641 const llvm::function_ref<RValue(RValue)> &CommonGen);
2642 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
2643 OMPPrivateScope &PrivateScope);
2644 void EmitOMPPrivateClause(const OMPExecutableDirective &D,
2645 OMPPrivateScope &PrivateScope);
2646 void EmitOMPUseDevicePtrClause(
2647 const OMPClause &C, OMPPrivateScope &PrivateScope,
2648 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
2649 /// \brief Emit code for copyin clause in \a D directive. The next code is
2650 /// generated at the start of outlined functions for directives:
2652 /// threadprivate_var1 = master_threadprivate_var1;
2653 /// operator=(threadprivate_var2, master_threadprivate_var2);
2655 /// __kmpc_barrier(&loc, global_tid);
2658 /// \param D OpenMP directive possibly with 'copyin' clause(s).
2659 /// \returns true if at least one copyin variable is found, false otherwise.
2660 bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
2661 /// \brief Emit initial code for lastprivate variables. If some variable is
2662 /// not also firstprivate, then the default initialization is used. Otherwise
2663 /// initialization of this variable is performed by EmitOMPFirstprivateClause
2666 /// \param D Directive that may have 'lastprivate' directives.
2667 /// \param PrivateScope Private scope for capturing lastprivate variables for
2668 /// proper codegen in internal captured statement.
2670 /// \returns true if there is at least one lastprivate variable, false
2672 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
2673 OMPPrivateScope &PrivateScope);
2674 /// \brief Emit final copying of lastprivate values to original variables at
2675 /// the end of the worksharing or simd directive.
2677 /// \param D Directive that has at least one 'lastprivate' directives.
2678 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
2679 /// it is the last iteration of the loop code in associated directive, or to
2680 /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
2681 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
2683 llvm::Value *IsLastIterCond = nullptr);
2684 /// Emit initial code for linear clauses.
2685 void EmitOMPLinearClause(const OMPLoopDirective &D,
2686 CodeGenFunction::OMPPrivateScope &PrivateScope);
2687 /// Emit final code for linear clauses.
2688 /// \param CondGen Optional conditional code for final part of codegen for
2690 void EmitOMPLinearClauseFinal(
2691 const OMPLoopDirective &D,
2692 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2693 /// \brief Emit initial code for reduction variables. Creates reduction copies
2694 /// and initializes them with the values according to OpenMP standard.
2696 /// \param D Directive (possibly) with the 'reduction' clause.
2697 /// \param PrivateScope Private scope for capturing reduction variables for
2698 /// proper codegen in internal captured statement.
2700 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
2701 OMPPrivateScope &PrivateScope);
2702 /// \brief Emit final update of reduction values to original variables at
2703 /// the end of the directive.
2705 /// \param D Directive that has at least one 'reduction' directives.
2706 /// \param ReductionKind The kind of reduction to perform.
2707 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
2708 const OpenMPDirectiveKind ReductionKind);
2709 /// \brief Emit initial code for linear variables. Creates private copies
2710 /// and initializes them with the values according to OpenMP standard.
2712 /// \param D Directive (possibly) with the 'linear' clause.
2713 void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
2715 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
2716 llvm::Value * /*OutlinedFn*/,
2717 const OMPTaskDataTy & /*Data*/)>
2719 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2720 const RegionCodeGenTy &BodyGen,
2721 const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
2723 void EmitOMPParallelDirective(const OMPParallelDirective &S);
2724 void EmitOMPSimdDirective(const OMPSimdDirective &S);
2725 void EmitOMPForDirective(const OMPForDirective &S);
2726 void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
2727 void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
2728 void EmitOMPSectionDirective(const OMPSectionDirective &S);
2729 void EmitOMPSingleDirective(const OMPSingleDirective &S);
2730 void EmitOMPMasterDirective(const OMPMasterDirective &S);
2731 void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
2732 void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
2733 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
2734 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
2735 void EmitOMPTaskDirective(const OMPTaskDirective &S);
2736 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
2737 void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
2738 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
2739 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
2740 void EmitOMPFlushDirective(const OMPFlushDirective &S);
2741 void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
2742 void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
2743 void EmitOMPTargetDirective(const OMPTargetDirective &S);
2744 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
2745 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
2746 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
2747 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
2748 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
2750 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
2751 void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
2753 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
2754 void EmitOMPCancelDirective(const OMPCancelDirective &S);
2755 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
2756 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
2757 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
2758 void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
2759 void EmitOMPDistributeLoop(const OMPDistributeDirective &S);
2760 void EmitOMPDistributeParallelForDirective(
2761 const OMPDistributeParallelForDirective &S);
2762 void EmitOMPDistributeParallelForSimdDirective(
2763 const OMPDistributeParallelForSimdDirective &S);
2764 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
2765 void EmitOMPTargetParallelForSimdDirective(
2766 const OMPTargetParallelForSimdDirective &S);
2767 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
2768 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
2770 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
2771 void EmitOMPTeamsDistributeParallelForSimdDirective(
2772 const OMPTeamsDistributeParallelForSimdDirective &S);
2773 void EmitOMPTeamsDistributeParallelForDirective(
2774 const OMPTeamsDistributeParallelForDirective &S);
2775 void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
2776 void EmitOMPTargetTeamsDistributeDirective(
2777 const OMPTargetTeamsDistributeDirective &S);
2778 void EmitOMPTargetTeamsDistributeParallelForDirective(
2779 const OMPTargetTeamsDistributeParallelForDirective &S);
2780 void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2781 const OMPTargetTeamsDistributeParallelForSimdDirective &S);
2782 void EmitOMPTargetTeamsDistributeSimdDirective(
2783 const OMPTargetTeamsDistributeSimdDirective &S);
2785 /// Emit device code for the target directive.
2786 static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
2787 StringRef ParentName,
2788 const OMPTargetDirective &S);
2790 EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
2791 const OMPTargetParallelDirective &S);
2793 EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
2794 const OMPTargetTeamsDirective &S);
2795 /// \brief Emit inner loop of the worksharing/simd construct.
2797 /// \param S Directive, for which the inner loop must be emitted.
2798 /// \param RequiresCleanup true, if directive has some associated private
2800 /// \param LoopCond Bollean condition for loop continuation.
2801 /// \param IncExpr Increment expression for loop control variable.
2802 /// \param BodyGen Generator for the inner body of the inner loop.
2803 /// \param PostIncGen Genrator for post-increment code (required for ordered
2804 /// loop directvies).
2805 void EmitOMPInnerLoop(
2806 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
2807 const Expr *IncExpr,
2808 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
2809 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
2811 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
2812 /// Emit initial code for loop counters of loop-based directives.
2813 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
2814 OMPPrivateScope &LoopScope);
2817 /// Helpers for blocks
2818 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
2820 /// Helpers for the OpenMP loop directives.
2821 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
2822 void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
2823 void EmitOMPSimdFinal(
2824 const OMPLoopDirective &D,
2825 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2826 /// \brief Emit code for the worksharing loop-based directive.
2827 /// \return true, if this construct has any lastprivate clause, false -
2829 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S);
2830 void EmitOMPOuterLoop(bool IsMonotonic, bool DynamicOrOrdered,
2831 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
2832 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk);
2833 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
2834 bool IsMonotonic, const OMPLoopDirective &S,
2835 OMPPrivateScope &LoopScope, bool Ordered, Address LB,
2836 Address UB, Address ST, Address IL,
2837 llvm::Value *Chunk);
2838 void EmitOMPDistributeOuterLoop(
2839 OpenMPDistScheduleClauseKind ScheduleKind,
2840 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
2841 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk);
2842 /// \brief Emit code for sections directive.
2843 void EmitSections(const OMPExecutableDirective &S);
2847 //===--------------------------------------------------------------------===//
2848 // LValue Expression Emission
2849 //===--------------------------------------------------------------------===//
2851 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
2852 RValue GetUndefRValue(QualType Ty);
2854 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
2855 /// and issue an ErrorUnsupported style diagnostic (using the
2857 RValue EmitUnsupportedRValue(const Expr *E,
2860 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
2861 /// an ErrorUnsupported style diagnostic (using the provided Name).
2862 LValue EmitUnsupportedLValue(const Expr *E,
2865 /// EmitLValue - Emit code to compute a designator that specifies the location
2866 /// of the expression.
2868 /// This can return one of two things: a simple address or a bitfield
2869 /// reference. In either case, the LLVM Value* in the LValue structure is
2870 /// guaranteed to be an LLVM pointer type.
2872 /// If this returns a bitfield reference, nothing about the pointee type of
2873 /// the LLVM value is known: For example, it may not be a pointer to an
2876 /// If this returns a normal address, and if the lvalue's C type is fixed
2877 /// size, this method guarantees that the returned pointer type will point to
2878 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
2879 /// variable length type, this is not possible.
2881 LValue EmitLValue(const Expr *E);
2883 /// \brief Same as EmitLValue but additionally we generate checking code to
2884 /// guard against undefined behavior. This is only suitable when we know
2885 /// that the address will be used to access the object.
2886 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
2888 RValue convertTempToRValue(Address addr, QualType type,
2889 SourceLocation Loc);
2891 void EmitAtomicInit(Expr *E, LValue lvalue);
2893 bool LValueIsSuitableForInlineAtomic(LValue Src);
2895 RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
2896 AggValueSlot Slot = AggValueSlot::ignored());
2898 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
2899 llvm::AtomicOrdering AO, bool IsVolatile = false,
2900 AggValueSlot slot = AggValueSlot::ignored());
2902 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
2904 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
2905 bool IsVolatile, bool isInit);
2907 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
2908 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2909 llvm::AtomicOrdering Success =
2910 llvm::AtomicOrdering::SequentiallyConsistent,
2911 llvm::AtomicOrdering Failure =
2912 llvm::AtomicOrdering::SequentiallyConsistent,
2913 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
2915 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
2916 const llvm::function_ref<RValue(RValue)> &UpdateOp,
2919 /// EmitToMemory - Change a scalar value from its value
2920 /// representation to its in-memory representation.
2921 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
2923 /// EmitFromMemory - Change a scalar value from its memory
2924 /// representation to its value representation.
2925 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
2927 /// Check if the scalar \p Value is within the valid range for the given
2930 /// Returns true if a check is needed (even if the range is unknown).
2931 bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
2932 SourceLocation Loc);
2934 /// EmitLoadOfScalar - Load a scalar value from an address, taking
2935 /// care to appropriately convert from the memory representation to
2936 /// the LLVM value representation.
2937 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
2939 AlignmentSource AlignSource =
2940 AlignmentSource::Type,
2941 llvm::MDNode *TBAAInfo = nullptr,
2942 QualType TBAABaseTy = QualType(),
2943 uint64_t TBAAOffset = 0,
2944 bool isNontemporal = false);
2946 /// EmitLoadOfScalar - Load a scalar value from an address, taking
2947 /// care to appropriately convert from the memory representation to
2948 /// the LLVM value representation. The l-value must be a simple
2950 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
2952 /// EmitStoreOfScalar - Store a scalar value to an address, taking
2953 /// care to appropriately convert from the memory representation to
2954 /// the LLVM value representation.
2955 void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
2956 bool Volatile, QualType Ty,
2957 AlignmentSource AlignSource = AlignmentSource::Type,
2958 llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
2959 QualType TBAABaseTy = QualType(),
2960 uint64_t TBAAOffset = 0, bool isNontemporal = false);
2962 /// EmitStoreOfScalar - Store a scalar value to an address, taking
2963 /// care to appropriately convert from the memory representation to
2964 /// the LLVM value representation. The l-value must be a simple
2965 /// l-value. The isInit flag indicates whether this is an initialization.
2966 /// If so, atomic qualifiers are ignored and the store is always non-atomic.
2967 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
2969 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
2970 /// this method emits the address of the lvalue, then loads the result as an
2971 /// rvalue, returning the rvalue.
2972 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
2973 RValue EmitLoadOfExtVectorElementLValue(LValue V);
2974 RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc);
2975 RValue EmitLoadOfGlobalRegLValue(LValue LV);
2977 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
2978 /// lvalue, where both are guaranteed to the have the same type, and that type
2980 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
2981 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
2982 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
2984 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
2985 /// as EmitStoreThroughLValue.
2987 /// \param Result [out] - If non-null, this will be set to a Value* for the
2988 /// bit-field contents after the store, appropriate for use as the result of
2989 /// an assignment to the bit-field.
2990 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
2991 llvm::Value **Result=nullptr);
2993 /// Emit an l-value for an assignment (simple or compound) of complex type.
2994 LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
2995 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
2996 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
2997 llvm::Value *&Result);
2999 // Note: only available for agg return types
3000 LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
3001 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
3002 // Note: only available for agg return types
3003 LValue EmitCallExprLValue(const CallExpr *E);
3004 // Note: only available for agg return types
3005 LValue EmitVAArgExprLValue(const VAArgExpr *E);
3006 LValue EmitDeclRefLValue(const DeclRefExpr *E);
3007 LValue EmitStringLiteralLValue(const StringLiteral *E);
3008 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
3009 LValue EmitPredefinedLValue(const PredefinedExpr *E);
3010 LValue EmitUnaryOpLValue(const UnaryOperator *E);
3011 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3012 bool Accessed = false);
3013 LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3014 bool IsLowerBound = true);
3015 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
3016 LValue EmitMemberExpr(const MemberExpr *E);
3017 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
3018 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
3019 LValue EmitInitListLValue(const InitListExpr *E);
3020 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
3021 LValue EmitCastLValue(const CastExpr *E);
3022 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
3023 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
3025 Address EmitExtVectorElementLValue(LValue V);
3027 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
3029 Address EmitArrayToPointerDecay(const Expr *Array,
3030 AlignmentSource *AlignSource = nullptr);
3032 class ConstantEmission {
3033 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
3034 ConstantEmission(llvm::Constant *C, bool isReference)
3035 : ValueAndIsReference(C, isReference) {}
3037 ConstantEmission() {}
3038 static ConstantEmission forReference(llvm::Constant *C) {
3039 return ConstantEmission(C, true);
3041 static ConstantEmission forValue(llvm::Constant *C) {
3042 return ConstantEmission(C, false);
3045 explicit operator bool() const {
3046 return ValueAndIsReference.getOpaqueValue() != nullptr;
3049 bool isReference() const { return ValueAndIsReference.getInt(); }
3050 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
3051 assert(isReference());
3052 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
3053 refExpr->getType());
3056 llvm::Constant *getValue() const {
3057 assert(!isReference());
3058 return ValueAndIsReference.getPointer();
3062 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
3064 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
3065 AggValueSlot slot = AggValueSlot::ignored());
3066 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
3068 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
3069 const ObjCIvarDecl *Ivar);
3070 LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
3071 LValue EmitLValueForLambdaField(const FieldDecl *Field);
3073 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
3074 /// if the Field is a reference, this will return the address of the reference
3075 /// and not the address of the value stored in the reference.
3076 LValue EmitLValueForFieldInitialization(LValue Base,
3077 const FieldDecl* Field);
3079 LValue EmitLValueForIvar(QualType ObjectTy,
3080 llvm::Value* Base, const ObjCIvarDecl *Ivar,
3081 unsigned CVRQualifiers);
3083 LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
3084 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
3085 LValue EmitLambdaLValue(const LambdaExpr *E);
3086 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
3087 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
3089 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
3090 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
3091 LValue EmitStmtExprLValue(const StmtExpr *E);
3092 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
3093 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
3094 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
3096 //===--------------------------------------------------------------------===//
3097 // Scalar Expression Emission
3098 //===--------------------------------------------------------------------===//
3100 /// EmitCall - Generate a call of the given function, expecting the given
3101 /// result type, and using the given argument list which specifies both the
3102 /// LLVM arguments and the types they were derived from.
3103 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
3104 ReturnValueSlot ReturnValue, const CallArgList &Args,
3105 llvm::Instruction **callOrInvoke = nullptr);
3107 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
3108 ReturnValueSlot ReturnValue,
3109 llvm::Value *Chain = nullptr);
3110 RValue EmitCallExpr(const CallExpr *E,
3111 ReturnValueSlot ReturnValue = ReturnValueSlot());
3112 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3113 CGCallee EmitCallee(const Expr *E);
3115 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
3117 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3118 const Twine &name = "");
3119 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3120 ArrayRef<llvm::Value*> args,
3121 const Twine &name = "");
3122 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3123 const Twine &name = "");
3124 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3125 ArrayRef<llvm::Value*> args,
3126 const Twine &name = "");
3128 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
3129 ArrayRef<llvm::Value *> Args,
3130 const Twine &Name = "");
3131 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3132 ArrayRef<llvm::Value*> args,
3133 const Twine &name = "");
3134 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3135 const Twine &name = "");
3136 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3137 ArrayRef<llvm::Value*> args);
3139 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
3140 NestedNameSpecifier *Qual,
3143 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
3145 const CXXRecordDecl *RD);
3148 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
3149 const CGCallee &Callee,
3150 ReturnValueSlot ReturnValue, llvm::Value *This,
3151 llvm::Value *ImplicitParam,
3152 QualType ImplicitParamTy, const CallExpr *E,
3153 CallArgList *RtlArgs);
3154 RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD,
3155 const CGCallee &Callee,
3156 llvm::Value *This, llvm::Value *ImplicitParam,
3157 QualType ImplicitParamTy, const CallExpr *E,
3159 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
3160 ReturnValueSlot ReturnValue);
3161 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
3162 const CXXMethodDecl *MD,
3163 ReturnValueSlot ReturnValue,
3165 NestedNameSpecifier *Qualifier,
3166 bool IsArrow, const Expr *Base);
3167 // Compute the object pointer.
3168 Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
3169 llvm::Value *memberPtr,
3170 const MemberPointerType *memberPtrType,
3171 AlignmentSource *AlignSource = nullptr);
3172 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
3173 ReturnValueSlot ReturnValue);
3175 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
3176 const CXXMethodDecl *MD,
3177 ReturnValueSlot ReturnValue);
3178 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
3180 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
3181 ReturnValueSlot ReturnValue);
3183 RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E,
3184 ReturnValueSlot ReturnValue);
3186 RValue EmitBuiltinExpr(const FunctionDecl *FD,
3187 unsigned BuiltinID, const CallExpr *E,
3188 ReturnValueSlot ReturnValue);
3190 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3192 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
3193 /// is unhandled by the current target.
3194 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3196 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
3197 const llvm::CmpInst::Predicate Fp,
3198 const llvm::CmpInst::Predicate Ip,
3199 const llvm::Twine &Name = "");
3200 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3202 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
3203 unsigned LLVMIntrinsic,
3204 unsigned AltLLVMIntrinsic,
3205 const char *NameHint,
3208 SmallVectorImpl<llvm::Value *> &Ops,
3209 Address PtrOp0, Address PtrOp1);
3210 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
3211 unsigned Modifier, llvm::Type *ArgTy,
3213 llvm::Value *EmitNeonCall(llvm::Function *F,
3214 SmallVectorImpl<llvm::Value*> &O,
3216 unsigned shift = 0, bool rightshift = false);
3217 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
3218 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
3219 bool negateForRightShift);
3220 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
3221 llvm::Type *Ty, bool usgn, const char *name);
3222 llvm::Value *vectorWrapScalar16(llvm::Value *Op);
3223 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3225 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
3226 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3227 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3228 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3229 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3230 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3231 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
3235 enum class MSVCIntrin;
3238 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
3240 llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args);
3242 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
3243 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
3244 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
3245 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
3246 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
3247 llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
3248 const ObjCMethodDecl *MethodWithObjects);
3249 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
3250 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
3251 ReturnValueSlot Return = ReturnValueSlot());
3253 /// Retrieves the default cleanup kind for an ARC cleanup.
3254 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
3255 CleanupKind getARCCleanupKind() {
3256 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
3257 ? NormalAndEHCleanup : NormalCleanup;
3261 void EmitARCInitWeak(Address addr, llvm::Value *value);
3262 void EmitARCDestroyWeak(Address addr);
3263 llvm::Value *EmitARCLoadWeak(Address addr);
3264 llvm::Value *EmitARCLoadWeakRetained(Address addr);
3265 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
3266 void EmitARCCopyWeak(Address dst, Address src);
3267 void EmitARCMoveWeak(Address dst, Address src);
3268 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
3269 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
3270 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
3271 bool resultIgnored);
3272 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
3273 bool resultIgnored);
3274 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
3275 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
3276 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
3277 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
3278 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
3279 llvm::Value *EmitARCAutorelease(llvm::Value *value);
3280 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
3281 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
3282 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
3283 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
3285 std::pair<LValue,llvm::Value*>
3286 EmitARCStoreAutoreleasing(const BinaryOperator *e);
3287 std::pair<LValue,llvm::Value*>
3288 EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
3289 std::pair<LValue,llvm::Value*>
3290 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
3292 llvm::Value *EmitObjCThrowOperand(const Expr *expr);
3293 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
3294 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
3296 llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
3297 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
3298 bool allowUnsafeClaim);
3299 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
3300 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
3301 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
3303 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
3305 static Destroyer destroyARCStrongImprecise;
3306 static Destroyer destroyARCStrongPrecise;
3307 static Destroyer destroyARCWeak;
3309 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
3310 llvm::Value *EmitObjCAutoreleasePoolPush();
3311 llvm::Value *EmitObjCMRRAutoreleasePoolPush();
3312 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
3313 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
3315 /// \brief Emits a reference binding to the passed in expression.
3316 RValue EmitReferenceBindingToExpr(const Expr *E);
3318 //===--------------------------------------------------------------------===//
3319 // Expression Emission
3320 //===--------------------------------------------------------------------===//
3322 // Expressions are broken into three classes: scalar, complex, aggregate.
3324 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
3325 /// scalar type, returning the result.
3326 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
3328 /// Emit a conversion from the specified type to the specified destination
3329 /// type, both of which are LLVM scalar types.
3330 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
3331 QualType DstTy, SourceLocation Loc);
3333 /// Emit a conversion from the specified complex type to the specified
3334 /// destination type, where the destination type is an LLVM scalar type.
3335 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
3337 SourceLocation Loc);
3339 /// EmitAggExpr - Emit the computation of the specified expression
3340 /// of aggregate type. The result is computed into the given slot,
3341 /// which may be null to indicate that the value is not needed.
3342 void EmitAggExpr(const Expr *E, AggValueSlot AS);
3344 /// EmitAggExprToLValue - Emit the computation of the specified expression of
3345 /// aggregate type into a temporary LValue.
3346 LValue EmitAggExprToLValue(const Expr *E);
3348 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3349 /// make sure it survives garbage collection until this point.
3350 void EmitExtendGCLifetime(llvm::Value *object);
3352 /// EmitComplexExpr - Emit the computation of the specified expression of
3353 /// complex type, returning the result.
3354 ComplexPairTy EmitComplexExpr(const Expr *E,
3355 bool IgnoreReal = false,
3356 bool IgnoreImag = false);
3358 /// EmitComplexExprIntoLValue - Emit the given expression of complex
3359 /// type and place its result into the specified l-value.
3360 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
3362 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
3363 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
3365 /// EmitLoadOfComplex - Load a complex number from the specified l-value.
3366 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
3368 Address emitAddrOfRealComponent(Address complex, QualType complexType);
3369 Address emitAddrOfImagComponent(Address complex, QualType complexType);
3371 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
3372 /// global variable that has already been created for it. If the initializer
3373 /// has a different type than GV does, this may free GV and return a different
3374 /// one. Otherwise it just returns GV.
3375 llvm::GlobalVariable *
3376 AddInitializerToStaticVarDecl(const VarDecl &D,
3377 llvm::GlobalVariable *GV);
3380 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
3381 /// variable with global storage.
3382 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
3385 llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
3386 llvm::Constant *Addr);
3388 /// Call atexit() with a function that passes the given argument to
3389 /// the given function.
3390 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
3391 llvm::Constant *addr);
3393 /// Emit code in this function to perform a guarded variable
3394 /// initialization. Guarded initializations are used when it's not
3395 /// possible to prove that an initialization will be done exactly
3396 /// once, e.g. with a static local variable or a static data member
3397 /// of a class template.
3398 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
3401 /// GenerateCXXGlobalInitFunc - Generates code for initializing global
3403 void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
3404 ArrayRef<llvm::Function *> CXXThreadLocals,
3405 Address Guard = Address::invalid());
3407 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
3409 void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
3410 const std::vector<std::pair<llvm::WeakVH,
3411 llvm::Constant*> > &DtorsAndObjects);
3413 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
3415 llvm::GlobalVariable *Addr,
3418 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
3420 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
3422 void enterFullExpression(const ExprWithCleanups *E) {
3423 if (E->getNumObjects() == 0) return;
3424 enterNonTrivialFullExpression(E);
3426 void enterNonTrivialFullExpression(const ExprWithCleanups *E);
3428 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
3430 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
3432 RValue EmitAtomicExpr(AtomicExpr *E);
3434 //===--------------------------------------------------------------------===//
3435 // Annotations Emission
3436 //===--------------------------------------------------------------------===//
3438 /// Emit an annotation call (intrinsic or builtin).
3439 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
3440 llvm::Value *AnnotatedVal,
3441 StringRef AnnotationStr,
3442 SourceLocation Location);
3444 /// Emit local annotations for the local variable V, declared by D.
3445 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
3447 /// Emit field annotations for the given field & value. Returns the
3448 /// annotation result.
3449 Address EmitFieldAnnotations(const FieldDecl *D, Address V);
3451 //===--------------------------------------------------------------------===//
3453 //===--------------------------------------------------------------------===//
3455 /// ContainsLabel - Return true if the statement contains a label in it. If
3456 /// this statement is not executed normally, it not containing a label means
3457 /// that we can just remove the code.
3458 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
3460 /// containsBreak - Return true if the statement contains a break out of it.
3461 /// If the statement (recursively) contains a switch or loop with a break
3462 /// inside of it, this is fine.
3463 static bool containsBreak(const Stmt *S);
3465 /// Determine if the given statement might introduce a declaration into the
3466 /// current scope, by being a (possibly-labelled) DeclStmt.
3467 static bool mightAddDeclToScope(const Stmt *S);
3469 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3470 /// to a constant, or if it does but contains a label, return false. If it
3471 /// constant folds return true and set the boolean result in Result.
3472 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
3473 bool AllowLabels = false);
3475 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3476 /// to a constant, or if it does but contains a label, return false. If it
3477 /// constant folds return true and set the folded value.
3478 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
3479 bool AllowLabels = false);
3481 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
3482 /// if statement) to the specified blocks. Based on the condition, this might
3483 /// try to simplify the codegen of the conditional based on the branch.
3484 /// TrueCount should be the number of times we expect the condition to
3485 /// evaluate to true based on PGO data.
3486 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
3487 llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
3489 /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is
3490 /// nonnull, if \p LHS is marked _Nonnull.
3491 void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc);
3493 /// \brief Emit a description of a type in a format suitable for passing to
3494 /// a runtime sanitizer handler.
3495 llvm::Constant *EmitCheckTypeDescriptor(QualType T);
3497 /// \brief Convert a value into a format suitable for passing to a runtime
3498 /// sanitizer handler.
3499 llvm::Value *EmitCheckValue(llvm::Value *V);
3501 /// \brief Emit a description of a source location in a format suitable for
3502 /// passing to a runtime sanitizer handler.
3503 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
3505 /// \brief Create a basic block that will call a handler function in a
3506 /// sanitizer runtime with the provided arguments, and create a conditional
3508 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3509 SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
3510 ArrayRef<llvm::Value *> DynamicArgs);
3512 /// \brief Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
3513 /// if Cond if false.
3514 void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
3515 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
3516 ArrayRef<llvm::Constant *> StaticArgs);
3518 /// \brief Create a basic block that will call the trap intrinsic, and emit a
3519 /// conditional branch to it, for the -ftrapv checks.
3520 void EmitTrapCheck(llvm::Value *Checked);
3522 /// \brief Emit a call to trap or debugtrap and attach function attribute
3523 /// "trap-func-name" if specified.
3524 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
3526 /// \brief Emit a stub for the cross-DSO CFI check function.
3527 void EmitCfiCheckStub();
3529 /// \brief Emit a cross-DSO CFI failure handling function.
3530 void EmitCfiCheckFail();
3532 /// \brief Create a check for a function parameter that may potentially be
3533 /// declared as non-null.
3534 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
3535 AbstractCallee AC, unsigned ParmNum);
3537 /// EmitCallArg - Emit a single call argument.
3538 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
3540 /// EmitDelegateCallArg - We are performing a delegate call; that
3541 /// is, the current function is delegating to another one. Produce
3542 /// a r-value suitable for passing the given parameter.
3543 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
3544 SourceLocation loc);
3546 /// SetFPAccuracy - Set the minimum required accuracy of the given floating
3547 /// point operation, expressed as the maximum relative error in ulp.
3548 void SetFPAccuracy(llvm::Value *Val, float Accuracy);
3551 llvm::MDNode *getRangeForLoadFromType(QualType Ty);
3552 void EmitReturnOfRValue(RValue RV, QualType Ty);
3554 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
3556 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
3557 DeferredReplacements;
3559 /// Set the address of a local variable.
3560 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
3561 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
3562 LocalDeclMap.insert({VD, Addr});
3565 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
3566 /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
3568 /// \param AI - The first function argument of the expansion.
3569 void ExpandTypeFromArgs(QualType Ty, LValue Dst,
3570 SmallVectorImpl<llvm::Value *>::iterator &AI);
3572 /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
3573 /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
3574 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
3575 void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
3576 SmallVectorImpl<llvm::Value *> &IRCallArgs,
3577 unsigned &IRCallArgPos);
3579 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
3580 const Expr *InputExpr, std::string &ConstraintStr);
3582 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
3583 LValue InputValue, QualType InputType,
3584 std::string &ConstraintStr,
3585 SourceLocation Loc);
3587 /// \brief Attempts to statically evaluate the object size of E. If that
3588 /// fails, emits code to figure the size of E out for us. This is
3589 /// pass_object_size aware.
3591 /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
3592 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
3593 llvm::IntegerType *ResType,
3594 llvm::Value *EmittedE);
3596 /// \brief Emits the size of E, as required by __builtin_object_size. This
3597 /// function is aware of pass_object_size parameters, and will act accordingly
3598 /// if E is a parameter with the pass_object_size attribute.
3599 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
3600 llvm::IntegerType *ResType,
3601 llvm::Value *EmittedE);
3605 // Determine whether the given argument is an Objective-C method
3606 // that may have type parameters in its signature.
3607 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
3608 const DeclContext *dc = method->getDeclContext();
3609 if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
3610 return classDecl->getTypeParamListAsWritten();
3613 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
3614 return catDecl->getTypeParamList();
3620 template<typename T>
3621 static bool isObjCMethodWithTypeParams(const T *) { return false; }
3624 enum class EvaluationOrder {
3625 ///! No language constraints on evaluation order.
3627 ///! Language semantics require left-to-right evaluation.
3629 ///! Language semantics require right-to-left evaluation.
3633 /// EmitCallArgs - Emit call arguments for a function.
3634 template <typename T>
3635 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
3636 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3637 AbstractCallee AC = AbstractCallee(),
3638 unsigned ParamsToSkip = 0,
3639 EvaluationOrder Order = EvaluationOrder::Default) {
3640 SmallVector<QualType, 16> ArgTypes;
3641 CallExpr::const_arg_iterator Arg = ArgRange.begin();
3643 assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
3644 "Can't skip parameters if type info is not provided");
3645 if (CallArgTypeInfo) {
3647 bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
3650 // First, use the argument types that the type info knows about
3651 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
3652 E = CallArgTypeInfo->param_type_end();
3653 I != E; ++I, ++Arg) {
3654 assert(Arg != ArgRange.end() && "Running over edge of argument list!");
3655 assert((isGenericMethod ||
3656 ((*I)->isVariablyModifiedType() ||
3657 (*I).getNonReferenceType()->isObjCRetainableType() ||
3659 .getCanonicalType((*I).getNonReferenceType())
3662 .getCanonicalType((*Arg)->getType())
3664 "type mismatch in call argument!");
3665 ArgTypes.push_back(*I);
3669 // Either we've emitted all the call args, or we have a call to variadic
3671 assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
3672 CallArgTypeInfo->isVariadic()) &&
3673 "Extra arguments in non-variadic function!");
3675 // If we still have any arguments, emit them using the type of the argument.
3676 for (auto *A : llvm::make_range(Arg, ArgRange.end()))
3677 ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType());
3679 EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order);
3682 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
3683 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3684 AbstractCallee AC = AbstractCallee(),
3685 unsigned ParamsToSkip = 0,
3686 EvaluationOrder Order = EvaluationOrder::Default);
3688 /// EmitPointerWithAlignment - Given an expression with a pointer
3689 /// type, emit the value and compute our best estimate of the
3690 /// alignment of the pointee.
3692 /// Note that this function will conservatively fall back on the type
3695 /// \param Source - If non-null, this will be initialized with
3696 /// information about the source of the alignment. Note that this
3697 /// function will conservatively fall back on the type when it
3698 /// doesn't recognize the expression, which means that sometimes
3700 /// a worst-case One
3701 /// reasonable way to use this information is when there's a
3702 /// language guarantee that the pointer must be aligned to some
3703 /// stricter value, and we're simply trying to ensure that
3704 /// sufficiently obvious uses of under-aligned objects don't get
3705 /// miscompiled; for example, a placement new into the address of
3706 /// a local variable. In such a case, it's quite reasonable to
3707 /// just ignore the returned alignment when it isn't from an
3708 /// explicit source.
3709 Address EmitPointerWithAlignment(const Expr *Addr,
3710 AlignmentSource *Source = nullptr);
3712 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
3715 QualType getVarArgType(const Expr *Arg);
3717 const TargetCodeGenInfo &getTargetHooks() const {
3718 return CGM.getTargetCodeGenInfo();
3721 void EmitDeclMetadata();
3723 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
3724 const AutoVarEmission &emission);
3726 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
3728 llvm::Value *GetValueForARMHint(unsigned BuiltinID);
3731 /// Helper class with most of the code for saving a value for a
3732 /// conditional expression cleanup.
3733 struct DominatingLLVMValue {
3734 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
3736 /// Answer whether the given value needs extra work to be saved.
3737 static bool needsSaving(llvm::Value *value) {
3738 // If it's not an instruction, we don't need to save.
3739 if (!isa<llvm::Instruction>(value)) return false;
3741 // If it's an instruction in the entry block, we don't need to save.
3742 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
3743 return (block != &block->getParent()->getEntryBlock());
3746 /// Try to save the given value.
3747 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
3748 if (!needsSaving(value)) return saved_type(value, false);
3750 // Otherwise, we need an alloca.
3751 auto align = CharUnits::fromQuantity(
3752 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
3754 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
3755 CGF.Builder.CreateStore(value, alloca);
3757 return saved_type(alloca.getPointer(), true);
3760 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
3761 // If the value says it wasn't saved, trust that it's still dominating.
3762 if (!value.getInt()) return value.getPointer();
3764 // Otherwise, it should be an alloca instruction, as set up in save().
3765 auto alloca = cast<llvm::AllocaInst>(value.getPointer());
3766 return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
3770 /// A partial specialization of DominatingValue for llvm::Values that
3771 /// might be llvm::Instructions.
3772 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
3774 static type restore(CodeGenFunction &CGF, saved_type value) {
3775 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
3779 /// A specialization of DominatingValue for Address.
3780 template <> struct DominatingValue<Address> {
3781 typedef Address type;
3784 DominatingLLVMValue::saved_type SavedValue;
3785 CharUnits Alignment;
3788 static bool needsSaving(type value) {
3789 return DominatingLLVMValue::needsSaving(value.getPointer());
3791 static saved_type save(CodeGenFunction &CGF, type value) {
3792 return { DominatingLLVMValue::save(CGF, value.getPointer()),
3793 value.getAlignment() };
3795 static type restore(CodeGenFunction &CGF, saved_type value) {
3796 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
3801 /// A specialization of DominatingValue for RValue.
3802 template <> struct DominatingValue<RValue> {
3803 typedef RValue type;
3805 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
3806 AggregateAddress, ComplexAddress };
3810 unsigned Align : 29;
3811 saved_type(llvm::Value *v, Kind k, unsigned a = 0)
3812 : Value(v), K(k), Align(a) {}
3815 static bool needsSaving(RValue value);
3816 static saved_type save(CodeGenFunction &CGF, RValue value);
3817 RValue restore(CodeGenFunction &CGF);
3819 // implementations in CGCleanup.cpp
3822 static bool needsSaving(type value) {
3823 return saved_type::needsSaving(value);
3825 static saved_type save(CodeGenFunction &CGF, type value) {
3826 return saved_type::save(CGF, value);
3828 static type restore(CodeGenFunction &CGF, saved_type value) {
3829 return value.restore(CGF);
3833 } // end namespace CodeGen
3834 } // end namespace clang