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 CLANG_CODEGEN_CODEGENFUNCTION_H
15 #define CLANG_CODEGEN_CODEGENFUNCTION_H
17 #include "clang/AST/Type.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Support/ValueHandle.h"
25 #include "CodeGenModule.h"
27 #include "CGBuilder.h"
46 class CXXDestructorDecl;
49 class EnumConstantDecl;
51 class FunctionProtoType;
53 class ObjCContainerDecl;
54 class ObjCInterfaceDecl;
57 class ObjCImplementationDecl;
58 class ObjCPropertyImplDecl;
60 class TargetCodeGenInfo;
62 class ObjCForCollectionStmt;
64 class ObjCAtThrowStmt;
65 class ObjCAtSynchronizedStmt;
75 /// A branch fixup. These are required when emitting a goto to a
76 /// label which hasn't been emitted yet. The goto is optimistically
77 /// emitted as a branch to the basic block for the label, and (if it
78 /// occurs in a scope with non-trivial cleanups) a fixup is added to
79 /// the innermost cleanup. When a (normal) cleanup is popped, any
80 /// unresolved fixups in that scope are threaded through the cleanup.
82 /// The block containing the terminator which needs to be modified
83 /// into a switch if this fixup is resolved into the current scope.
84 /// If null, LatestBranch points directly to the destination.
85 llvm::BasicBlock *OptimisticBranchBlock;
87 /// The ultimate destination of the branch.
89 /// This can be set to null to indicate that this fixup was
90 /// successfully resolved.
91 llvm::BasicBlock *Destination;
93 /// The destination index value.
94 unsigned DestinationIndex;
96 /// The initial branch of the fixup.
97 llvm::BranchInst *InitialBranch;
103 NormalAndEHCleanup = EHCleanup | NormalCleanup,
105 InactiveCleanup = 0x4,
106 InactiveEHCleanup = EHCleanup | InactiveCleanup,
107 InactiveNormalCleanup = NormalCleanup | InactiveCleanup,
108 InactiveNormalAndEHCleanup = NormalAndEHCleanup | InactiveCleanup
111 /// A stack of scopes which respond to exceptions, including cleanups
112 /// and catch blocks.
115 /// A saved depth on the scope stack. This is necessary because
116 /// pushing scopes onto the stack invalidates iterators.
117 class stable_iterator {
118 friend class EHScopeStack;
120 /// Offset from StartOfData to EndOfBuffer.
123 stable_iterator(ptrdiff_t Size) : Size(Size) {}
126 static stable_iterator invalid() { return stable_iterator(-1); }
127 stable_iterator() : Size(-1) {}
129 bool isValid() const { return Size >= 0; }
131 /// Returns true if this scope encloses I.
132 /// Returns false if I is invalid.
133 /// This scope must be valid.
134 bool encloses(stable_iterator I) const { return Size <= I.Size; }
136 /// Returns true if this scope strictly encloses I: that is,
137 /// if it encloses I and is not I.
138 /// Returns false is I is invalid.
139 /// This scope must be valid.
140 bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
142 friend bool operator==(stable_iterator A, stable_iterator B) {
143 return A.Size == B.Size;
145 friend bool operator!=(stable_iterator A, stable_iterator B) {
146 return A.Size != B.Size;
150 /// Information for lazily generating a cleanup. Subclasses must be
151 /// POD-like: cleanups will not be destructed, and they will be
152 /// allocated on the cleanup stack and freely copied and moved
155 /// Cleanup implementations should generally be declared in an
156 /// anonymous namespace.
159 // Anchor the construction vtable. We use the destructor because
160 // gcc gives an obnoxious warning if there are virtual methods
161 // with an accessible non-virtual destructor. Unfortunately,
162 // declaring this destructor makes it non-trivial, but there
163 // doesn't seem to be any other way around this warning.
165 // This destructor will never be called.
168 /// Emit the cleanup. For normal cleanups, this is run in the
169 /// same EH context as when the cleanup was pushed, i.e. the
170 /// immediately-enclosing context of the cleanup scope. For
171 /// EH cleanups, this is run in a terminate context.
173 // \param IsForEHCleanup true if this is for an EH cleanup, false
174 /// if for a normal cleanup.
175 virtual void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) = 0;
179 // The implementation for this class is in CGException.h and
180 // CGException.cpp; the definition is here because it's used as a
181 // member of CodeGenFunction.
183 /// The start of the scope-stack buffer, i.e. the allocated pointer
184 /// for the buffer. All of these pointers are either simultaneously
185 /// null or simultaneously valid.
188 /// The end of the buffer.
191 /// The first valid entry in the buffer.
194 /// The innermost normal cleanup on the stack.
195 stable_iterator InnermostNormalCleanup;
197 /// The innermost EH cleanup on the stack.
198 stable_iterator InnermostEHCleanup;
200 /// The number of catches on the stack.
203 /// The current EH destination index. Reset to FirstCatchIndex
204 /// whenever the last EH cleanup is popped.
205 unsigned NextEHDestIndex;
206 enum { FirstEHDestIndex = 1 };
208 /// The current set of branch fixups. A branch fixup is a jump to
209 /// an as-yet unemitted label, i.e. a label for which we don't yet
210 /// know the EH stack depth. Whenever we pop a cleanup, we have
211 /// to thread all the current branch fixups through it.
213 /// Fixups are recorded as the Use of the respective branch or
214 /// switch statement. The use points to the final destination.
215 /// When popping out of a cleanup, these uses are threaded through
216 /// the cleanup and adjusted to point to the new cleanup.
218 /// Note that branches are allowed to jump into protected scopes
219 /// in certain situations; e.g. the following code is legal:
220 /// struct A { ~A(); }; // trivial ctor, non-trivial dtor
225 llvm::SmallVector<BranchFixup, 8> BranchFixups;
227 char *allocate(size_t Size);
229 void *pushCleanup(CleanupKind K, size_t DataSize);
232 EHScopeStack() : StartOfBuffer(0), EndOfBuffer(0), StartOfData(0),
233 InnermostNormalCleanup(stable_end()),
234 InnermostEHCleanup(stable_end()),
235 CatchDepth(0), NextEHDestIndex(FirstEHDestIndex) {}
236 ~EHScopeStack() { delete[] StartOfBuffer; }
238 // Variadic templates would make this not terrible.
240 /// Push a lazily-created cleanup on the stack.
242 void pushCleanup(CleanupKind Kind) {
243 void *Buffer = pushCleanup(Kind, sizeof(T));
244 Cleanup *Obj = new(Buffer) T();
248 /// Push a lazily-created cleanup on the stack.
249 template <class T, class A0>
250 void pushCleanup(CleanupKind Kind, A0 a0) {
251 void *Buffer = pushCleanup(Kind, sizeof(T));
252 Cleanup *Obj = new(Buffer) T(a0);
256 /// Push a lazily-created cleanup on the stack.
257 template <class T, class A0, class A1>
258 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
259 void *Buffer = pushCleanup(Kind, sizeof(T));
260 Cleanup *Obj = new(Buffer) T(a0, a1);
264 /// Push a lazily-created cleanup on the stack.
265 template <class T, class A0, class A1, class A2>
266 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) {
267 void *Buffer = pushCleanup(Kind, sizeof(T));
268 Cleanup *Obj = new(Buffer) T(a0, a1, a2);
272 /// Push a lazily-created cleanup on the stack.
273 template <class T, class A0, class A1, class A2, class A3>
274 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
275 void *Buffer = pushCleanup(Kind, sizeof(T));
276 Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
280 /// Push a lazily-created cleanup on the stack.
281 template <class T, class A0, class A1, class A2, class A3, class A4>
282 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
283 void *Buffer = pushCleanup(Kind, sizeof(T));
284 Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
288 /// Pops a cleanup scope off the stack. This should only be called
289 /// by CodeGenFunction::PopCleanupBlock.
292 /// Push a set of catch handlers on the stack. The catch is
293 /// uninitialized and will need to have the given number of handlers
295 class EHCatchScope *pushCatch(unsigned NumHandlers);
297 /// Pops a catch scope off the stack.
300 /// Push an exceptions filter on the stack.
301 class EHFilterScope *pushFilter(unsigned NumFilters);
303 /// Pops an exceptions filter off the stack.
306 /// Push a terminate handler on the stack.
307 void pushTerminate();
309 /// Pops a terminate handler off the stack.
312 /// Determines whether the exception-scopes stack is empty.
313 bool empty() const { return StartOfData == EndOfBuffer; }
315 bool requiresLandingPad() const {
316 return (CatchDepth || hasEHCleanups());
319 /// Determines whether there are any normal cleanups on the stack.
320 bool hasNormalCleanups() const {
321 return InnermostNormalCleanup != stable_end();
324 /// Returns the innermost normal cleanup on the stack, or
325 /// stable_end() if there are no normal cleanups.
326 stable_iterator getInnermostNormalCleanup() const {
327 return InnermostNormalCleanup;
329 stable_iterator getInnermostActiveNormalCleanup() const; // CGException.h
331 /// Determines whether there are any EH cleanups on the stack.
332 bool hasEHCleanups() const {
333 return InnermostEHCleanup != stable_end();
336 /// Returns the innermost EH cleanup on the stack, or stable_end()
337 /// if there are no EH cleanups.
338 stable_iterator getInnermostEHCleanup() const {
339 return InnermostEHCleanup;
341 stable_iterator getInnermostActiveEHCleanup() const; // CGException.h
343 /// An unstable reference to a scope-stack depth. Invalidated by
344 /// pushes but not pops.
347 /// Returns an iterator pointing to the innermost EH scope.
348 iterator begin() const;
350 /// Returns an iterator pointing to the outermost EH scope.
351 iterator end() const;
353 /// Create a stable reference to the top of the EH stack. The
354 /// returned reference is valid until that scope is popped off the
356 stable_iterator stable_begin() const {
357 return stable_iterator(EndOfBuffer - StartOfData);
360 /// Create a stable reference to the bottom of the EH stack.
361 static stable_iterator stable_end() {
362 return stable_iterator(0);
365 /// Translates an iterator into a stable_iterator.
366 stable_iterator stabilize(iterator it) const;
368 /// Finds the nearest cleanup enclosing the given iterator.
369 /// Returns stable_iterator::invalid() if there are no such cleanups.
370 stable_iterator getEnclosingEHCleanup(iterator it) const;
372 /// Turn a stable reference to a scope depth into a unstable pointer
374 iterator find(stable_iterator save) const;
376 /// Removes the cleanup pointed to by the given stable_iterator.
377 void removeCleanup(stable_iterator save);
379 /// Add a branch fixup to the current cleanup scope.
380 BranchFixup &addBranchFixup() {
381 assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
382 BranchFixups.push_back(BranchFixup());
383 return BranchFixups.back();
386 unsigned getNumBranchFixups() const { return BranchFixups.size(); }
387 BranchFixup &getBranchFixup(unsigned I) {
388 assert(I < getNumBranchFixups());
389 return BranchFixups[I];
392 /// Pops lazily-removed fixups from the end of the list. This
393 /// should only be called by procedures which have just popped a
394 /// cleanup or resolved one or more fixups.
395 void popNullFixups();
397 /// Clears the branch-fixups list. This should only be called by
398 /// CodeGenFunction::ResolveAllBranchFixups.
399 void clearFixups() { BranchFixups.clear(); }
401 /// Gets the next EH destination index.
402 unsigned getNextEHDestIndex() { return NextEHDestIndex++; }
405 /// CodeGenFunction - This class organizes the per-function state that is used
406 /// while generating LLVM code.
407 class CodeGenFunction : public BlockFunction {
408 CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT
409 void operator=(const CodeGenFunction&); // DO NOT IMPLEMENT
411 friend class CGCXXABI;
413 /// A jump destination is an abstract label, branching to which may
414 /// require a jump out through normal cleanups.
416 JumpDest() : Block(0), ScopeDepth(), Index(0) {}
417 JumpDest(llvm::BasicBlock *Block,
418 EHScopeStack::stable_iterator Depth,
420 : Block(Block), ScopeDepth(Depth), Index(Index) {}
422 bool isValid() const { return Block != 0; }
423 llvm::BasicBlock *getBlock() const { return Block; }
424 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
425 unsigned getDestIndex() const { return Index; }
428 llvm::BasicBlock *Block;
429 EHScopeStack::stable_iterator ScopeDepth;
433 /// An unwind destination is an abstract label, branching to which
434 /// may require a jump out through EH cleanups.
436 UnwindDest() : Block(0), ScopeDepth(), Index(0) {}
437 UnwindDest(llvm::BasicBlock *Block,
438 EHScopeStack::stable_iterator Depth,
440 : Block(Block), ScopeDepth(Depth), Index(Index) {}
442 bool isValid() const { return Block != 0; }
443 llvm::BasicBlock *getBlock() const { return Block; }
444 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
445 unsigned getDestIndex() const { return Index; }
448 llvm::BasicBlock *Block;
449 EHScopeStack::stable_iterator ScopeDepth;
453 CodeGenModule &CGM; // Per-module state.
454 const TargetInfo &Target;
456 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
459 /// CurFuncDecl - Holds the Decl for the current function or ObjC method.
460 /// This excludes BlockDecls.
461 const Decl *CurFuncDecl;
462 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
463 const Decl *CurCodeDecl;
464 const CGFunctionInfo *CurFnInfo;
466 llvm::Function *CurFn;
468 /// CurGD - The GlobalDecl for the current function being compiled.
471 /// ReturnBlock - Unified return block.
472 JumpDest ReturnBlock;
474 /// ReturnValue - The temporary alloca to hold the return value. This is null
475 /// iff the function has no return value.
476 llvm::Value *ReturnValue;
478 /// RethrowBlock - Unified rethrow block.
479 UnwindDest RethrowBlock;
481 /// AllocaInsertPoint - This is an instruction in the entry block before which
482 /// we prefer to insert allocas.
483 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
485 // intptr_t, i32, i64
486 const llvm::IntegerType *IntPtrTy, *Int32Ty, *Int64Ty;
487 uint32_t LLVMPointerWidth;
492 /// \brief A mapping from NRVO variables to the flags used to indicate
493 /// when the NRVO has been applied to this variable.
494 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
496 EHScopeStack EHStack;
498 /// i32s containing the indexes of the cleanup destinations.
499 llvm::AllocaInst *NormalCleanupDest;
500 llvm::AllocaInst *EHCleanupDest;
502 unsigned NextCleanupDestIndex;
504 /// The exception slot. All landing pads write the current
505 /// exception pointer into this alloca.
506 llvm::Value *ExceptionSlot;
508 /// Emits a landing pad for the current EH stack.
509 llvm::BasicBlock *EmitLandingPad();
511 llvm::BasicBlock *getInvokeDestImpl();
514 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
516 llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack;
518 // A struct holding information about a finally block's IR
519 // generation. For now, doesn't actually hold anything.
523 FinallyInfo EnterFinallyBlock(const Stmt *Stmt,
524 llvm::Constant *BeginCatchFn,
525 llvm::Constant *EndCatchFn,
526 llvm::Constant *RethrowFn);
527 void ExitFinallyBlock(FinallyInfo &FinallyInfo);
529 /// PushDestructorCleanup - Push a cleanup to call the
530 /// complete-object destructor of an object of the given type at the
531 /// given address. Does nothing if T is not a C++ class type with a
532 /// non-trivial destructor.
533 void PushDestructorCleanup(QualType T, llvm::Value *Addr);
535 /// PushDestructorCleanup - Push a cleanup to call the
536 /// complete-object variant of the given destructor on the object at
537 /// the given address.
538 void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
541 /// PopCleanupBlock - Will pop the cleanup entry on the stack and
542 /// process all branch fixups.
543 void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
545 void ActivateCleanup(EHScopeStack::stable_iterator Cleanup);
547 /// \brief Enters a new scope for capturing cleanups, all of which
548 /// will be executed once the scope is exited.
549 class RunCleanupsScope {
550 CodeGenFunction& CGF;
551 EHScopeStack::stable_iterator CleanupStackDepth;
552 bool OldDidCallStackSave;
555 RunCleanupsScope(const RunCleanupsScope &); // DO NOT IMPLEMENT
556 RunCleanupsScope &operator=(const RunCleanupsScope &); // DO NOT IMPLEMENT
559 /// \brief Enter a new cleanup scope.
560 explicit RunCleanupsScope(CodeGenFunction &CGF)
561 : CGF(CGF), PerformCleanup(true)
563 CleanupStackDepth = CGF.EHStack.stable_begin();
564 OldDidCallStackSave = CGF.DidCallStackSave;
567 /// \brief Exit this cleanup scope, emitting any accumulated
569 ~RunCleanupsScope() {
570 if (PerformCleanup) {
571 CGF.DidCallStackSave = OldDidCallStackSave;
572 CGF.PopCleanupBlocks(CleanupStackDepth);
576 /// \brief Determine whether this scope requires any cleanups.
577 bool requiresCleanups() const {
578 return CGF.EHStack.stable_begin() != CleanupStackDepth;
581 /// \brief Force the emission of cleanups now, instead of waiting
582 /// until this object is destroyed.
583 void ForceCleanup() {
584 assert(PerformCleanup && "Already forced cleanup");
585 CGF.DidCallStackSave = OldDidCallStackSave;
586 CGF.PopCleanupBlocks(CleanupStackDepth);
587 PerformCleanup = false;
592 /// PopCleanupBlocks - Takes the old cleanup stack size and emits
593 /// the cleanup blocks that have been added.
594 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
596 void ResolveAllBranchFixups(llvm::SwitchInst *Switch);
597 void ResolveBranchFixups(llvm::BasicBlock *Target);
599 /// The given basic block lies in the current EH scope, but may be a
600 /// target of a potentially scope-crossing jump; get a stable handle
601 /// to which we can perform this jump later.
602 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
603 return JumpDest(Target,
604 EHStack.getInnermostNormalCleanup(),
605 NextCleanupDestIndex++);
608 /// The given basic block lies in the current EH scope, but may be a
609 /// target of a potentially scope-crossing jump; get a stable handle
610 /// to which we can perform this jump later.
611 JumpDest getJumpDestInCurrentScope(const char *Name = 0) {
612 return getJumpDestInCurrentScope(createBasicBlock(Name));
615 /// EmitBranchThroughCleanup - Emit a branch from the current insert
616 /// block through the normal cleanup handling code (if any) and then
618 void EmitBranchThroughCleanup(JumpDest Dest);
620 /// EmitBranchThroughEHCleanup - Emit a branch from the current
621 /// insert block through the EH cleanup handling code (if any) and
622 /// then on to \arg Dest.
623 void EmitBranchThroughEHCleanup(UnwindDest Dest);
625 /// getRethrowDest - Returns the unified outermost-scope rethrow
627 UnwindDest getRethrowDest();
629 /// BeginConditionalBranch - Should be called before a conditional part of an
630 /// expression is emitted. For example, before the RHS of the expression below
635 /// This is used to make sure that any temporaries created in the conditional
636 /// branch are only destroyed if the branch is taken.
637 void BeginConditionalBranch() {
638 ++ConditionalBranchLevel;
641 /// EndConditionalBranch - Should be called after a conditional part of an
642 /// expression has been emitted.
643 void EndConditionalBranch() {
644 assert(ConditionalBranchLevel != 0 &&
645 "Conditional branch mismatch!");
647 --ConditionalBranchLevel;
651 CGDebugInfo *DebugInfo;
653 /// IndirectBranch - The first time an indirect goto is seen we create a block
654 /// with an indirect branch. Every time we see the address of a label taken,
655 /// we add the label to the indirect goto. Every subsequent indirect goto is
656 /// codegen'd as a jump to the IndirectBranch's basic block.
657 llvm::IndirectBrInst *IndirectBranch;
659 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
661 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
663 /// LabelMap - This keeps track of the LLVM basic block for each C label.
664 llvm::DenseMap<const LabelStmt*, JumpDest> LabelMap;
666 // BreakContinueStack - This keeps track of where break and continue
667 // statements should jump to.
668 struct BreakContinue {
669 BreakContinue(JumpDest Break, JumpDest Continue)
670 : BreakBlock(Break), ContinueBlock(Continue) {}
673 JumpDest ContinueBlock;
675 llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
677 /// SwitchInsn - This is nearest current switch instruction. It is null if if
678 /// current context is not in a switch.
679 llvm::SwitchInst *SwitchInsn;
681 /// CaseRangeBlock - This block holds if condition check for last case
682 /// statement range in current switch instruction.
683 llvm::BasicBlock *CaseRangeBlock;
685 // VLASizeMap - This keeps track of the associated size for each VLA type.
686 // We track this by the size expression rather than the type itself because
687 // in certain situations, like a const qualifier applied to an VLA typedef,
688 // multiple VLA types can share the same size expression.
689 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
690 // enter/leave scopes.
691 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
693 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
694 /// calling llvm.stacksave for multiple VLAs in the same scope.
695 bool DidCallStackSave;
697 /// A block containing a single 'unreachable' instruction. Created
698 /// lazily by getUnreachableBlock().
699 llvm::BasicBlock *UnreachableBlock;
701 /// CXXThisDecl - When generating code for a C++ member function,
702 /// this will hold the implicit 'this' declaration.
703 ImplicitParamDecl *CXXThisDecl;
704 llvm::Value *CXXThisValue;
706 /// CXXVTTDecl - When generating code for a base object constructor or
707 /// base object destructor with virtual bases, this will hold the implicit
709 ImplicitParamDecl *CXXVTTDecl;
710 llvm::Value *CXXVTTValue;
712 /// ConditionalBranchLevel - Contains the nesting level of the current
713 /// conditional branch. This is used so that we know if a temporary should be
714 /// destroyed conditionally.
715 unsigned ConditionalBranchLevel;
718 /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
719 /// type as well as the field number that contains the actual data.
720 llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *,
721 unsigned> > ByRefValueInfo;
723 /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
724 /// number that holds the value.
725 unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
727 llvm::BasicBlock *TerminateLandingPad;
728 llvm::BasicBlock *TerminateHandler;
729 llvm::BasicBlock *TrapBB;
732 CodeGenFunction(CodeGenModule &cgm);
734 CodeGenTypes &getTypes() const { return CGM.getTypes(); }
735 ASTContext &getContext() const;
736 CGDebugInfo *getDebugInfo() { return DebugInfo; }
738 /// Returns a pointer to the function's exception object slot, which
739 /// is assigned in every landing pad.
740 llvm::Value *getExceptionSlot();
742 llvm::Value *getNormalCleanupDestSlot();
743 llvm::Value *getEHCleanupDestSlot();
745 llvm::BasicBlock *getUnreachableBlock() {
746 if (!UnreachableBlock) {
747 UnreachableBlock = createBasicBlock("unreachable");
748 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
750 return UnreachableBlock;
753 llvm::BasicBlock *getInvokeDest() {
754 if (!EHStack.requiresLandingPad()) return 0;
755 return getInvokeDestImpl();
758 llvm::LLVMContext &getLLVMContext() { return VMContext; }
760 //===--------------------------------------------------------------------===//
762 //===--------------------------------------------------------------------===//
764 void GenerateObjCMethod(const ObjCMethodDecl *OMD);
766 void StartObjCMethod(const ObjCMethodDecl *MD,
767 const ObjCContainerDecl *CD);
769 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
770 void GenerateObjCGetter(ObjCImplementationDecl *IMP,
771 const ObjCPropertyImplDecl *PID);
772 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
773 ObjCMethodDecl *MD, bool ctor);
775 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
776 /// for the given property.
777 void GenerateObjCSetter(ObjCImplementationDecl *IMP,
778 const ObjCPropertyImplDecl *PID);
779 bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
780 bool IvarTypeWithAggrGCObjects(QualType Ty);
782 //===--------------------------------------------------------------------===//
784 //===--------------------------------------------------------------------===//
786 llvm::Value *BuildBlockLiteralTmp(const BlockExpr *);
787 llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
788 const CGBlockInfo &Info,
789 const llvm::StructType *,
790 llvm::Constant *BlockVarLayout,
791 std::vector<HelperInfo> *);
793 llvm::Function *GenerateBlockFunction(GlobalDecl GD,
794 const BlockExpr *BExpr,
796 const Decl *OuterFuncDecl,
797 llvm::Constant *& BlockVarLayout,
798 llvm::DenseMap<const Decl*, llvm::Value*> ldm);
800 llvm::Value *LoadBlockStruct();
802 void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
803 void AllocateBlockDecl(const BlockDeclRefExpr *E);
804 llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
805 return GetAddrOfBlockDecl(E->getDecl(), E->isByRef());
807 llvm::Value *GetAddrOfBlockDecl(const ValueDecl *D, bool ByRef);
808 const llvm::Type *BuildByRefType(const ValueDecl *D);
810 void GenerateCode(GlobalDecl GD, llvm::Function *Fn);
811 void StartFunction(GlobalDecl GD, QualType RetTy,
813 const FunctionArgList &Args,
814 SourceLocation StartLoc);
816 void EmitConstructorBody(FunctionArgList &Args);
817 void EmitDestructorBody(FunctionArgList &Args);
818 void EmitFunctionBody(FunctionArgList &Args);
820 /// EmitReturnBlock - Emit the unified return block, trying to avoid its
821 /// emission when possible.
822 void EmitReturnBlock();
824 /// FinishFunction - Complete IR generation of the current function. It is
825 /// legal to call this function even if there is no current insertion point.
826 void FinishFunction(SourceLocation EndLoc=SourceLocation());
828 /// GenerateThunk - Generate a thunk for the given method.
829 void GenerateThunk(llvm::Function *Fn, GlobalDecl GD, const ThunkInfo &Thunk);
831 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
832 FunctionArgList &Args);
834 /// InitializeVTablePointer - Initialize the vtable pointer of the given
837 void InitializeVTablePointer(BaseSubobject Base,
838 const CXXRecordDecl *NearestVBase,
839 uint64_t OffsetFromNearestVBase,
840 llvm::Constant *VTable,
841 const CXXRecordDecl *VTableClass);
843 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
844 void InitializeVTablePointers(BaseSubobject Base,
845 const CXXRecordDecl *NearestVBase,
846 uint64_t OffsetFromNearestVBase,
847 bool BaseIsNonVirtualPrimaryBase,
848 llvm::Constant *VTable,
849 const CXXRecordDecl *VTableClass,
850 VisitedVirtualBasesSetTy& VBases);
852 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
855 /// EnterDtorCleanups - Enter the cleanups necessary to complete the
856 /// given phase of destruction for a destructor. The end result
857 /// should call destructors on members and base classes in reverse
858 /// order of their construction.
859 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
861 /// ShouldInstrumentFunction - Return true if the current function should be
862 /// instrumented with __cyg_profile_func_* calls
863 bool ShouldInstrumentFunction();
865 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
866 /// instrumentation function with the current function and the call site, if
867 /// function instrumentation is enabled.
868 void EmitFunctionInstrumentation(const char *Fn);
870 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
871 /// arguments for the given function. This is also responsible for naming the
872 /// LLVM function arguments.
873 void EmitFunctionProlog(const CGFunctionInfo &FI,
875 const FunctionArgList &Args);
877 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
879 void EmitFunctionEpilog(const CGFunctionInfo &FI);
881 /// EmitStartEHSpec - Emit the start of the exception spec.
882 void EmitStartEHSpec(const Decl *D);
884 /// EmitEndEHSpec - Emit the end of the exception spec.
885 void EmitEndEHSpec(const Decl *D);
887 /// getTerminateLandingPad - Return a landing pad that just calls terminate.
888 llvm::BasicBlock *getTerminateLandingPad();
890 /// getTerminateHandler - Return a handler (not a landing pad, just
891 /// a catch handler) that just calls terminate. This is used when
892 /// a terminate scope encloses a try.
893 llvm::BasicBlock *getTerminateHandler();
895 const llvm::Type *ConvertTypeForMem(QualType T);
896 const llvm::Type *ConvertType(QualType T);
897 const llvm::Type *ConvertType(const TypeDecl *T) {
898 return ConvertType(getContext().getTypeDeclType(T));
901 /// LoadObjCSelf - Load the value of self. This function is only valid while
902 /// generating code for an Objective-C method.
903 llvm::Value *LoadObjCSelf();
905 /// TypeOfSelfObject - Return type of object that this self represents.
906 QualType TypeOfSelfObject();
908 /// hasAggregateLLVMType - Return true if the specified AST type will map into
909 /// an aggregate LLVM type or is void.
910 static bool hasAggregateLLVMType(QualType T);
912 /// createBasicBlock - Create an LLVM basic block.
913 llvm::BasicBlock *createBasicBlock(const char *Name="",
914 llvm::Function *Parent=0,
915 llvm::BasicBlock *InsertBefore=0) {
917 return llvm::BasicBlock::Create(VMContext, "", Parent, InsertBefore);
919 return llvm::BasicBlock::Create(VMContext, Name, Parent, InsertBefore);
923 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
925 JumpDest getJumpDestForLabel(const LabelStmt *S);
927 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
928 /// another basic block, simplify it. This assumes that no other code could
929 /// potentially reference the basic block.
930 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
932 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
933 /// adding a fall-through branch from the current insert block if
934 /// necessary. It is legal to call this function even if there is no current
937 /// IsFinished - If true, indicates that the caller has finished emitting
938 /// branches to the given block and does not expect to emit code into it. This
939 /// means the block can be ignored if it is unreachable.
940 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
942 /// EmitBranch - Emit a branch to the specified basic block from the current
943 /// insert block, taking care to avoid creation of branches from dummy
944 /// blocks. It is legal to call this function even if there is no current
947 /// This function clears the current insertion point. The caller should follow
948 /// calls to this function with calls to Emit*Block prior to generation new
950 void EmitBranch(llvm::BasicBlock *Block);
952 /// HaveInsertPoint - True if an insertion point is defined. If not, this
953 /// indicates that the current code being emitted is unreachable.
954 bool HaveInsertPoint() const {
955 return Builder.GetInsertBlock() != 0;
958 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
959 /// emitted IR has a place to go. Note that by definition, if this function
960 /// creates a block then that block is unreachable; callers may do better to
961 /// detect when no insertion point is defined and simply skip IR generation.
962 void EnsureInsertPoint() {
963 if (!HaveInsertPoint())
964 EmitBlock(createBasicBlock());
967 /// ErrorUnsupported - Print out an error that codegen doesn't support the
968 /// specified stmt yet.
969 void ErrorUnsupported(const Stmt *S, const char *Type,
970 bool OmitOnError=false);
972 //===--------------------------------------------------------------------===//
974 //===--------------------------------------------------------------------===//
976 LValue MakeAddrLValue(llvm::Value *V, QualType T, unsigned Alignment = 0) {
977 return LValue::MakeAddr(V, T, Alignment, getContext());
980 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
981 /// block. The caller is responsible for setting an appropriate alignment on
983 llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
984 const llvm::Twine &Name = "tmp");
986 /// InitTempAlloca - Provide an initial value for the given alloca.
987 void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
989 /// CreateIRTemp - Create a temporary IR object of the given type, with
990 /// appropriate alignment. This routine should only be used when an temporary
991 /// value needs to be stored into an alloca (for example, to avoid explicit
992 /// PHI construction), but the type is the IR type, not the type appropriate
993 /// for storing in memory.
994 llvm::AllocaInst *CreateIRTemp(QualType T, const llvm::Twine &Name = "tmp");
996 /// CreateMemTemp - Create a temporary memory object of the given type, with
997 /// appropriate alignment.
998 llvm::AllocaInst *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp");
1000 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1001 /// expression and compare the result against zero, returning an Int1Ty value.
1002 llvm::Value *EvaluateExprAsBool(const Expr *E);
1004 /// EmitAnyExpr - Emit code to compute the specified expression which can have
1005 /// any type. The result is returned as an RValue struct. If this is an
1006 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1007 /// the result should be returned.
1009 /// \param IgnoreResult - True if the resulting value isn't used.
1010 RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
1011 bool IsAggLocVolatile = false, bool IgnoreResult = false,
1012 bool IsInitializer = false);
1014 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1015 // or the value of the expression, depending on how va_list is defined.
1016 llvm::Value *EmitVAListRef(const Expr *E);
1018 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
1019 /// always be accessible even if no aggregate location is provided.
1020 RValue EmitAnyExprToTemp(const Expr *E, bool IsAggLocVolatile = false,
1021 bool IsInitializer = false);
1023 /// EmitsAnyExprToMem - Emits the code necessary to evaluate an
1024 /// arbitrary expression into the given memory location.
1025 void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
1026 bool IsLocationVolatile = false,
1027 bool IsInitializer = false);
1029 /// EmitAggregateCopy - Emit an aggrate copy.
1031 /// \param isVolatile - True iff either the source or the destination is
1033 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1034 QualType EltTy, bool isVolatile=false);
1036 /// StartBlock - Start new block named N. If insert block is a dummy block
1038 void StartBlock(const char *N);
1040 /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
1041 llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD) {
1042 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
1045 /// GetAddrOfLocalVar - Return the address of a local variable.
1046 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) {
1047 llvm::Value *Res = LocalDeclMap[VD];
1048 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
1052 /// getAccessedFieldNo - Given an encoded value and a result number, return
1053 /// the input field number being accessed.
1054 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
1056 llvm::BlockAddress *GetAddrOfLabel(const LabelStmt *L);
1057 llvm::BasicBlock *GetIndirectGotoBlock();
1059 /// EmitNullInitialization - Generate code to set a value of the given type to
1060 /// null, If the type contains data member pointers, they will be initialized
1061 /// to -1 in accordance with the Itanium C++ ABI.
1062 void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
1064 // EmitVAArg - Generate code to get an argument from the passed in pointer
1065 // and update it accordingly. The return value is a pointer to the argument.
1066 // FIXME: We should be able to get rid of this method and use the va_arg
1067 // instruction in LLVM instead once it works well enough.
1068 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
1070 /// EmitVLASize - Generate code for any VLA size expressions that might occur
1071 /// in a variably modified type. If Ty is a VLA, will return the value that
1072 /// corresponds to the size in bytes of the VLA type. Will return 0 otherwise.
1074 /// This function can be called with a null (unreachable) insert point.
1075 llvm::Value *EmitVLASize(QualType Ty);
1077 // GetVLASize - Returns an LLVM value that corresponds to the size in bytes
1078 // of a variable length array type.
1079 llvm::Value *GetVLASize(const VariableArrayType *);
1081 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
1082 /// generating code for an C++ member function.
1083 llvm::Value *LoadCXXThis() {
1084 assert(CXXThisValue && "no 'this' value for this function");
1085 return CXXThisValue;
1088 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
1090 llvm::Value *LoadCXXVTT() {
1091 assert(CXXVTTValue && "no VTT value for this function");
1095 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
1096 /// complete class to the given direct base.
1098 GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
1099 const CXXRecordDecl *Derived,
1100 const CXXRecordDecl *Base,
1101 bool BaseIsVirtual);
1103 /// GetAddressOfBaseClass - This function will add the necessary delta to the
1104 /// load of 'this' and returns address of the base class.
1105 llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
1106 const CXXRecordDecl *Derived,
1107 CastExpr::path_const_iterator PathBegin,
1108 CastExpr::path_const_iterator PathEnd,
1109 bool NullCheckValue);
1111 llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
1112 const CXXRecordDecl *Derived,
1113 CastExpr::path_const_iterator PathBegin,
1114 CastExpr::path_const_iterator PathEnd,
1115 bool NullCheckValue);
1117 llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
1118 const CXXRecordDecl *ClassDecl,
1119 const CXXRecordDecl *BaseClassDecl);
1121 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1122 CXXCtorType CtorType,
1123 const FunctionArgList &Args);
1124 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
1125 bool ForVirtualBase, llvm::Value *This,
1126 CallExpr::const_arg_iterator ArgBeg,
1127 CallExpr::const_arg_iterator ArgEnd);
1129 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1130 const ConstantArrayType *ArrayTy,
1131 llvm::Value *ArrayPtr,
1132 CallExpr::const_arg_iterator ArgBeg,
1133 CallExpr::const_arg_iterator ArgEnd,
1134 bool ZeroInitialization = false);
1136 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1137 llvm::Value *NumElements,
1138 llvm::Value *ArrayPtr,
1139 CallExpr::const_arg_iterator ArgBeg,
1140 CallExpr::const_arg_iterator ArgEnd,
1141 bool ZeroInitialization = false);
1143 void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1144 const ArrayType *Array,
1147 void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1148 llvm::Value *NumElements,
1151 llvm::Function *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
1152 const ArrayType *Array,
1155 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
1156 bool ForVirtualBase, llvm::Value *This);
1158 void EmitNewArrayInitializer(const CXXNewExpr *E, llvm::Value *NewPtr,
1159 llvm::Value *NumElements);
1161 void EmitCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
1163 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
1164 void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
1166 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
1169 llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
1170 llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
1172 void EmitCheck(llvm::Value *, unsigned Size);
1174 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1175 bool isInc, bool isPre);
1176 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
1177 bool isInc, bool isPre);
1178 //===--------------------------------------------------------------------===//
1179 // Declaration Emission
1180 //===--------------------------------------------------------------------===//
1182 /// EmitDecl - Emit a declaration.
1184 /// This function can be called with a null (unreachable) insert point.
1185 void EmitDecl(const Decl &D);
1187 /// EmitBlockVarDecl - Emit a block variable declaration.
1189 /// This function can be called with a null (unreachable) insert point.
1190 void EmitBlockVarDecl(const VarDecl &D);
1192 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
1193 llvm::Value *Address);
1195 /// EmitLocalBlockVarDecl - Emit a local block variable declaration.
1197 /// This function can be called with a null (unreachable) insert point.
1198 void EmitLocalBlockVarDecl(const VarDecl &D, SpecialInitFn *SpecialInit = 0);
1200 void EmitStaticBlockVarDecl(const VarDecl &D,
1201 llvm::GlobalValue::LinkageTypes Linkage);
1203 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
1204 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
1206 //===--------------------------------------------------------------------===//
1207 // Statement Emission
1208 //===--------------------------------------------------------------------===//
1210 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
1211 void EmitStopPoint(const Stmt *S);
1213 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
1214 /// this function even if there is no current insertion point.
1216 /// This function may clear the current insertion point; callers should use
1217 /// EnsureInsertPoint if they wish to subsequently generate code without first
1218 /// calling EmitBlock, EmitBranch, or EmitStmt.
1219 void EmitStmt(const Stmt *S);
1221 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
1222 /// necessarily require an insertion point or debug information; typically
1223 /// because the statement amounts to a jump or a container of other
1226 /// \return True if the statement was handled.
1227 bool EmitSimpleStmt(const Stmt *S);
1229 RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
1230 llvm::Value *AggLoc = 0, bool isAggVol = false);
1232 /// EmitLabel - Emit the block for the given label. It is legal to call this
1233 /// function even if there is no current insertion point.
1234 void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
1236 void EmitLabelStmt(const LabelStmt &S);
1237 void EmitGotoStmt(const GotoStmt &S);
1238 void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
1239 void EmitIfStmt(const IfStmt &S);
1240 void EmitWhileStmt(const WhileStmt &S);
1241 void EmitDoStmt(const DoStmt &S);
1242 void EmitForStmt(const ForStmt &S);
1243 void EmitReturnStmt(const ReturnStmt &S);
1244 void EmitDeclStmt(const DeclStmt &S);
1245 void EmitBreakStmt(const BreakStmt &S);
1246 void EmitContinueStmt(const ContinueStmt &S);
1247 void EmitSwitchStmt(const SwitchStmt &S);
1248 void EmitDefaultStmt(const DefaultStmt &S);
1249 void EmitCaseStmt(const CaseStmt &S);
1250 void EmitCaseStmtRange(const CaseStmt &S);
1251 void EmitAsmStmt(const AsmStmt &S);
1253 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
1254 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
1255 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
1256 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
1258 llvm::Constant *getUnwindResumeOrRethrowFn();
1259 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
1260 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
1262 void EmitCXXTryStmt(const CXXTryStmt &S);
1264 //===--------------------------------------------------------------------===//
1265 // LValue Expression Emission
1266 //===--------------------------------------------------------------------===//
1268 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
1269 RValue GetUndefRValue(QualType Ty);
1271 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
1272 /// and issue an ErrorUnsupported style diagnostic (using the
1274 RValue EmitUnsupportedRValue(const Expr *E,
1277 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
1278 /// an ErrorUnsupported style diagnostic (using the provided Name).
1279 LValue EmitUnsupportedLValue(const Expr *E,
1282 /// EmitLValue - Emit code to compute a designator that specifies the location
1283 /// of the expression.
1285 /// This can return one of two things: a simple address or a bitfield
1286 /// reference. In either case, the LLVM Value* in the LValue structure is
1287 /// guaranteed to be an LLVM pointer type.
1289 /// If this returns a bitfield reference, nothing about the pointee type of
1290 /// the LLVM value is known: For example, it may not be a pointer to an
1293 /// If this returns a normal address, and if the lvalue's C type is fixed
1294 /// size, this method guarantees that the returned pointer type will point to
1295 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
1296 /// variable length type, this is not possible.
1298 LValue EmitLValue(const Expr *E);
1300 /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
1301 /// checking code to guard against undefined behavior. This is only
1302 /// suitable when we know that the address will be used to access the
1304 LValue EmitCheckedLValue(const Expr *E);
1306 /// EmitLoadOfScalar - Load a scalar value from an address, taking
1307 /// care to appropriately convert from the memory representation to
1308 /// the LLVM value representation.
1309 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
1310 unsigned Alignment, QualType Ty);
1312 /// EmitStoreOfScalar - Store a scalar value to an address, taking
1313 /// care to appropriately convert from the memory representation to
1314 /// the LLVM value representation.
1315 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
1316 bool Volatile, unsigned Alignment, QualType Ty);
1318 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
1319 /// this method emits the address of the lvalue, then loads the result as an
1320 /// rvalue, returning the rvalue.
1321 RValue EmitLoadOfLValue(LValue V, QualType LVType);
1322 RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
1323 RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
1324 RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType);
1325 RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType);
1328 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1329 /// lvalue, where both are guaranteed to the have the same type, and that type
1331 void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
1332 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
1334 void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty);
1335 void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty);
1337 /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
1338 /// EmitStoreThroughLValue.
1340 /// \param Result [out] - If non-null, this will be set to a Value* for the
1341 /// bit-field contents after the store, appropriate for use as the result of
1342 /// an assignment to the bit-field.
1343 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
1344 llvm::Value **Result=0);
1346 // Note: only availabe for agg return types
1347 LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
1348 LValue EmitCompoundAssignOperatorLValue(const CompoundAssignOperator *E);
1349 // Note: only available for agg return types
1350 LValue EmitCallExprLValue(const CallExpr *E);
1351 // Note: only available for agg return types
1352 LValue EmitVAArgExprLValue(const VAArgExpr *E);
1353 LValue EmitDeclRefLValue(const DeclRefExpr *E);
1354 LValue EmitStringLiteralLValue(const StringLiteral *E);
1355 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
1356 LValue EmitPredefinedLValue(const PredefinedExpr *E);
1357 LValue EmitUnaryOpLValue(const UnaryOperator *E);
1358 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
1359 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
1360 LValue EmitMemberExpr(const MemberExpr *E);
1361 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
1362 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
1363 LValue EmitConditionalOperatorLValue(const ConditionalOperator *E);
1364 LValue EmitCastLValue(const CastExpr *E);
1365 LValue EmitNullInitializationLValue(const CXXScalarValueInitExpr *E);
1367 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1368 const ObjCIvarDecl *Ivar);
1369 LValue EmitLValueForAnonRecordField(llvm::Value* Base,
1370 const FieldDecl* Field,
1371 unsigned CVRQualifiers);
1372 LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
1373 unsigned CVRQualifiers);
1375 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
1376 /// if the Field is a reference, this will return the address of the reference
1377 /// and not the address of the value stored in the reference.
1378 LValue EmitLValueForFieldInitialization(llvm::Value* Base,
1379 const FieldDecl* Field,
1380 unsigned CVRQualifiers);
1382 LValue EmitLValueForIvar(QualType ObjectTy,
1383 llvm::Value* Base, const ObjCIvarDecl *Ivar,
1384 unsigned CVRQualifiers);
1386 LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
1387 unsigned CVRQualifiers);
1389 LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
1391 LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
1392 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
1393 LValue EmitCXXExprWithTemporariesLValue(const CXXExprWithTemporaries *E);
1394 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
1396 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
1397 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
1398 LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
1399 LValue EmitObjCKVCRefLValue(const ObjCImplicitSetterGetterRefExpr *E);
1400 LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E);
1401 LValue EmitStmtExprLValue(const StmtExpr *E);
1402 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
1403 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
1404 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::ConstantInt *Init);
1405 //===--------------------------------------------------------------------===//
1406 // Scalar Expression Emission
1407 //===--------------------------------------------------------------------===//
1409 /// EmitCall - Generate a call of the given function, expecting the given
1410 /// result type, and using the given argument list which specifies both the
1411 /// LLVM arguments and the types they were derived from.
1413 /// \param TargetDecl - If given, the decl of the function in a direct call;
1414 /// used to set attributes on the call (noreturn, etc.).
1415 RValue EmitCall(const CGFunctionInfo &FnInfo,
1416 llvm::Value *Callee,
1417 ReturnValueSlot ReturnValue,
1418 const CallArgList &Args,
1419 const Decl *TargetDecl = 0,
1420 llvm::Instruction **callOrInvoke = 0);
1422 RValue EmitCall(QualType FnType, llvm::Value *Callee,
1423 ReturnValueSlot ReturnValue,
1424 CallExpr::const_arg_iterator ArgBeg,
1425 CallExpr::const_arg_iterator ArgEnd,
1426 const Decl *TargetDecl = 0);
1427 RValue EmitCallExpr(const CallExpr *E,
1428 ReturnValueSlot ReturnValue = ReturnValueSlot());
1430 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
1431 llvm::Value * const *ArgBegin,
1432 llvm::Value * const *ArgEnd,
1433 const llvm::Twine &Name = "");
1435 llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1436 const llvm::Type *Ty);
1437 llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1438 llvm::Value *&This, const llvm::Type *Ty);
1440 RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
1441 llvm::Value *Callee,
1442 ReturnValueSlot ReturnValue,
1445 CallExpr::const_arg_iterator ArgBeg,
1446 CallExpr::const_arg_iterator ArgEnd);
1447 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
1448 ReturnValueSlot ReturnValue);
1449 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
1450 ReturnValueSlot ReturnValue);
1452 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
1453 const CXXMethodDecl *MD,
1454 ReturnValueSlot ReturnValue);
1457 RValue EmitBuiltinExpr(const FunctionDecl *FD,
1458 unsigned BuiltinID, const CallExpr *E);
1460 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
1462 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
1463 /// is unhandled by the current target.
1464 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1466 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1467 llvm::Value *EmitNeonCall(llvm::Function *F,
1468 llvm::SmallVectorImpl<llvm::Value*> &O,
1469 const char *name, bool splat = false,
1470 unsigned shift = 0, bool rightshift = false);
1471 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx,
1472 bool widen = false);
1473 llvm::Value *EmitNeonShiftVector(llvm::Value *V, const llvm::Type *Ty,
1474 bool negateForRightShift);
1476 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1477 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1479 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
1480 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
1481 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
1482 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
1483 ReturnValueSlot Return = ReturnValueSlot());
1484 RValue EmitObjCPropertyGet(const Expr *E,
1485 ReturnValueSlot Return = ReturnValueSlot());
1486 RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S,
1487 ReturnValueSlot Return = ReturnValueSlot());
1488 void EmitObjCPropertySet(const Expr *E, RValue Src);
1489 void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src);
1492 /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
1493 /// expression. Will emit a temporary variable if E is not an LValue.
1494 RValue EmitReferenceBindingToExpr(const Expr* E,
1495 const NamedDecl *InitializedDecl);
1497 //===--------------------------------------------------------------------===//
1498 // Expression Emission
1499 //===--------------------------------------------------------------------===//
1501 // Expressions are broken into three classes: scalar, complex, aggregate.
1503 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
1504 /// scalar type, returning the result.
1505 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
1507 /// EmitScalarConversion - Emit a conversion from the specified type to the
1508 /// specified destination type, both of which are LLVM scalar types.
1509 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
1512 /// EmitComplexToScalarConversion - Emit a conversion from the specified
1513 /// complex type to the specified destination type, where the destination type
1514 /// is an LLVM scalar type.
1515 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
1519 /// EmitAggExpr - Emit the computation of the specified expression of
1520 /// aggregate type. The result is computed into DestPtr. Note that if
1521 /// DestPtr is null, the value of the aggregate expression is not needed.
1522 void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest,
1523 bool IgnoreResult = false, bool IsInitializer = false,
1524 bool RequiresGCollection = false);
1526 /// EmitAggExprToLValue - Emit the computation of the specified expression of
1527 /// aggregate type into a temporary LValue.
1528 LValue EmitAggExprToLValue(const Expr *E);
1530 /// EmitGCMemmoveCollectable - Emit special API for structs with object
1532 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1535 /// EmitComplexExpr - Emit the computation of the specified expression of
1536 /// complex type, returning the result.
1537 ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false,
1538 bool IgnoreImag = false,
1539 bool IgnoreRealAssign = false,
1540 bool IgnoreImagAssign = false);
1542 /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
1543 /// of complex type, storing into the specified Value*.
1544 void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
1545 bool DestIsVolatile);
1547 /// StoreComplexToAddr - Store a complex number into the specified address.
1548 void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
1549 bool DestIsVolatile);
1550 /// LoadComplexFromAddr - Load a complex number from the specified address.
1551 ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
1553 /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global for a
1554 /// static block var decl.
1555 llvm::GlobalVariable *CreateStaticBlockVarDecl(const VarDecl &D,
1556 const char *Separator,
1557 llvm::GlobalValue::LinkageTypes Linkage);
1559 /// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the
1560 /// global variable that has already been created for it. If the initializer
1561 /// has a different type than GV does, this may free GV and return a different
1562 /// one. Otherwise it just returns GV.
1563 llvm::GlobalVariable *
1564 AddInitializerToGlobalBlockVarDecl(const VarDecl &D,
1565 llvm::GlobalVariable *GV);
1568 /// EmitStaticCXXBlockVarDeclInit - Create the initializer for a C++ runtime
1569 /// initialized static block var decl.
1570 void EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
1571 llvm::GlobalVariable *GV);
1573 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
1574 /// variable with global storage.
1575 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
1577 /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
1578 /// with the C++ runtime so that its destructor will be called at exit.
1579 void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
1580 llvm::Constant *DeclPtr);
1582 /// GenerateCXXGlobalInitFunc - Generates code for initializing global
1584 void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
1585 llvm::Constant **Decls,
1588 /// GenerateCXXGlobalDtorFunc - Generates code for destroying global
1590 void GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
1591 const std::vector<std::pair<llvm::WeakVH,
1592 llvm::Constant*> > &DtorsAndObjects);
1594 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D);
1596 void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E);
1598 RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E,
1599 llvm::Value *AggLoc = 0,
1600 bool IsAggLocVolatile = false,
1601 bool IsInitializer = false);
1603 void EmitCXXThrowExpr(const CXXThrowExpr *E);
1605 //===--------------------------------------------------------------------===//
1607 //===--------------------------------------------------------------------===//
1609 /// ContainsLabel - Return true if the statement contains a label in it. If
1610 /// this statement is not executed normally, it not containing a label means
1611 /// that we can just remove the code.
1612 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
1614 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1615 /// to a constant, or if it does but contains a label, return 0. If it
1616 /// constant folds to 'true' and does not contain a label, return 1, if it
1617 /// constant folds to 'false' and does not contain a label, return -1.
1618 int ConstantFoldsToSimpleInteger(const Expr *Cond);
1620 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
1621 /// if statement) to the specified blocks. Based on the condition, this might
1622 /// try to simplify the codegen of the conditional based on the branch.
1623 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
1624 llvm::BasicBlock *FalseBlock);
1626 /// getTrapBB - Create a basic block that will call the trap intrinsic. We'll
1627 /// generate a branch around the created basic block as necessary.
1628 llvm::BasicBlock *getTrapBB();
1630 /// EmitCallArg - Emit a single call argument.
1631 RValue EmitCallArg(const Expr *E, QualType ArgType);
1633 /// EmitDelegateCallArg - We are performing a delegate call; that
1634 /// is, the current function is delegating to another one. Produce
1635 /// a r-value suitable for passing the given parameter.
1636 RValue EmitDelegateCallArg(const VarDecl *Param);
1639 void EmitReturnOfRValue(RValue RV, QualType Ty);
1641 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
1642 /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
1644 /// \param AI - The first function argument of the expansion.
1645 /// \return The argument following the last expanded function
1647 llvm::Function::arg_iterator
1648 ExpandTypeFromArgs(QualType Ty, LValue Dst,
1649 llvm::Function::arg_iterator AI);
1651 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
1652 /// Ty, into individual arguments on the provided vector \arg Args. See
1653 /// ABIArgInfo::Expand.
1654 void ExpandTypeToArgs(QualType Ty, RValue Src,
1655 llvm::SmallVector<llvm::Value*, 16> &Args);
1657 llvm::Value* EmitAsmInput(const AsmStmt &S,
1658 const TargetInfo::ConstraintInfo &Info,
1659 const Expr *InputExpr, std::string &ConstraintStr);
1661 llvm::Value* EmitAsmInputLValue(const AsmStmt &S,
1662 const TargetInfo::ConstraintInfo &Info,
1663 LValue InputValue, QualType InputType,
1664 std::string &ConstraintStr);
1666 /// EmitCallArgs - Emit call arguments for a function.
1667 /// The CallArgTypeInfo parameter is used for iterating over the known
1668 /// argument types of the function being called.
1669 template<typename T>
1670 void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
1671 CallExpr::const_arg_iterator ArgBeg,
1672 CallExpr::const_arg_iterator ArgEnd) {
1673 CallExpr::const_arg_iterator Arg = ArgBeg;
1675 // First, use the argument types that the type info knows about
1676 if (CallArgTypeInfo) {
1677 for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
1678 E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
1679 assert(Arg != ArgEnd && "Running over edge of argument list!");
1680 QualType ArgType = *I;
1682 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
1684 getContext().getCanonicalType(Arg->getType()).getTypePtr() &&
1685 "type mismatch in call argument!");
1687 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1691 // Either we've emitted all the call args, or we have a call to a
1692 // variadic function.
1693 assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
1694 "Extra arguments in non-variadic function!");
1698 // If we still have any arguments, emit them using the type of the argument.
1699 for (; Arg != ArgEnd; ++Arg) {
1700 QualType ArgType = Arg->getType();
1701 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1706 const TargetCodeGenInfo &getTargetHooks() const {
1707 return CGM.getTargetCodeGenInfo();
1710 void EmitDeclMetadata();
1713 /// CGBlockInfo - Information to generate a block literal.
1716 /// Name - The name of the block, kindof.
1719 /// DeclRefs - Variables from parent scopes that have been
1720 /// imported into this block.
1721 llvm::SmallVector<const BlockDeclRefExpr *, 8> DeclRefs;
1723 /// InnerBlocks - This block and the blocks it encloses.
1724 llvm::SmallPtrSet<const DeclContext *, 4> InnerBlocks;
1726 /// CXXThisRef - Non-null if 'this' was required somewhere, in
1727 /// which case this is that expression.
1728 const CXXThisExpr *CXXThisRef;
1730 /// NeedsObjCSelf - True if something in this block has an implicit
1731 /// reference to 'self'.
1734 /// These are initialized by GenerateBlockFunction.
1735 bool BlockHasCopyDispose;
1736 CharUnits BlockSize;
1737 CharUnits BlockAlign;
1738 llvm::SmallVector<const Expr*, 8> BlockLayout;
1740 CGBlockInfo(const char *Name);
1743 } // end namespace CodeGen
1744 } // end namespace clang