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 "CGBuilder.h"
18 #include "CGDebugInfo.h"
19 #include "CGLoopInfo.h"
21 #include "CodeGenModule.h"
22 #include "CodeGenPGO.h"
23 #include "EHScopeStack.h"
24 #include "clang/AST/CharUnits.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/Type.h"
28 #include "clang/Basic/ABI.h"
29 #include "clang/Basic/CapturedStmt.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Frontend/CodeGenOptions.h"
32 #include "llvm/ADT/ArrayRef.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/IR/ValueHandle.h"
36 #include "llvm/Support/Debug.h"
52 class CXXDestructorDecl;
53 class CXXForRangeStmt;
57 class EnumConstantDecl;
59 class FunctionProtoType;
61 class ObjCContainerDecl;
62 class ObjCInterfaceDecl;
65 class ObjCImplementationDecl;
66 class ObjCPropertyImplDecl;
68 class TargetCodeGenInfo;
70 class ObjCForCollectionStmt;
72 class ObjCAtThrowStmt;
73 class ObjCAtSynchronizedStmt;
74 class ObjCAutoreleasePoolStmt;
83 class BlockFieldFlags;
85 /// The kind of evaluation to perform on values of a particular
86 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or
89 /// TODO: should vectors maybe be split out into their own thing?
90 enum TypeEvaluationKind {
96 class SuppressDebugLocation {
97 llvm::DebugLoc CurLoc;
98 llvm::IRBuilderBase &Builder;
100 SuppressDebugLocation(llvm::IRBuilderBase &Builder)
101 : CurLoc(Builder.getCurrentDebugLocation()), Builder(Builder) {
102 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
104 ~SuppressDebugLocation() {
105 Builder.SetCurrentDebugLocation(CurLoc);
109 /// CodeGenFunction - This class organizes the per-function state that is used
110 /// while generating LLVM code.
111 class CodeGenFunction : public CodeGenTypeCache {
112 CodeGenFunction(const CodeGenFunction &) LLVM_DELETED_FUNCTION;
113 void operator=(const CodeGenFunction &) LLVM_DELETED_FUNCTION;
115 friend class CGCXXABI;
117 /// A jump destination is an abstract label, branching to which may
118 /// require a jump out through normal cleanups.
120 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
121 JumpDest(llvm::BasicBlock *Block,
122 EHScopeStack::stable_iterator Depth,
124 : Block(Block), ScopeDepth(Depth), Index(Index) {}
126 bool isValid() const { return Block != nullptr; }
127 llvm::BasicBlock *getBlock() const { return Block; }
128 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
129 unsigned getDestIndex() const { return Index; }
131 // This should be used cautiously.
132 void setScopeDepth(EHScopeStack::stable_iterator depth) {
137 llvm::BasicBlock *Block;
138 EHScopeStack::stable_iterator ScopeDepth;
142 CodeGenModule &CGM; // Per-module state.
143 const TargetInfo &Target;
145 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
146 LoopInfoStack LoopStack;
149 /// \brief CGBuilder insert helper. This function is called after an
150 /// instruction is created using Builder.
151 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
152 llvm::BasicBlock *BB,
153 llvm::BasicBlock::iterator InsertPt) const;
155 /// CurFuncDecl - Holds the Decl for the current outermost
156 /// non-closure context.
157 const Decl *CurFuncDecl;
158 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
159 const Decl *CurCodeDecl;
160 const CGFunctionInfo *CurFnInfo;
162 llvm::Function *CurFn;
164 /// CurGD - The GlobalDecl for the current function being compiled.
167 /// PrologueCleanupDepth - The cleanup depth enclosing all the
168 /// cleanups associated with the parameters.
169 EHScopeStack::stable_iterator PrologueCleanupDepth;
171 /// ReturnBlock - Unified return block.
172 JumpDest ReturnBlock;
174 /// ReturnValue - The temporary alloca to hold the return value. This is null
175 /// iff the function has no return value.
176 llvm::Value *ReturnValue;
178 /// AllocaInsertPoint - This is an instruction in the entry block before which
179 /// we prefer to insert allocas.
180 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
182 /// \brief API for captured statement code generation.
183 class CGCapturedStmtInfo {
185 explicit CGCapturedStmtInfo(const CapturedStmt &S,
186 CapturedRegionKind K = CR_Default)
187 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
189 RecordDecl::field_iterator Field =
190 S.getCapturedRecordDecl()->field_begin();
191 for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
193 I != E; ++I, ++Field) {
194 if (I->capturesThis())
195 CXXThisFieldDecl = *Field;
197 CaptureFields[I->getCapturedVar()] = *Field;
201 virtual ~CGCapturedStmtInfo();
203 CapturedRegionKind getKind() const { return Kind; }
205 void setContextValue(llvm::Value *V) { ThisValue = V; }
206 // \brief Retrieve the value of the context parameter.
207 llvm::Value *getContextValue() const { return ThisValue; }
209 /// \brief Lookup the captured field decl for a variable.
210 const FieldDecl *lookup(const VarDecl *VD) const {
211 return CaptureFields.lookup(VD);
214 bool isCXXThisExprCaptured() const { return CXXThisFieldDecl != nullptr; }
215 FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
217 /// \brief Emit the captured statement body.
218 virtual void EmitBody(CodeGenFunction &CGF, Stmt *S) {
219 RegionCounter Cnt = CGF.getPGORegionCounter(S);
220 Cnt.beginRegion(CGF.Builder);
224 /// \brief Get the name of the capture helper.
225 virtual StringRef getHelperName() const { return "__captured_stmt"; }
228 /// \brief The kind of captured statement being generated.
229 CapturedRegionKind Kind;
231 /// \brief Keep the map between VarDecl and FieldDecl.
232 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
234 /// \brief The base address of the captured record, passed in as the first
235 /// argument of the parallel region function.
236 llvm::Value *ThisValue;
238 /// \brief Captured 'this' type.
239 FieldDecl *CXXThisFieldDecl;
241 CGCapturedStmtInfo *CapturedStmtInfo;
243 /// BoundsChecking - Emit run-time bounds checks. Higher values mean
244 /// potentially higher performance penalties.
245 unsigned char BoundsChecking;
247 /// \brief Sanitizer options to use for this function.
248 const SanitizerOptions *SanOpts;
250 /// \brief True if CodeGen currently emits code implementing sanitizer checks.
251 bool IsSanitizerScope;
253 /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope.
254 class SanitizerScope {
255 CodeGenFunction *CGF;
257 SanitizerScope(CodeGenFunction *CGF);
261 /// In ARC, whether we should autorelease the return value.
262 bool AutoreleaseResult;
264 const CodeGen::CGBlockInfo *BlockInfo;
265 llvm::Value *BlockPointer;
267 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
268 FieldDecl *LambdaThisCaptureField;
270 /// \brief A mapping from NRVO variables to the flags used to indicate
271 /// when the NRVO has been applied to this variable.
272 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
274 EHScopeStack EHStack;
275 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
277 /// Header for data within LifetimeExtendedCleanupStack.
278 struct LifetimeExtendedCleanupHeader {
279 /// The size of the following cleanup object.
281 /// The kind of cleanup to push: a value from the CleanupKind enumeration.
284 size_t getSize() const { return Size; }
285 CleanupKind getKind() const { return static_cast<CleanupKind>(Kind); }
288 /// i32s containing the indexes of the cleanup destinations.
289 llvm::AllocaInst *NormalCleanupDest;
291 unsigned NextCleanupDestIndex;
293 /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
294 CGBlockInfo *FirstBlockInfo;
296 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
297 llvm::BasicBlock *EHResumeBlock;
299 /// The exception slot. All landing pads write the current exception pointer
300 /// into this alloca.
301 llvm::Value *ExceptionSlot;
303 /// The selector slot. Under the MandatoryCleanup model, all landing pads
304 /// write the current selector value into this alloca.
305 llvm::AllocaInst *EHSelectorSlot;
307 /// Emits a landing pad for the current EH stack.
308 llvm::BasicBlock *EmitLandingPad();
310 llvm::BasicBlock *getInvokeDestImpl();
313 typename DominatingValue<T>::saved_type saveValueInCond(T value) {
314 return DominatingValue<T>::save(*this, value);
318 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
320 SmallVector<llvm::Value*, 8> ObjCEHValueStack;
322 /// A class controlling the emission of a finally block.
324 /// Where the catchall's edge through the cleanup should go.
325 JumpDest RethrowDest;
327 /// A function to call to enter the catch.
328 llvm::Constant *BeginCatchFn;
330 /// An i1 variable indicating whether or not the @finally is
331 /// running for an exception.
332 llvm::AllocaInst *ForEHVar;
334 /// An i8* variable into which the exception pointer to rethrow
336 llvm::AllocaInst *SavedExnVar;
339 void enter(CodeGenFunction &CGF, const Stmt *Finally,
340 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
341 llvm::Constant *rethrowFn);
342 void exit(CodeGenFunction &CGF);
345 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
346 /// current full-expression. Safe against the possibility that
347 /// we're currently inside a conditionally-evaluated expression.
348 template <class T, class A0>
349 void pushFullExprCleanup(CleanupKind kind, A0 a0) {
350 // If we're not in a conditional branch, or if none of the
351 // arguments requires saving, then use the unconditional cleanup.
352 if (!isInConditionalBranch())
353 return EHStack.pushCleanup<T>(kind, a0);
355 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
357 typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType;
358 EHStack.pushCleanup<CleanupType>(kind, a0_saved);
359 initFullExprCleanup();
362 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
363 /// current full-expression. Safe against the possibility that
364 /// we're currently inside a conditionally-evaluated expression.
365 template <class T, class A0, class A1>
366 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) {
367 // If we're not in a conditional branch, or if none of the
368 // arguments requires saving, then use the unconditional cleanup.
369 if (!isInConditionalBranch())
370 return EHStack.pushCleanup<T>(kind, a0, a1);
372 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
373 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
375 typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType;
376 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved);
377 initFullExprCleanup();
380 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
381 /// current full-expression. Safe against the possibility that
382 /// we're currently inside a conditionally-evaluated expression.
383 template <class T, class A0, class A1, class A2>
384 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2) {
385 // If we're not in a conditional branch, or if none of the
386 // arguments requires saving, then use the unconditional cleanup.
387 if (!isInConditionalBranch()) {
388 return EHStack.pushCleanup<T>(kind, a0, a1, a2);
391 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
392 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
393 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2);
395 typedef EHScopeStack::ConditionalCleanup3<T, A0, A1, A2> CleanupType;
396 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, a2_saved);
397 initFullExprCleanup();
400 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
401 /// current full-expression. Safe against the possibility that
402 /// we're currently inside a conditionally-evaluated expression.
403 template <class T, class A0, class A1, class A2, class A3>
404 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2, A3 a3) {
405 // If we're not in a conditional branch, or if none of the
406 // arguments requires saving, then use the unconditional cleanup.
407 if (!isInConditionalBranch()) {
408 return EHStack.pushCleanup<T>(kind, a0, a1, a2, a3);
411 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
412 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
413 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2);
414 typename DominatingValue<A3>::saved_type a3_saved = saveValueInCond(a3);
416 typedef EHScopeStack::ConditionalCleanup4<T, A0, A1, A2, A3> CleanupType;
417 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved,
419 initFullExprCleanup();
422 /// \brief Queue a cleanup to be pushed after finishing the current
424 template <class T, class A0, class A1, class A2, class A3>
425 void pushCleanupAfterFullExpr(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
426 assert(!isInConditionalBranch() && "can't defer conditional cleanup");
428 LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
430 size_t OldSize = LifetimeExtendedCleanupStack.size();
431 LifetimeExtendedCleanupStack.resize(
432 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
434 char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
435 new (Buffer) LifetimeExtendedCleanupHeader(Header);
436 new (Buffer + sizeof(Header)) T(a0, a1, a2, a3);
439 /// Set up the last cleaup that was pushed as a conditional
440 /// full-expression cleanup.
441 void initFullExprCleanup();
443 /// PushDestructorCleanup - Push a cleanup to call the
444 /// complete-object destructor of an object of the given type at the
445 /// given address. Does nothing if T is not a C++ class type with a
446 /// non-trivial destructor.
447 void PushDestructorCleanup(QualType T, llvm::Value *Addr);
449 /// PushDestructorCleanup - Push a cleanup to call the
450 /// complete-object variant of the given destructor on the object at
451 /// the given address.
452 void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
455 /// PopCleanupBlock - Will pop the cleanup entry on the stack and
456 /// process all branch fixups.
457 void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
459 /// DeactivateCleanupBlock - Deactivates the given cleanup block.
460 /// The block cannot be reactivated. Pops it if it's the top of the
463 /// \param DominatingIP - An instruction which is known to
464 /// dominate the current IP (if set) and which lies along
465 /// all paths of execution between the current IP and the
466 /// the point at which the cleanup comes into scope.
467 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
468 llvm::Instruction *DominatingIP);
470 /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
471 /// Cannot be used to resurrect a deactivated cleanup.
473 /// \param DominatingIP - An instruction which is known to
474 /// dominate the current IP (if set) and which lies along
475 /// all paths of execution between the current IP and the
476 /// the point at which the cleanup comes into scope.
477 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
478 llvm::Instruction *DominatingIP);
480 /// \brief Enters a new scope for capturing cleanups, all of which
481 /// will be executed once the scope is exited.
482 class RunCleanupsScope {
483 EHScopeStack::stable_iterator CleanupStackDepth;
484 size_t LifetimeExtendedCleanupStackSize;
485 bool OldDidCallStackSave;
490 RunCleanupsScope(const RunCleanupsScope &) LLVM_DELETED_FUNCTION;
491 void operator=(const RunCleanupsScope &) LLVM_DELETED_FUNCTION;
494 CodeGenFunction& CGF;
497 /// \brief Enter a new cleanup scope.
498 explicit RunCleanupsScope(CodeGenFunction &CGF)
499 : PerformCleanup(true), CGF(CGF)
501 CleanupStackDepth = CGF.EHStack.stable_begin();
502 LifetimeExtendedCleanupStackSize =
503 CGF.LifetimeExtendedCleanupStack.size();
504 OldDidCallStackSave = CGF.DidCallStackSave;
505 CGF.DidCallStackSave = false;
508 /// \brief Exit this cleanup scope, emitting any accumulated
510 ~RunCleanupsScope() {
511 if (PerformCleanup) {
512 CGF.DidCallStackSave = OldDidCallStackSave;
513 CGF.PopCleanupBlocks(CleanupStackDepth,
514 LifetimeExtendedCleanupStackSize);
518 /// \brief Determine whether this scope requires any cleanups.
519 bool requiresCleanups() const {
520 return CGF.EHStack.stable_begin() != CleanupStackDepth;
523 /// \brief Force the emission of cleanups now, instead of waiting
524 /// until this object is destroyed.
525 void ForceCleanup() {
526 assert(PerformCleanup && "Already forced cleanup");
527 CGF.DidCallStackSave = OldDidCallStackSave;
528 CGF.PopCleanupBlocks(CleanupStackDepth,
529 LifetimeExtendedCleanupStackSize);
530 PerformCleanup = false;
534 class LexicalScope: protected RunCleanupsScope {
536 SmallVector<const LabelDecl*, 4> Labels;
537 LexicalScope *ParentScope;
539 LexicalScope(const LexicalScope &) LLVM_DELETED_FUNCTION;
540 void operator=(const LexicalScope &) LLVM_DELETED_FUNCTION;
543 /// \brief Enter a new cleanup scope.
544 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
545 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
546 CGF.CurLexicalScope = this;
547 if (CGDebugInfo *DI = CGF.getDebugInfo())
548 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
551 void addLabel(const LabelDecl *label) {
552 assert(PerformCleanup && "adding label to dead scope?");
553 Labels.push_back(label);
556 /// \brief Exit this cleanup scope, emitting any accumulated
559 if (CGDebugInfo *DI = CGF.getDebugInfo())
560 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
562 // If we should perform a cleanup, force them now. Note that
563 // this ends the cleanup scope before rescoping any labels.
564 if (PerformCleanup) ForceCleanup();
567 /// \brief Force the emission of cleanups now, instead of waiting
568 /// until this object is destroyed.
569 void ForceCleanup() {
570 CGF.CurLexicalScope = ParentScope;
571 RunCleanupsScope::ForceCleanup();
577 void rescopeLabels();
581 /// \brief Takes the old cleanup stack size and emits the cleanup blocks
582 /// that have been added.
583 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
585 /// \brief Takes the old cleanup stack size and emits the cleanup blocks
586 /// that have been added, then adds all lifetime-extended cleanups from
587 /// the given position to the stack.
588 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
589 size_t OldLifetimeExtendedStackSize);
591 void ResolveBranchFixups(llvm::BasicBlock *Target);
593 /// The given basic block lies in the current EH scope, but may be a
594 /// target of a potentially scope-crossing jump; get a stable handle
595 /// to which we can perform this jump later.
596 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
597 return JumpDest(Target,
598 EHStack.getInnermostNormalCleanup(),
599 NextCleanupDestIndex++);
602 /// The given basic block lies in the current EH scope, but may be a
603 /// target of a potentially scope-crossing jump; get a stable handle
604 /// to which we can perform this jump later.
605 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
606 return getJumpDestInCurrentScope(createBasicBlock(Name));
609 /// EmitBranchThroughCleanup - Emit a branch from the current insert
610 /// block through the normal cleanup handling code (if any) and then
612 void EmitBranchThroughCleanup(JumpDest Dest);
614 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
615 /// specified destination obviously has no cleanups to run. 'false' is always
616 /// a conservatively correct answer for this method.
617 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
619 /// popCatchScope - Pops the catch scope at the top of the EHScope
620 /// stack, emitting any required code (other than the catch handlers
622 void popCatchScope();
624 llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
625 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
627 /// An object to manage conditionally-evaluated expressions.
628 class ConditionalEvaluation {
629 llvm::BasicBlock *StartBB;
632 ConditionalEvaluation(CodeGenFunction &CGF)
633 : StartBB(CGF.Builder.GetInsertBlock()) {}
635 void begin(CodeGenFunction &CGF) {
636 assert(CGF.OutermostConditional != this);
637 if (!CGF.OutermostConditional)
638 CGF.OutermostConditional = this;
641 void end(CodeGenFunction &CGF) {
642 assert(CGF.OutermostConditional != nullptr);
643 if (CGF.OutermostConditional == this)
644 CGF.OutermostConditional = nullptr;
647 /// Returns a block which will be executed prior to each
648 /// evaluation of the conditional code.
649 llvm::BasicBlock *getStartingBlock() const {
654 /// isInConditionalBranch - Return true if we're currently emitting
655 /// one branch or the other of a conditional expression.
656 bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
658 void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr) {
659 assert(isInConditionalBranch());
660 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
661 new llvm::StoreInst(value, addr, &block->back());
664 /// An RAII object to record that we're evaluating a statement
666 class StmtExprEvaluation {
667 CodeGenFunction &CGF;
669 /// We have to save the outermost conditional: cleanups in a
670 /// statement expression aren't conditional just because the
672 ConditionalEvaluation *SavedOutermostConditional;
675 StmtExprEvaluation(CodeGenFunction &CGF)
676 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
677 CGF.OutermostConditional = nullptr;
680 ~StmtExprEvaluation() {
681 CGF.OutermostConditional = SavedOutermostConditional;
682 CGF.EnsureInsertPoint();
686 /// An object which temporarily prevents a value from being
687 /// destroyed by aggressive peephole optimizations that assume that
688 /// all uses of a value have been realized in the IR.
689 class PeepholeProtection {
690 llvm::Instruction *Inst;
691 friend class CodeGenFunction;
694 PeepholeProtection() : Inst(nullptr) {}
697 /// A non-RAII class containing all the information about a bound
698 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
699 /// this which makes individual mappings very simple; using this
700 /// class directly is useful when you have a variable number of
701 /// opaque values or don't want the RAII functionality for some
703 class OpaqueValueMappingData {
704 const OpaqueValueExpr *OpaqueValue;
706 CodeGenFunction::PeepholeProtection Protection;
708 OpaqueValueMappingData(const OpaqueValueExpr *ov,
710 : OpaqueValue(ov), BoundLValue(boundLValue) {}
712 OpaqueValueMappingData() : OpaqueValue(nullptr) {}
714 static bool shouldBindAsLValue(const Expr *expr) {
715 // gl-values should be bound as l-values for obvious reasons.
716 // Records should be bound as l-values because IR generation
717 // always keeps them in memory. Expressions of function type
718 // act exactly like l-values but are formally required to be
720 return expr->isGLValue() ||
721 expr->getType()->isFunctionType() ||
722 hasAggregateEvaluationKind(expr->getType());
725 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
726 const OpaqueValueExpr *ov,
728 if (shouldBindAsLValue(ov))
729 return bind(CGF, ov, CGF.EmitLValue(e));
730 return bind(CGF, ov, CGF.EmitAnyExpr(e));
733 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
734 const OpaqueValueExpr *ov,
736 assert(shouldBindAsLValue(ov));
737 CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
738 return OpaqueValueMappingData(ov, true);
741 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
742 const OpaqueValueExpr *ov,
744 assert(!shouldBindAsLValue(ov));
745 CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
747 OpaqueValueMappingData data(ov, false);
749 // Work around an extremely aggressive peephole optimization in
750 // EmitScalarConversion which assumes that all other uses of a
752 data.Protection = CGF.protectFromPeepholes(rv);
757 bool isValid() const { return OpaqueValue != nullptr; }
758 void clear() { OpaqueValue = nullptr; }
760 void unbind(CodeGenFunction &CGF) {
761 assert(OpaqueValue && "no data to unbind!");
764 CGF.OpaqueLValues.erase(OpaqueValue);
766 CGF.OpaqueRValues.erase(OpaqueValue);
767 CGF.unprotectFromPeepholes(Protection);
772 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
773 class OpaqueValueMapping {
774 CodeGenFunction &CGF;
775 OpaqueValueMappingData Data;
778 static bool shouldBindAsLValue(const Expr *expr) {
779 return OpaqueValueMappingData::shouldBindAsLValue(expr);
782 /// Build the opaque value mapping for the given conditional
783 /// operator if it's the GNU ?: extension. This is a common
784 /// enough pattern that the convenience operator is really
787 OpaqueValueMapping(CodeGenFunction &CGF,
788 const AbstractConditionalOperator *op) : CGF(CGF) {
789 if (isa<ConditionalOperator>(op))
793 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
794 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
798 OpaqueValueMapping(CodeGenFunction &CGF,
799 const OpaqueValueExpr *opaqueValue,
801 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
804 OpaqueValueMapping(CodeGenFunction &CGF,
805 const OpaqueValueExpr *opaqueValue,
807 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
815 ~OpaqueValueMapping() {
816 if (Data.isValid()) Data.unbind(CGF);
820 /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
821 /// number that holds the value.
822 unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
824 /// BuildBlockByrefAddress - Computes address location of the
825 /// variable which is declared as __block.
826 llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr,
829 CGDebugInfo *DebugInfo;
830 bool DisableDebugInfo;
832 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
833 /// calling llvm.stacksave for multiple VLAs in the same scope.
834 bool DidCallStackSave;
836 /// IndirectBranch - The first time an indirect goto is seen we create a block
837 /// with an indirect branch. Every time we see the address of a label taken,
838 /// we add the label to the indirect goto. Every subsequent indirect goto is
839 /// codegen'd as a jump to the IndirectBranch's basic block.
840 llvm::IndirectBrInst *IndirectBranch;
842 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
844 typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy;
845 DeclMapTy LocalDeclMap;
847 /// LabelMap - This keeps track of the LLVM basic block for each C label.
848 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
850 // BreakContinueStack - This keeps track of where break and continue
851 // statements should jump to.
852 struct BreakContinue {
853 BreakContinue(JumpDest Break, JumpDest Continue)
854 : BreakBlock(Break), ContinueBlock(Continue) {}
857 JumpDest ContinueBlock;
859 SmallVector<BreakContinue, 8> BreakContinueStack;
864 /// Get a counter for instrumentation of the region associated with the given
866 RegionCounter getPGORegionCounter(const Stmt *S) {
867 return RegionCounter(PGO, S);
871 /// SwitchInsn - This is nearest current switch instruction. It is null if
872 /// current context is not in a switch.
873 llvm::SwitchInst *SwitchInsn;
874 /// The branch weights of SwitchInsn when doing instrumentation based PGO.
875 SmallVector<uint64_t, 16> *SwitchWeights;
877 /// CaseRangeBlock - This block holds if condition check for last case
878 /// statement range in current switch instruction.
879 llvm::BasicBlock *CaseRangeBlock;
881 /// OpaqueLValues - Keeps track of the current set of opaque value
883 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
884 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
886 // VLASizeMap - This keeps track of the associated size for each VLA type.
887 // We track this by the size expression rather than the type itself because
888 // in certain situations, like a const qualifier applied to an VLA typedef,
889 // multiple VLA types can share the same size expression.
890 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
891 // enter/leave scopes.
892 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
894 /// A block containing a single 'unreachable' instruction. Created
895 /// lazily by getUnreachableBlock().
896 llvm::BasicBlock *UnreachableBlock;
898 /// Counts of the number return expressions in the function.
899 unsigned NumReturnExprs;
901 /// Count the number of simple (constant) return expressions in the function.
902 unsigned NumSimpleReturnExprs;
904 /// The last regular (non-return) debug location (breakpoint) in the function.
905 SourceLocation LastStopPoint;
908 /// A scope within which we are constructing the fields of an object which
909 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
910 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
911 class FieldConstructionScope {
913 FieldConstructionScope(CodeGenFunction &CGF, llvm::Value *This)
914 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
915 CGF.CXXDefaultInitExprThis = This;
917 ~FieldConstructionScope() {
918 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
922 CodeGenFunction &CGF;
923 llvm::Value *OldCXXDefaultInitExprThis;
926 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
927 /// is overridden to be the object under construction.
928 class CXXDefaultInitExprScope {
930 CXXDefaultInitExprScope(CodeGenFunction &CGF)
931 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue) {
932 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis;
934 ~CXXDefaultInitExprScope() {
935 CGF.CXXThisValue = OldCXXThisValue;
939 CodeGenFunction &CGF;
940 llvm::Value *OldCXXThisValue;
944 /// CXXThisDecl - When generating code for a C++ member function,
945 /// this will hold the implicit 'this' declaration.
946 ImplicitParamDecl *CXXABIThisDecl;
947 llvm::Value *CXXABIThisValue;
948 llvm::Value *CXXThisValue;
950 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
952 llvm::Value *CXXDefaultInitExprThis;
954 /// CXXStructorImplicitParamDecl - When generating code for a constructor or
955 /// destructor, this will hold the implicit argument (e.g. VTT).
956 ImplicitParamDecl *CXXStructorImplicitParamDecl;
957 llvm::Value *CXXStructorImplicitParamValue;
959 /// OutermostConditional - Points to the outermost active
960 /// conditional control. This is used so that we know if a
961 /// temporary should be destroyed conditionally.
962 ConditionalEvaluation *OutermostConditional;
964 /// The current lexical scope.
965 LexicalScope *CurLexicalScope;
967 /// The current source location that should be used for exception
969 SourceLocation CurEHLocation;
971 /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
972 /// type as well as the field number that contains the actual data.
973 llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *,
974 unsigned> > ByRefValueInfo;
976 llvm::BasicBlock *TerminateLandingPad;
977 llvm::BasicBlock *TerminateHandler;
978 llvm::BasicBlock *TrapBB;
980 /// Add a kernel metadata node to the named metadata node 'opencl.kernels'.
981 /// In the kernel metadata node, reference the kernel function and metadata
982 /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2):
983 /// - A node for the vec_type_hint(<type>) qualifier contains string
984 /// "vec_type_hint", an undefined value of the <type> data type,
985 /// and a Boolean that is true if the <type> is integer and signed.
986 /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string
987 /// "work_group_size_hint", and three 32-bit integers X, Y and Z.
988 /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string
989 /// "reqd_work_group_size", and three 32-bit integers X, Y and Z.
990 void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
994 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
997 CodeGenTypes &getTypes() const { return CGM.getTypes(); }
998 ASTContext &getContext() const { return CGM.getContext(); }
999 CGDebugInfo *getDebugInfo() {
1000 if (DisableDebugInfo)
1004 void disableDebugInfo() { DisableDebugInfo = true; }
1005 void enableDebugInfo() { DisableDebugInfo = false; }
1007 bool shouldUseFusedARCCalls() {
1008 return CGM.getCodeGenOpts().OptimizationLevel == 0;
1011 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
1013 /// Returns a pointer to the function's exception object and selector slot,
1014 /// which is assigned in every landing pad.
1015 llvm::Value *getExceptionSlot();
1016 llvm::Value *getEHSelectorSlot();
1018 /// Returns the contents of the function's exception object and selector
1020 llvm::Value *getExceptionFromSlot();
1021 llvm::Value *getSelectorFromSlot();
1023 llvm::Value *getNormalCleanupDestSlot();
1025 llvm::BasicBlock *getUnreachableBlock() {
1026 if (!UnreachableBlock) {
1027 UnreachableBlock = createBasicBlock("unreachable");
1028 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
1030 return UnreachableBlock;
1033 llvm::BasicBlock *getInvokeDest() {
1034 if (!EHStack.requiresLandingPad()) return nullptr;
1035 return getInvokeDestImpl();
1038 const TargetInfo &getTarget() const { return Target; }
1039 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
1041 //===--------------------------------------------------------------------===//
1043 //===--------------------------------------------------------------------===//
1045 typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty);
1047 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1048 llvm::Value *arrayEndPointer,
1049 QualType elementType,
1050 Destroyer *destroyer);
1051 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1052 llvm::Value *arrayEnd,
1053 QualType elementType,
1054 Destroyer *destroyer);
1056 void pushDestroy(QualType::DestructionKind dtorKind,
1057 llvm::Value *addr, QualType type);
1058 void pushEHDestroy(QualType::DestructionKind dtorKind,
1059 llvm::Value *addr, QualType type);
1060 void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type,
1061 Destroyer *destroyer, bool useEHCleanupForArray);
1062 void pushLifetimeExtendedDestroy(CleanupKind kind, llvm::Value *addr,
1063 QualType type, Destroyer *destroyer,
1064 bool useEHCleanupForArray);
1065 void pushStackRestore(CleanupKind kind, llvm::Value *SPMem);
1066 void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer,
1067 bool useEHCleanupForArray);
1068 llvm::Function *generateDestroyHelper(llvm::Constant *addr, QualType type,
1069 Destroyer *destroyer,
1070 bool useEHCleanupForArray,
1072 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
1073 QualType type, Destroyer *destroyer,
1074 bool checkZeroLength, bool useEHCleanup);
1076 Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
1078 /// Determines whether an EH cleanup is required to destroy a type
1079 /// with the given destruction kind.
1080 bool needsEHCleanup(QualType::DestructionKind kind) {
1082 case QualType::DK_none:
1084 case QualType::DK_cxx_destructor:
1085 case QualType::DK_objc_weak_lifetime:
1086 return getLangOpts().Exceptions;
1087 case QualType::DK_objc_strong_lifetime:
1088 return getLangOpts().Exceptions &&
1089 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1091 llvm_unreachable("bad destruction kind");
1094 CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1095 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1098 //===--------------------------------------------------------------------===//
1100 //===--------------------------------------------------------------------===//
1102 void GenerateObjCMethod(const ObjCMethodDecl *OMD);
1104 void StartObjCMethod(const ObjCMethodDecl *MD,
1105 const ObjCContainerDecl *CD,
1106 SourceLocation StartLoc);
1108 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
1109 void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1110 const ObjCPropertyImplDecl *PID);
1111 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1112 const ObjCPropertyImplDecl *propImpl,
1113 const ObjCMethodDecl *GetterMothodDecl,
1114 llvm::Constant *AtomicHelperFn);
1116 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1117 ObjCMethodDecl *MD, bool ctor);
1119 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1120 /// for the given property.
1121 void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1122 const ObjCPropertyImplDecl *PID);
1123 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1124 const ObjCPropertyImplDecl *propImpl,
1125 llvm::Constant *AtomicHelperFn);
1126 bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
1127 bool IvarTypeWithAggrGCObjects(QualType Ty);
1129 //===--------------------------------------------------------------------===//
1131 //===--------------------------------------------------------------------===//
1133 llvm::Value *EmitBlockLiteral(const BlockExpr *);
1134 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
1135 static void destroyBlockInfos(CGBlockInfo *info);
1136 llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
1137 const CGBlockInfo &Info,
1139 llvm::Constant *BlockVarLayout);
1141 llvm::Function *GenerateBlockFunction(GlobalDecl GD,
1142 const CGBlockInfo &Info,
1143 const DeclMapTy &ldm,
1144 bool IsLambdaConversionToBlock);
1146 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1147 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
1148 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
1149 const ObjCPropertyImplDecl *PID);
1150 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
1151 const ObjCPropertyImplDecl *PID);
1152 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
1154 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
1156 class AutoVarEmission;
1158 void emitByrefStructureInit(const AutoVarEmission &emission);
1159 void enterByrefCleanup(const AutoVarEmission &emission);
1161 llvm::Value *LoadBlockStruct() {
1162 assert(BlockPointer && "no block pointer set!");
1163 return BlockPointer;
1166 void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
1167 void AllocateBlockDecl(const DeclRefExpr *E);
1168 llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
1169 llvm::Type *BuildByRefType(const VarDecl *var);
1171 void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1172 const CGFunctionInfo &FnInfo);
1173 /// \brief Emit code for the start of a function.
1174 /// \param Loc The location to be associated with the function.
1175 /// \param StartLoc The location of the function body.
1176 void StartFunction(GlobalDecl GD,
1179 const CGFunctionInfo &FnInfo,
1180 const FunctionArgList &Args,
1181 SourceLocation Loc = SourceLocation(),
1182 SourceLocation StartLoc = SourceLocation());
1184 void EmitConstructorBody(FunctionArgList &Args);
1185 void EmitDestructorBody(FunctionArgList &Args);
1186 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
1187 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
1188 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, RegionCounter &Cnt);
1190 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
1191 CallArgList &CallArgs);
1192 void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
1193 void EmitLambdaBlockInvokeBody();
1194 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
1195 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
1197 /// EmitReturnBlock - Emit the unified return block, trying to avoid its
1198 /// emission when possible.
1199 void EmitReturnBlock();
1201 /// FinishFunction - Complete IR generation of the current function. It is
1202 /// legal to call this function even if there is no current insertion point.
1203 void FinishFunction(SourceLocation EndLoc=SourceLocation());
1205 void StartThunk(llvm::Function *Fn, GlobalDecl GD, const CGFunctionInfo &FnInfo);
1207 void EmitCallAndReturnForThunk(GlobalDecl GD, llvm::Value *Callee,
1208 const ThunkInfo *Thunk);
1210 /// GenerateThunk - Generate a thunk for the given method.
1211 void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1212 GlobalDecl GD, const ThunkInfo &Thunk);
1214 void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1215 GlobalDecl GD, const ThunkInfo &Thunk);
1217 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1218 FunctionArgList &Args);
1220 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init,
1221 ArrayRef<VarDecl *> ArrayIndexes);
1223 /// InitializeVTablePointer - Initialize the vtable pointer of the given
1226 void InitializeVTablePointer(BaseSubobject Base,
1227 const CXXRecordDecl *NearestVBase,
1228 CharUnits OffsetFromNearestVBase,
1229 const CXXRecordDecl *VTableClass);
1231 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1232 void InitializeVTablePointers(BaseSubobject Base,
1233 const CXXRecordDecl *NearestVBase,
1234 CharUnits OffsetFromNearestVBase,
1235 bool BaseIsNonVirtualPrimaryBase,
1236 const CXXRecordDecl *VTableClass,
1237 VisitedVirtualBasesSetTy& VBases);
1239 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1241 /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1243 llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty);
1246 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
1247 /// expr can be devirtualized.
1248 bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
1249 const CXXMethodDecl *MD);
1251 /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1252 /// given phase of destruction for a destructor. The end result
1253 /// should call destructors on members and base classes in reverse
1254 /// order of their construction.
1255 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1257 /// ShouldInstrumentFunction - Return true if the current function should be
1258 /// instrumented with __cyg_profile_func_* calls
1259 bool ShouldInstrumentFunction();
1261 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
1262 /// instrumentation function with the current function and the call site, if
1263 /// function instrumentation is enabled.
1264 void EmitFunctionInstrumentation(const char *Fn);
1266 /// EmitMCountInstrumentation - Emit call to .mcount.
1267 void EmitMCountInstrumentation();
1269 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
1270 /// arguments for the given function. This is also responsible for naming the
1271 /// LLVM function arguments.
1272 void EmitFunctionProlog(const CGFunctionInfo &FI,
1274 const FunctionArgList &Args);
1276 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
1277 /// given temporary.
1278 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
1279 SourceLocation EndLoc);
1281 /// EmitStartEHSpec - Emit the start of the exception spec.
1282 void EmitStartEHSpec(const Decl *D);
1284 /// EmitEndEHSpec - Emit the end of the exception spec.
1285 void EmitEndEHSpec(const Decl *D);
1287 /// getTerminateLandingPad - Return a landing pad that just calls terminate.
1288 llvm::BasicBlock *getTerminateLandingPad();
1290 /// getTerminateHandler - Return a handler (not a landing pad, just
1291 /// a catch handler) that just calls terminate. This is used when
1292 /// a terminate scope encloses a try.
1293 llvm::BasicBlock *getTerminateHandler();
1295 llvm::Type *ConvertTypeForMem(QualType T);
1296 llvm::Type *ConvertType(QualType T);
1297 llvm::Type *ConvertType(const TypeDecl *T) {
1298 return ConvertType(getContext().getTypeDeclType(T));
1301 /// LoadObjCSelf - Load the value of self. This function is only valid while
1302 /// generating code for an Objective-C method.
1303 llvm::Value *LoadObjCSelf();
1305 /// TypeOfSelfObject - Return type of object that this self represents.
1306 QualType TypeOfSelfObject();
1308 /// hasAggregateLLVMType - Return true if the specified AST type will map into
1309 /// an aggregate LLVM type or is void.
1310 static TypeEvaluationKind getEvaluationKind(QualType T);
1312 static bool hasScalarEvaluationKind(QualType T) {
1313 return getEvaluationKind(T) == TEK_Scalar;
1316 static bool hasAggregateEvaluationKind(QualType T) {
1317 return getEvaluationKind(T) == TEK_Aggregate;
1320 /// createBasicBlock - Create an LLVM basic block.
1321 llvm::BasicBlock *createBasicBlock(const Twine &name = "",
1322 llvm::Function *parent = nullptr,
1323 llvm::BasicBlock *before = nullptr) {
1325 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
1327 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
1331 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
1333 JumpDest getJumpDestForLabel(const LabelDecl *S);
1335 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
1336 /// another basic block, simplify it. This assumes that no other code could
1337 /// potentially reference the basic block.
1338 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
1340 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
1341 /// adding a fall-through branch from the current insert block if
1342 /// necessary. It is legal to call this function even if there is no current
1343 /// insertion point.
1345 /// IsFinished - If true, indicates that the caller has finished emitting
1346 /// branches to the given block and does not expect to emit code into it. This
1347 /// means the block can be ignored if it is unreachable.
1348 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
1350 /// EmitBlockAfterUses - Emit the given block somewhere hopefully
1351 /// near its uses, and leave the insertion point in it.
1352 void EmitBlockAfterUses(llvm::BasicBlock *BB);
1354 /// EmitBranch - Emit a branch to the specified basic block from the current
1355 /// insert block, taking care to avoid creation of branches from dummy
1356 /// blocks. It is legal to call this function even if there is no current
1357 /// insertion point.
1359 /// This function clears the current insertion point. The caller should follow
1360 /// calls to this function with calls to Emit*Block prior to generation new
1362 void EmitBranch(llvm::BasicBlock *Block);
1364 /// HaveInsertPoint - True if an insertion point is defined. If not, this
1365 /// indicates that the current code being emitted is unreachable.
1366 bool HaveInsertPoint() const {
1367 return Builder.GetInsertBlock() != nullptr;
1370 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
1371 /// emitted IR has a place to go. Note that by definition, if this function
1372 /// creates a block then that block is unreachable; callers may do better to
1373 /// detect when no insertion point is defined and simply skip IR generation.
1374 void EnsureInsertPoint() {
1375 if (!HaveInsertPoint())
1376 EmitBlock(createBasicBlock());
1379 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1380 /// specified stmt yet.
1381 void ErrorUnsupported(const Stmt *S, const char *Type);
1383 //===--------------------------------------------------------------------===//
1385 //===--------------------------------------------------------------------===//
1387 LValue MakeAddrLValue(llvm::Value *V, QualType T,
1388 CharUnits Alignment = CharUnits()) {
1389 return LValue::MakeAddr(V, T, Alignment, getContext(),
1390 CGM.getTBAAInfo(T));
1393 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
1394 CharUnits Alignment;
1395 if (!T->isIncompleteType())
1396 Alignment = getContext().getTypeAlignInChars(T);
1397 return LValue::MakeAddr(V, T, Alignment, getContext(),
1398 CGM.getTBAAInfo(T));
1401 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
1402 /// block. The caller is responsible for setting an appropriate alignment on
1404 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
1405 const Twine &Name = "tmp");
1407 /// InitTempAlloca - Provide an initial value for the given alloca.
1408 void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
1410 /// CreateIRTemp - Create a temporary IR object of the given type, with
1411 /// appropriate alignment. This routine should only be used when an temporary
1412 /// value needs to be stored into an alloca (for example, to avoid explicit
1413 /// PHI construction), but the type is the IR type, not the type appropriate
1414 /// for storing in memory.
1415 llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp");
1417 /// CreateMemTemp - Create a temporary memory object of the given type, with
1418 /// appropriate alignment.
1419 llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp");
1421 /// CreateAggTemp - Create a temporary memory object for the given
1423 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
1424 CharUnits Alignment = getContext().getTypeAlignInChars(T);
1425 return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment,
1427 AggValueSlot::IsNotDestructed,
1428 AggValueSlot::DoesNotNeedGCBarriers,
1429 AggValueSlot::IsNotAliased);
1432 /// CreateInAllocaTmp - Create a temporary memory object for the given
1434 AggValueSlot CreateInAllocaTmp(QualType T, const Twine &Name = "inalloca");
1436 /// Emit a cast to void* in the appropriate address space.
1437 llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
1439 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1440 /// expression and compare the result against zero, returning an Int1Ty value.
1441 llvm::Value *EvaluateExprAsBool(const Expr *E);
1443 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1444 void EmitIgnoredExpr(const Expr *E);
1446 /// EmitAnyExpr - Emit code to compute the specified expression which can have
1447 /// any type. The result is returned as an RValue struct. If this is an
1448 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1449 /// the result should be returned.
1451 /// \param ignoreResult True if the resulting value isn't used.
1452 RValue EmitAnyExpr(const Expr *E,
1453 AggValueSlot aggSlot = AggValueSlot::ignored(),
1454 bool ignoreResult = false);
1456 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1457 // or the value of the expression, depending on how va_list is defined.
1458 llvm::Value *EmitVAListRef(const Expr *E);
1460 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
1461 /// always be accessible even if no aggregate location is provided.
1462 RValue EmitAnyExprToTemp(const Expr *E);
1464 /// EmitAnyExprToMem - Emits the code necessary to evaluate an
1465 /// arbitrary expression into the given memory location.
1466 void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
1467 Qualifiers Quals, bool IsInitializer);
1469 /// EmitExprAsInit - Emits the code necessary to initialize a
1470 /// location in memory with the given initializer.
1471 void EmitExprAsInit(const Expr *init, const ValueDecl *D,
1472 LValue lvalue, bool capturedByInit);
1474 /// hasVolatileMember - returns true if aggregate type has a volatile
1476 bool hasVolatileMember(QualType T) {
1477 if (const RecordType *RT = T->getAs<RecordType>()) {
1478 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
1479 return RD->hasVolatileMember();
1483 /// EmitAggregateCopy - Emit an aggregate assignment.
1485 /// The difference to EmitAggregateCopy is that tail padding is not copied.
1486 /// This is required for correctness when assigning non-POD structures in C++.
1487 void EmitAggregateAssign(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1489 bool IsVolatile = hasVolatileMember(EltTy);
1490 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, CharUnits::Zero(),
1494 /// EmitAggregateCopy - Emit an aggregate copy.
1496 /// \param isVolatile - True iff either the source or the destination is
1498 /// \param isAssignment - If false, allow padding to be copied. This often
1499 /// yields more efficient.
1500 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1501 QualType EltTy, bool isVolatile=false,
1502 CharUnits Alignment = CharUnits::Zero(),
1503 bool isAssignment = false);
1505 /// StartBlock - Start new block named N. If insert block is a dummy block
1507 void StartBlock(const char *N);
1509 /// GetAddrOfLocalVar - Return the address of a local variable.
1510 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) {
1511 llvm::Value *Res = LocalDeclMap[VD];
1512 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
1516 /// getOpaqueLValueMapping - Given an opaque value expression (which
1517 /// must be mapped to an l-value), return its mapping.
1518 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
1519 assert(OpaqueValueMapping::shouldBindAsLValue(e));
1521 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
1522 it = OpaqueLValues.find(e);
1523 assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
1527 /// getOpaqueRValueMapping - Given an opaque value expression (which
1528 /// must be mapped to an r-value), return its mapping.
1529 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
1530 assert(!OpaqueValueMapping::shouldBindAsLValue(e));
1532 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
1533 it = OpaqueRValues.find(e);
1534 assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
1538 /// getAccessedFieldNo - Given an encoded value and a result number, return
1539 /// the input field number being accessed.
1540 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
1542 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
1543 llvm::BasicBlock *GetIndirectGotoBlock();
1545 /// EmitNullInitialization - Generate code to set a value of the given type to
1546 /// null, If the type contains data member pointers, they will be initialized
1547 /// to -1 in accordance with the Itanium C++ ABI.
1548 void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
1550 // EmitVAArg - Generate code to get an argument from the passed in pointer
1551 // and update it accordingly. The return value is a pointer to the argument.
1552 // FIXME: We should be able to get rid of this method and use the va_arg
1553 // instruction in LLVM instead once it works well enough.
1554 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
1556 /// emitArrayLength - Compute the length of an array, even if it's a
1557 /// VLA, and drill down to the base element type.
1558 llvm::Value *emitArrayLength(const ArrayType *arrayType,
1560 llvm::Value *&addr);
1562 /// EmitVLASize - Capture all the sizes for the VLA expressions in
1563 /// the given variably-modified type and store them in the VLASizeMap.
1565 /// This function can be called with a null (unreachable) insert point.
1566 void EmitVariablyModifiedType(QualType Ty);
1568 /// getVLASize - Returns an LLVM value that corresponds to the size,
1569 /// in non-variably-sized elements, of a variable length array type,
1570 /// plus that largest non-variably-sized element type. Assumes that
1571 /// the type has already been emitted with EmitVariablyModifiedType.
1572 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
1573 std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
1575 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
1576 /// generating code for an C++ member function.
1577 llvm::Value *LoadCXXThis() {
1578 assert(CXXThisValue && "no 'this' value for this function");
1579 return CXXThisValue;
1582 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
1584 // FIXME: Every place that calls LoadCXXVTT is something
1585 // that needs to be abstracted properly.
1586 llvm::Value *LoadCXXVTT() {
1587 assert(CXXStructorImplicitParamValue && "no VTT value for this function");
1588 return CXXStructorImplicitParamValue;
1591 /// LoadCXXStructorImplicitParam - Load the implicit parameter
1592 /// for a constructor/destructor.
1593 llvm::Value *LoadCXXStructorImplicitParam() {
1594 assert(CXXStructorImplicitParamValue &&
1595 "no implicit argument value for this function");
1596 return CXXStructorImplicitParamValue;
1599 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
1600 /// complete class to the given direct base.
1602 GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
1603 const CXXRecordDecl *Derived,
1604 const CXXRecordDecl *Base,
1605 bool BaseIsVirtual);
1607 /// GetAddressOfBaseClass - This function will add the necessary delta to the
1608 /// load of 'this' and returns address of the base class.
1609 llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
1610 const CXXRecordDecl *Derived,
1611 CastExpr::path_const_iterator PathBegin,
1612 CastExpr::path_const_iterator PathEnd,
1613 bool NullCheckValue);
1615 llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
1616 const CXXRecordDecl *Derived,
1617 CastExpr::path_const_iterator PathBegin,
1618 CastExpr::path_const_iterator PathEnd,
1619 bool NullCheckValue);
1621 /// GetVTTParameter - Return the VTT parameter that should be passed to a
1622 /// base constructor/destructor with virtual bases.
1623 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
1624 /// to ItaniumCXXABI.cpp together with all the references to VTT.
1625 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
1628 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1629 CXXCtorType CtorType,
1630 const FunctionArgList &Args,
1631 SourceLocation Loc);
1632 // It's important not to confuse this and the previous function. Delegating
1633 // constructors are the C++0x feature. The constructor delegate optimization
1634 // is used to reduce duplication in the base and complete consturctors where
1635 // they are substantially the same.
1636 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1637 const FunctionArgList &Args);
1638 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
1639 bool ForVirtualBase, bool Delegating,
1641 CallExpr::const_arg_iterator ArgBeg,
1642 CallExpr::const_arg_iterator ArgEnd);
1644 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1645 llvm::Value *This, llvm::Value *Src,
1646 CallExpr::const_arg_iterator ArgBeg,
1647 CallExpr::const_arg_iterator ArgEnd);
1649 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1650 const ConstantArrayType *ArrayTy,
1651 llvm::Value *ArrayPtr,
1652 CallExpr::const_arg_iterator ArgBeg,
1653 CallExpr::const_arg_iterator ArgEnd,
1654 bool ZeroInitialization = false);
1656 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1657 llvm::Value *NumElements,
1658 llvm::Value *ArrayPtr,
1659 CallExpr::const_arg_iterator ArgBeg,
1660 CallExpr::const_arg_iterator ArgEnd,
1661 bool ZeroInitialization = false);
1663 static Destroyer destroyCXXObject;
1665 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
1666 bool ForVirtualBase, bool Delegating,
1669 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
1670 llvm::Value *NewPtr, llvm::Value *NumElements,
1671 llvm::Value *AllocSizeWithoutCookie);
1673 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
1676 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
1677 void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
1679 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
1682 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1683 const Expr *Arg, bool IsDelete);
1685 llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
1686 llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
1687 llvm::Value* EmitCXXUuidofExpr(const CXXUuidofExpr *E);
1689 /// \brief Situations in which we might emit a check for the suitability of a
1690 /// pointer or glvalue.
1691 enum TypeCheckKind {
1692 /// Checking the operand of a load. Must be suitably sized and aligned.
1694 /// Checking the destination of a store. Must be suitably sized and aligned.
1696 /// Checking the bound value in a reference binding. Must be suitably sized
1697 /// and aligned, but is not required to refer to an object (until the
1698 /// reference is used), per core issue 453.
1699 TCK_ReferenceBinding,
1700 /// Checking the object expression in a non-static data member access. Must
1701 /// be an object within its lifetime.
1703 /// Checking the 'this' pointer for a call to a non-static member function.
1704 /// Must be an object within its lifetime.
1706 /// Checking the 'this' pointer for a constructor call.
1707 TCK_ConstructorCall,
1708 /// Checking the operand of a static_cast to a derived pointer type. Must be
1709 /// null or an object within its lifetime.
1710 TCK_DowncastPointer,
1711 /// Checking the operand of a static_cast to a derived reference type. Must
1712 /// be an object within its lifetime.
1713 TCK_DowncastReference
1716 /// \brief Whether any type-checking sanitizers are enabled. If \c false,
1717 /// calls to EmitTypeCheck can be skipped.
1718 bool sanitizePerformTypeCheck() const;
1720 /// \brief Emit a check that \p V is the address of storage of the
1721 /// appropriate size and alignment for an object of type \p Type.
1722 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
1723 QualType Type, CharUnits Alignment = CharUnits::Zero());
1725 /// \brief Emit a check that \p Base points into an array object, which
1726 /// we can access at index \p Index. \p Accessed should be \c false if we
1727 /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
1728 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
1729 QualType IndexType, bool Accessed);
1731 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1732 bool isInc, bool isPre);
1733 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
1734 bool isInc, bool isPre);
1735 //===--------------------------------------------------------------------===//
1736 // Declaration Emission
1737 //===--------------------------------------------------------------------===//
1739 /// EmitDecl - Emit a declaration.
1741 /// This function can be called with a null (unreachable) insert point.
1742 void EmitDecl(const Decl &D);
1744 /// EmitVarDecl - Emit a local variable declaration.
1746 /// This function can be called with a null (unreachable) insert point.
1747 void EmitVarDecl(const VarDecl &D);
1749 void EmitScalarInit(const Expr *init, const ValueDecl *D,
1750 LValue lvalue, bool capturedByInit);
1751 void EmitScalarInit(llvm::Value *init, LValue lvalue);
1753 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
1754 llvm::Value *Address);
1756 /// EmitAutoVarDecl - Emit an auto variable declaration.
1758 /// This function can be called with a null (unreachable) insert point.
1759 void EmitAutoVarDecl(const VarDecl &D);
1761 class AutoVarEmission {
1762 friend class CodeGenFunction;
1764 const VarDecl *Variable;
1766 /// The alignment of the variable.
1767 CharUnits Alignment;
1769 /// The address of the alloca. Null if the variable was emitted
1770 /// as a global constant.
1771 llvm::Value *Address;
1773 llvm::Value *NRVOFlag;
1775 /// True if the variable is a __block variable.
1778 /// True if the variable is of aggregate type and has a constant
1780 bool IsConstantAggregate;
1782 /// Non-null if we should use lifetime annotations.
1783 llvm::Value *SizeForLifetimeMarkers;
1786 AutoVarEmission(Invalid) : Variable(nullptr) {}
1788 AutoVarEmission(const VarDecl &variable)
1789 : Variable(&variable), Address(nullptr), NRVOFlag(nullptr),
1790 IsByRef(false), IsConstantAggregate(false),
1791 SizeForLifetimeMarkers(nullptr) {}
1793 bool wasEmittedAsGlobal() const { return Address == nullptr; }
1796 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
1798 bool useLifetimeMarkers() const {
1799 return SizeForLifetimeMarkers != nullptr;
1801 llvm::Value *getSizeForLifetimeMarkers() const {
1802 assert(useLifetimeMarkers());
1803 return SizeForLifetimeMarkers;
1806 /// Returns the raw, allocated address, which is not necessarily
1807 /// the address of the object itself.
1808 llvm::Value *getAllocatedAddress() const {
1812 /// Returns the address of the object within this declaration.
1813 /// Note that this does not chase the forwarding pointer for
1815 llvm::Value *getObjectAddress(CodeGenFunction &CGF) const {
1816 if (!IsByRef) return Address;
1818 return CGF.Builder.CreateStructGEP(Address,
1819 CGF.getByRefValueLLVMField(Variable),
1820 Variable->getNameAsString());
1823 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
1824 void EmitAutoVarInit(const AutoVarEmission &emission);
1825 void EmitAutoVarCleanups(const AutoVarEmission &emission);
1826 void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
1827 QualType::DestructionKind dtorKind);
1829 void EmitStaticVarDecl(const VarDecl &D,
1830 llvm::GlobalValue::LinkageTypes Linkage);
1832 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
1833 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, bool ArgIsPointer,
1836 /// protectFromPeepholes - Protect a value that we're intending to
1837 /// store to the side, but which will probably be used later, from
1838 /// aggressive peepholing optimizations that might delete it.
1840 /// Pass the result to unprotectFromPeepholes to declare that
1841 /// protection is no longer required.
1843 /// There's no particular reason why this shouldn't apply to
1844 /// l-values, it's just that no existing peepholes work on pointers.
1845 PeepholeProtection protectFromPeepholes(RValue rvalue);
1846 void unprotectFromPeepholes(PeepholeProtection protection);
1848 //===--------------------------------------------------------------------===//
1849 // Statement Emission
1850 //===--------------------------------------------------------------------===//
1852 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
1853 void EmitStopPoint(const Stmt *S);
1855 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
1856 /// this function even if there is no current insertion point.
1858 /// This function may clear the current insertion point; callers should use
1859 /// EnsureInsertPoint if they wish to subsequently generate code without first
1860 /// calling EmitBlock, EmitBranch, or EmitStmt.
1861 void EmitStmt(const Stmt *S);
1863 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
1864 /// necessarily require an insertion point or debug information; typically
1865 /// because the statement amounts to a jump or a container of other
1868 /// \return True if the statement was handled.
1869 bool EmitSimpleStmt(const Stmt *S);
1871 llvm::Value *EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
1872 AggValueSlot AVS = AggValueSlot::ignored());
1873 llvm::Value *EmitCompoundStmtWithoutScope(const CompoundStmt &S,
1874 bool GetLast = false,
1876 AggValueSlot::ignored());
1878 /// EmitLabel - Emit the block for the given label. It is legal to call this
1879 /// function even if there is no current insertion point.
1880 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
1882 void EmitLabelStmt(const LabelStmt &S);
1883 void EmitAttributedStmt(const AttributedStmt &S);
1884 void EmitGotoStmt(const GotoStmt &S);
1885 void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
1886 void EmitIfStmt(const IfStmt &S);
1888 void EmitCondBrHints(llvm::LLVMContext &Context, llvm::BranchInst *CondBr,
1889 const ArrayRef<const Attr *> &Attrs);
1890 void EmitWhileStmt(const WhileStmt &S,
1891 const ArrayRef<const Attr *> &Attrs = None);
1892 void EmitDoStmt(const DoStmt &S, const ArrayRef<const Attr *> &Attrs = None);
1893 void EmitForStmt(const ForStmt &S,
1894 const ArrayRef<const Attr *> &Attrs = None);
1895 void EmitReturnStmt(const ReturnStmt &S);
1896 void EmitDeclStmt(const DeclStmt &S);
1897 void EmitBreakStmt(const BreakStmt &S);
1898 void EmitContinueStmt(const ContinueStmt &S);
1899 void EmitSwitchStmt(const SwitchStmt &S);
1900 void EmitDefaultStmt(const DefaultStmt &S);
1901 void EmitCaseStmt(const CaseStmt &S);
1902 void EmitCaseStmtRange(const CaseStmt &S);
1903 void EmitAsmStmt(const AsmStmt &S);
1905 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
1906 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
1907 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
1908 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
1909 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
1911 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
1912 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
1914 void EmitCXXTryStmt(const CXXTryStmt &S);
1915 void EmitSEHTryStmt(const SEHTryStmt &S);
1916 void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
1917 void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
1918 const ArrayRef<const Attr *> &Attrs = None);
1920 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
1921 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
1922 llvm::Value *GenerateCapturedStmtArgument(const CapturedStmt &S);
1924 void EmitOMPParallelDirective(const OMPParallelDirective &S);
1925 void EmitOMPSimdDirective(const OMPSimdDirective &S);
1926 void EmitOMPForDirective(const OMPForDirective &S);
1927 void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
1928 void EmitOMPSectionDirective(const OMPSectionDirective &S);
1929 void EmitOMPSingleDirective(const OMPSingleDirective &S);
1930 void EmitOMPMasterDirective(const OMPMasterDirective &S);
1931 void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
1932 void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
1933 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
1934 void EmitOMPTaskDirective(const OMPTaskDirective &S);
1935 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
1936 void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
1937 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
1938 void EmitOMPFlushDirective(const OMPFlushDirective &S);
1940 //===--------------------------------------------------------------------===//
1941 // LValue Expression Emission
1942 //===--------------------------------------------------------------------===//
1944 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
1945 RValue GetUndefRValue(QualType Ty);
1947 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
1948 /// and issue an ErrorUnsupported style diagnostic (using the
1950 RValue EmitUnsupportedRValue(const Expr *E,
1953 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
1954 /// an ErrorUnsupported style diagnostic (using the provided Name).
1955 LValue EmitUnsupportedLValue(const Expr *E,
1958 /// EmitLValue - Emit code to compute a designator that specifies the location
1959 /// of the expression.
1961 /// This can return one of two things: a simple address or a bitfield
1962 /// reference. In either case, the LLVM Value* in the LValue structure is
1963 /// guaranteed to be an LLVM pointer type.
1965 /// If this returns a bitfield reference, nothing about the pointee type of
1966 /// the LLVM value is known: For example, it may not be a pointer to an
1969 /// If this returns a normal address, and if the lvalue's C type is fixed
1970 /// size, this method guarantees that the returned pointer type will point to
1971 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
1972 /// variable length type, this is not possible.
1974 LValue EmitLValue(const Expr *E);
1976 /// \brief Same as EmitLValue but additionally we generate checking code to
1977 /// guard against undefined behavior. This is only suitable when we know
1978 /// that the address will be used to access the object.
1979 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
1981 RValue convertTempToRValue(llvm::Value *addr, QualType type,
1982 SourceLocation Loc);
1984 void EmitAtomicInit(Expr *E, LValue lvalue);
1986 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
1987 AggValueSlot slot = AggValueSlot::ignored());
1989 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
1991 /// EmitToMemory - Change a scalar value from its value
1992 /// representation to its in-memory representation.
1993 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
1995 /// EmitFromMemory - Change a scalar value from its memory
1996 /// representation to its value representation.
1997 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
1999 /// EmitLoadOfScalar - Load a scalar value from an address, taking
2000 /// care to appropriately convert from the memory representation to
2001 /// the LLVM value representation.
2002 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
2003 unsigned Alignment, QualType Ty,
2005 llvm::MDNode *TBAAInfo = nullptr,
2006 QualType TBAABaseTy = QualType(),
2007 uint64_t TBAAOffset = 0);
2009 /// EmitLoadOfScalar - Load a scalar value from an address, taking
2010 /// care to appropriately convert from the memory representation to
2011 /// the LLVM value representation. The l-value must be a simple
2013 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
2015 /// EmitStoreOfScalar - Store a scalar value to an address, taking
2016 /// care to appropriately convert from the memory representation to
2017 /// the LLVM value representation.
2018 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
2019 bool Volatile, unsigned Alignment, QualType Ty,
2020 llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
2021 QualType TBAABaseTy = QualType(),
2022 uint64_t TBAAOffset = 0);
2024 /// EmitStoreOfScalar - Store a scalar value to an address, taking
2025 /// care to appropriately convert from the memory representation to
2026 /// the LLVM value representation. The l-value must be a simple
2027 /// l-value. The isInit flag indicates whether this is an initialization.
2028 /// If so, atomic qualifiers are ignored and the store is always non-atomic.
2029 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
2031 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
2032 /// this method emits the address of the lvalue, then loads the result as an
2033 /// rvalue, returning the rvalue.
2034 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
2035 RValue EmitLoadOfExtVectorElementLValue(LValue V);
2036 RValue EmitLoadOfBitfieldLValue(LValue LV);
2037 RValue EmitLoadOfGlobalRegLValue(LValue LV);
2039 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
2040 /// lvalue, where both are guaranteed to the have the same type, and that type
2042 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false);
2043 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
2044 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
2046 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
2047 /// as EmitStoreThroughLValue.
2049 /// \param Result [out] - If non-null, this will be set to a Value* for the
2050 /// bit-field contents after the store, appropriate for use as the result of
2051 /// an assignment to the bit-field.
2052 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
2053 llvm::Value **Result=nullptr);
2055 /// Emit an l-value for an assignment (simple or compound) of complex type.
2056 LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
2057 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
2058 LValue EmitScalarCompooundAssignWithComplex(const CompoundAssignOperator *E,
2059 llvm::Value *&Result);
2061 // Note: only available for agg return types
2062 LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
2063 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
2064 // Note: only available for agg return types
2065 LValue EmitCallExprLValue(const CallExpr *E);
2066 // Note: only available for agg return types
2067 LValue EmitVAArgExprLValue(const VAArgExpr *E);
2068 LValue EmitDeclRefLValue(const DeclRefExpr *E);
2069 LValue EmitReadRegister(const VarDecl *VD);
2070 LValue EmitStringLiteralLValue(const StringLiteral *E);
2071 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
2072 LValue EmitPredefinedLValue(const PredefinedExpr *E);
2073 LValue EmitUnaryOpLValue(const UnaryOperator *E);
2074 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2075 bool Accessed = false);
2076 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
2077 LValue EmitMemberExpr(const MemberExpr *E);
2078 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
2079 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
2080 LValue EmitInitListLValue(const InitListExpr *E);
2081 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
2082 LValue EmitCastLValue(const CastExpr *E);
2083 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
2084 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
2086 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
2088 class ConstantEmission {
2089 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
2090 ConstantEmission(llvm::Constant *C, bool isReference)
2091 : ValueAndIsReference(C, isReference) {}
2093 ConstantEmission() {}
2094 static ConstantEmission forReference(llvm::Constant *C) {
2095 return ConstantEmission(C, true);
2097 static ConstantEmission forValue(llvm::Constant *C) {
2098 return ConstantEmission(C, false);
2101 LLVM_EXPLICIT operator bool() const {
2102 return ValueAndIsReference.getOpaqueValue() != nullptr;
2105 bool isReference() const { return ValueAndIsReference.getInt(); }
2106 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
2107 assert(isReference());
2108 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
2109 refExpr->getType());
2112 llvm::Constant *getValue() const {
2113 assert(!isReference());
2114 return ValueAndIsReference.getPointer();
2118 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
2120 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
2121 AggValueSlot slot = AggValueSlot::ignored());
2122 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
2124 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2125 const ObjCIvarDecl *Ivar);
2126 LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
2127 LValue EmitLValueForLambdaField(const FieldDecl *Field);
2129 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
2130 /// if the Field is a reference, this will return the address of the reference
2131 /// and not the address of the value stored in the reference.
2132 LValue EmitLValueForFieldInitialization(LValue Base,
2133 const FieldDecl* Field);
2135 LValue EmitLValueForIvar(QualType ObjectTy,
2136 llvm::Value* Base, const ObjCIvarDecl *Ivar,
2137 unsigned CVRQualifiers);
2139 LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
2140 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
2141 LValue EmitLambdaLValue(const LambdaExpr *E);
2142 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
2143 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
2145 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
2146 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
2147 LValue EmitStmtExprLValue(const StmtExpr *E);
2148 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
2149 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
2150 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
2152 //===--------------------------------------------------------------------===//
2153 // Scalar Expression Emission
2154 //===--------------------------------------------------------------------===//
2156 /// EmitCall - Generate a call of the given function, expecting the given
2157 /// result type, and using the given argument list which specifies both the
2158 /// LLVM arguments and the types they were derived from.
2160 /// \param TargetDecl - If given, the decl of the function in a direct call;
2161 /// used to set attributes on the call (noreturn, etc.).
2162 RValue EmitCall(const CGFunctionInfo &FnInfo,
2163 llvm::Value *Callee,
2164 ReturnValueSlot ReturnValue,
2165 const CallArgList &Args,
2166 const Decl *TargetDecl = nullptr,
2167 llvm::Instruction **callOrInvoke = nullptr);
2169 RValue EmitCall(QualType FnType, llvm::Value *Callee,
2170 SourceLocation CallLoc,
2171 ReturnValueSlot ReturnValue,
2172 CallExpr::const_arg_iterator ArgBeg,
2173 CallExpr::const_arg_iterator ArgEnd,
2174 const Decl *TargetDecl = nullptr);
2175 RValue EmitCallExpr(const CallExpr *E,
2176 ReturnValueSlot ReturnValue = ReturnValueSlot());
2178 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
2179 const Twine &name = "");
2180 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
2181 ArrayRef<llvm::Value*> args,
2182 const Twine &name = "");
2183 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
2184 const Twine &name = "");
2185 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
2186 ArrayRef<llvm::Value*> args,
2187 const Twine &name = "");
2189 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
2190 ArrayRef<llvm::Value *> Args,
2191 const Twine &Name = "");
2192 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
2193 const Twine &Name = "");
2194 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
2195 ArrayRef<llvm::Value*> args,
2196 const Twine &name = "");
2197 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
2198 const Twine &name = "");
2199 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2200 ArrayRef<llvm::Value*> args);
2202 llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
2203 NestedNameSpecifier *Qual,
2206 llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
2208 const CXXRecordDecl *RD);
2210 RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
2211 SourceLocation CallLoc,
2212 llvm::Value *Callee,
2213 ReturnValueSlot ReturnValue,
2215 llvm::Value *ImplicitParam,
2216 QualType ImplicitParamTy,
2217 CallExpr::const_arg_iterator ArgBeg,
2218 CallExpr::const_arg_iterator ArgEnd);
2219 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
2220 ReturnValueSlot ReturnValue);
2221 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
2222 ReturnValueSlot ReturnValue);
2224 llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2225 const CXXMethodDecl *MD,
2227 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
2228 const CXXMethodDecl *MD,
2229 ReturnValueSlot ReturnValue);
2231 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
2232 ReturnValueSlot ReturnValue);
2235 RValue EmitBuiltinExpr(const FunctionDecl *FD,
2236 unsigned BuiltinID, const CallExpr *E);
2238 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
2240 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
2241 /// is unhandled by the current target.
2242 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2244 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
2245 const llvm::CmpInst::Predicate Fp,
2246 const llvm::CmpInst::Predicate Ip,
2247 const llvm::Twine &Name = "");
2248 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2250 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
2251 unsigned LLVMIntrinsic,
2252 unsigned AltLLVMIntrinsic,
2253 const char *NameHint,
2256 SmallVectorImpl<llvm::Value *> &Ops,
2257 llvm::Value *Align = nullptr);
2258 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
2259 unsigned Modifier, llvm::Type *ArgTy,
2261 llvm::Value *EmitNeonCall(llvm::Function *F,
2262 SmallVectorImpl<llvm::Value*> &O,
2264 unsigned shift = 0, bool rightshift = false);
2265 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
2266 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
2267 bool negateForRightShift);
2268 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
2269 llvm::Type *Ty, bool usgn, const char *name);
2270 // Helper functions for EmitAArch64BuiltinExpr.
2271 llvm::Value *vectorWrapScalar8(llvm::Value *Op);
2272 llvm::Value *vectorWrapScalar16(llvm::Value *Op);
2273 llvm::Value *emitVectorWrappedScalar8Intrinsic(
2274 unsigned Int, SmallVectorImpl<llvm::Value *> &Ops, const char *Name);
2275 llvm::Value *emitVectorWrappedScalar16Intrinsic(
2276 unsigned Int, SmallVectorImpl<llvm::Value *> &Ops, const char *Name);
2277 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2278 llvm::Value *EmitNeon64Call(llvm::Function *F,
2279 llvm::SmallVectorImpl<llvm::Value *> &O,
2282 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
2283 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2284 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2285 llvm::Value *EmitR600BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2287 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
2288 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
2289 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
2290 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
2291 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
2292 llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
2293 const ObjCMethodDecl *MethodWithObjects);
2294 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
2295 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
2296 ReturnValueSlot Return = ReturnValueSlot());
2298 /// Retrieves the default cleanup kind for an ARC cleanup.
2299 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
2300 CleanupKind getARCCleanupKind() {
2301 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
2302 ? NormalAndEHCleanup : NormalCleanup;
2306 void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr);
2307 void EmitARCDestroyWeak(llvm::Value *addr);
2308 llvm::Value *EmitARCLoadWeak(llvm::Value *addr);
2309 llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr);
2310 llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr,
2312 void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src);
2313 void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src);
2314 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
2315 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
2316 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
2317 bool resultIgnored);
2318 llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value,
2319 bool resultIgnored);
2320 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
2321 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
2322 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
2323 void EmitARCDestroyStrong(llvm::Value *addr, ARCPreciseLifetime_t precise);
2324 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
2325 llvm::Value *EmitARCAutorelease(llvm::Value *value);
2326 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
2327 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
2328 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
2330 std::pair<LValue,llvm::Value*>
2331 EmitARCStoreAutoreleasing(const BinaryOperator *e);
2332 std::pair<LValue,llvm::Value*>
2333 EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
2335 llvm::Value *EmitObjCThrowOperand(const Expr *expr);
2337 llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr);
2338 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
2339 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
2341 llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
2342 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
2343 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
2345 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
2347 static Destroyer destroyARCStrongImprecise;
2348 static Destroyer destroyARCStrongPrecise;
2349 static Destroyer destroyARCWeak;
2351 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
2352 llvm::Value *EmitObjCAutoreleasePoolPush();
2353 llvm::Value *EmitObjCMRRAutoreleasePoolPush();
2354 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
2355 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
2357 /// \brief Emits a reference binding to the passed in expression.
2358 RValue EmitReferenceBindingToExpr(const Expr *E);
2360 //===--------------------------------------------------------------------===//
2361 // Expression Emission
2362 //===--------------------------------------------------------------------===//
2364 // Expressions are broken into three classes: scalar, complex, aggregate.
2366 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
2367 /// scalar type, returning the result.
2368 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
2370 /// EmitScalarConversion - Emit a conversion from the specified type to the
2371 /// specified destination type, both of which are LLVM scalar types.
2372 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
2375 /// EmitComplexToScalarConversion - Emit a conversion from the specified
2376 /// complex type to the specified destination type, where the destination type
2377 /// is an LLVM scalar type.
2378 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
2382 /// EmitAggExpr - Emit the computation of the specified expression
2383 /// of aggregate type. The result is computed into the given slot,
2384 /// which may be null to indicate that the value is not needed.
2385 void EmitAggExpr(const Expr *E, AggValueSlot AS);
2387 /// EmitAggExprToLValue - Emit the computation of the specified expression of
2388 /// aggregate type into a temporary LValue.
2389 LValue EmitAggExprToLValue(const Expr *E);
2391 /// EmitGCMemmoveCollectable - Emit special API for structs with object
2393 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
2396 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2397 /// make sure it survives garbage collection until this point.
2398 void EmitExtendGCLifetime(llvm::Value *object);
2400 /// EmitComplexExpr - Emit the computation of the specified expression of
2401 /// complex type, returning the result.
2402 ComplexPairTy EmitComplexExpr(const Expr *E,
2403 bool IgnoreReal = false,
2404 bool IgnoreImag = false);
2406 /// EmitComplexExprIntoLValue - Emit the given expression of complex
2407 /// type and place its result into the specified l-value.
2408 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
2410 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
2411 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
2413 /// EmitLoadOfComplex - Load a complex number from the specified l-value.
2414 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
2416 /// CreateStaticVarDecl - Create a zero-initialized LLVM global for
2417 /// a static local variable.
2418 llvm::Constant *CreateStaticVarDecl(const VarDecl &D,
2419 const char *Separator,
2420 llvm::GlobalValue::LinkageTypes Linkage);
2422 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
2423 /// global variable that has already been created for it. If the initializer
2424 /// has a different type than GV does, this may free GV and return a different
2425 /// one. Otherwise it just returns GV.
2426 llvm::GlobalVariable *
2427 AddInitializerToStaticVarDecl(const VarDecl &D,
2428 llvm::GlobalVariable *GV);
2431 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
2432 /// variable with global storage.
2433 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
2436 /// Call atexit() with a function that passes the given argument to
2437 /// the given function.
2438 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
2439 llvm::Constant *addr);
2441 /// Emit code in this function to perform a guarded variable
2442 /// initialization. Guarded initializations are used when it's not
2443 /// possible to prove that an initialization will be done exactly
2444 /// once, e.g. with a static local variable or a static data member
2445 /// of a class template.
2446 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
2449 /// GenerateCXXGlobalInitFunc - Generates code for initializing global
2451 void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
2452 ArrayRef<llvm::Constant *> Decls,
2453 llvm::GlobalVariable *Guard = nullptr);
2455 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
2457 void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
2458 const std::vector<std::pair<llvm::WeakVH,
2459 llvm::Constant*> > &DtorsAndObjects);
2461 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
2463 llvm::GlobalVariable *Addr,
2466 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
2468 void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
2471 void enterFullExpression(const ExprWithCleanups *E) {
2472 if (E->getNumObjects() == 0) return;
2473 enterNonTrivialFullExpression(E);
2475 void enterNonTrivialFullExpression(const ExprWithCleanups *E);
2477 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
2479 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
2481 RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest = nullptr);
2483 //===--------------------------------------------------------------------===//
2484 // Annotations Emission
2485 //===--------------------------------------------------------------------===//
2487 /// Emit an annotation call (intrinsic or builtin).
2488 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
2489 llvm::Value *AnnotatedVal,
2490 StringRef AnnotationStr,
2491 SourceLocation Location);
2493 /// Emit local annotations for the local variable V, declared by D.
2494 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
2496 /// Emit field annotations for the given field & value. Returns the
2497 /// annotation result.
2498 llvm::Value *EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V);
2500 //===--------------------------------------------------------------------===//
2502 //===--------------------------------------------------------------------===//
2504 /// ContainsLabel - Return true if the statement contains a label in it. If
2505 /// this statement is not executed normally, it not containing a label means
2506 /// that we can just remove the code.
2507 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
2509 /// containsBreak - Return true if the statement contains a break out of it.
2510 /// If the statement (recursively) contains a switch or loop with a break
2511 /// inside of it, this is fine.
2512 static bool containsBreak(const Stmt *S);
2514 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
2515 /// to a constant, or if it does but contains a label, return false. If it
2516 /// constant folds return true and set the boolean result in Result.
2517 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result);
2519 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
2520 /// to a constant, or if it does but contains a label, return false. If it
2521 /// constant folds return true and set the folded value.
2522 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result);
2524 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
2525 /// if statement) to the specified blocks. Based on the condition, this might
2526 /// try to simplify the codegen of the conditional based on the branch.
2527 /// TrueCount should be the number of times we expect the condition to
2528 /// evaluate to true based on PGO data.
2529 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
2530 llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
2532 /// \brief Emit a description of a type in a format suitable for passing to
2533 /// a runtime sanitizer handler.
2534 llvm::Constant *EmitCheckTypeDescriptor(QualType T);
2536 /// \brief Convert a value into a format suitable for passing to a runtime
2537 /// sanitizer handler.
2538 llvm::Value *EmitCheckValue(llvm::Value *V);
2540 /// \brief Emit a description of a source location in a format suitable for
2541 /// passing to a runtime sanitizer handler.
2542 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
2544 /// \brief Specify under what conditions this check can be recovered
2545 enum CheckRecoverableKind {
2546 /// Always terminate program execution if this check fails
2548 /// Check supports recovering, allows user to specify which
2550 /// Runtime conditionally aborts, always need to support recovery.
2551 CRK_AlwaysRecoverable
2554 /// \brief Create a basic block that will call a handler function in a
2555 /// sanitizer runtime with the provided arguments, and create a conditional
2557 void EmitCheck(llvm::Value *Checked, StringRef CheckName,
2558 ArrayRef<llvm::Constant *> StaticArgs,
2559 ArrayRef<llvm::Value *> DynamicArgs,
2560 CheckRecoverableKind Recoverable);
2562 /// \brief Create a basic block that will call the trap intrinsic, and emit a
2563 /// conditional branch to it, for the -ftrapv checks.
2564 void EmitTrapCheck(llvm::Value *Checked);
2566 /// EmitCallArg - Emit a single call argument.
2567 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
2569 /// EmitDelegateCallArg - We are performing a delegate call; that
2570 /// is, the current function is delegating to another one. Produce
2571 /// a r-value suitable for passing the given parameter.
2572 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
2573 SourceLocation loc);
2575 /// SetFPAccuracy - Set the minimum required accuracy of the given floating
2576 /// point operation, expressed as the maximum relative error in ulp.
2577 void SetFPAccuracy(llvm::Value *Val, float Accuracy);
2580 llvm::MDNode *getRangeForLoadFromType(QualType Ty);
2581 void EmitReturnOfRValue(RValue RV, QualType Ty);
2583 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
2585 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
2586 DeferredReplacements;
2588 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
2589 /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
2591 /// \param AI - The first function argument of the expansion.
2592 /// \return The argument following the last expanded function
2594 llvm::Function::arg_iterator
2595 ExpandTypeFromArgs(QualType Ty, LValue Dst,
2596 llvm::Function::arg_iterator AI);
2598 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
2599 /// Ty, into individual arguments on the provided vector \arg Args. See
2600 /// ABIArgInfo::Expand.
2601 void ExpandTypeToArgs(QualType Ty, RValue Src,
2602 SmallVectorImpl<llvm::Value *> &Args,
2603 llvm::FunctionType *IRFuncTy);
2605 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
2606 const Expr *InputExpr, std::string &ConstraintStr);
2608 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
2609 LValue InputValue, QualType InputType,
2610 std::string &ConstraintStr,
2611 SourceLocation Loc);
2614 /// EmitCallArgs - Emit call arguments for a function.
2615 template <typename T>
2616 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
2617 CallExpr::const_arg_iterator ArgBeg,
2618 CallExpr::const_arg_iterator ArgEnd,
2619 bool ForceColumnInfo = false) {
2620 if (CallArgTypeInfo) {
2621 EmitCallArgs(Args, CallArgTypeInfo->isVariadic(),
2622 CallArgTypeInfo->param_type_begin(),
2623 CallArgTypeInfo->param_type_end(), ArgBeg, ArgEnd,
2626 // T::param_type_iterator might not have a default ctor.
2627 const QualType *NoIter = nullptr;
2628 EmitCallArgs(Args, /*AllowExtraArguments=*/true, NoIter, NoIter, ArgBeg,
2629 ArgEnd, ForceColumnInfo);
2633 template<typename ArgTypeIterator>
2634 void EmitCallArgs(CallArgList& Args,
2635 bool AllowExtraArguments,
2636 ArgTypeIterator ArgTypeBeg,
2637 ArgTypeIterator ArgTypeEnd,
2638 CallExpr::const_arg_iterator ArgBeg,
2639 CallExpr::const_arg_iterator ArgEnd,
2640 bool ForceColumnInfo = false) {
2641 SmallVector<QualType, 16> ArgTypes;
2642 CallExpr::const_arg_iterator Arg = ArgBeg;
2644 // First, use the argument types that the type info knows about
2645 for (ArgTypeIterator I = ArgTypeBeg, E = ArgTypeEnd; I != E; ++I, ++Arg) {
2646 assert(Arg != ArgEnd && "Running over edge of argument list!");
2648 QualType ArgType = *I;
2649 QualType ActualArgType = Arg->getType();
2650 if (ArgType->isPointerType() && ActualArgType->isPointerType()) {
2651 QualType ActualBaseType =
2652 ActualArgType->getAs<PointerType>()->getPointeeType();
2653 QualType ArgBaseType =
2654 ArgType->getAs<PointerType>()->getPointeeType();
2655 if (ArgBaseType->isVariableArrayType()) {
2656 if (const VariableArrayType *VAT =
2657 getContext().getAsVariableArrayType(ActualBaseType)) {
2658 if (!VAT->getSizeExpr())
2659 ActualArgType = ArgType;
2663 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
2665 getContext().getCanonicalType(ActualArgType).getTypePtr() &&
2666 "type mismatch in call argument!");
2668 ArgTypes.push_back(*I);
2671 // Either we've emitted all the call args, or we have a call to variadic
2672 // function or some other call that allows extra arguments.
2673 assert((Arg == ArgEnd || AllowExtraArguments) &&
2674 "Extra arguments in non-variadic function!");
2676 // If we still have any arguments, emit them using the type of the argument.
2677 for (; Arg != ArgEnd; ++Arg)
2678 ArgTypes.push_back(Arg->getType());
2680 EmitCallArgs(Args, ArgTypes, ArgBeg, ArgEnd, ForceColumnInfo);
2683 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
2684 CallExpr::const_arg_iterator ArgBeg,
2685 CallExpr::const_arg_iterator ArgEnd,
2686 bool ForceColumnInfo = false);
2689 const TargetCodeGenInfo &getTargetHooks() const {
2690 return CGM.getTargetCodeGenInfo();
2693 void EmitDeclMetadata();
2695 CodeGenModule::ByrefHelpers *
2696 buildByrefHelpers(llvm::StructType &byrefType,
2697 const AutoVarEmission &emission);
2699 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
2701 /// GetPointeeAlignment - Given an expression with a pointer type, emit the
2702 /// value and compute our best estimate of the alignment of the pointee.
2703 std::pair<llvm::Value*, unsigned> EmitPointerWithAlignment(const Expr *Addr);
2706 /// Helper class with most of the code for saving a value for a
2707 /// conditional expression cleanup.
2708 struct DominatingLLVMValue {
2709 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
2711 /// Answer whether the given value needs extra work to be saved.
2712 static bool needsSaving(llvm::Value *value) {
2713 // If it's not an instruction, we don't need to save.
2714 if (!isa<llvm::Instruction>(value)) return false;
2716 // If it's an instruction in the entry block, we don't need to save.
2717 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
2718 return (block != &block->getParent()->getEntryBlock());
2721 /// Try to save the given value.
2722 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
2723 if (!needsSaving(value)) return saved_type(value, false);
2725 // Otherwise we need an alloca.
2726 llvm::Value *alloca =
2727 CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save");
2728 CGF.Builder.CreateStore(value, alloca);
2730 return saved_type(alloca, true);
2733 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
2734 if (!value.getInt()) return value.getPointer();
2735 return CGF.Builder.CreateLoad(value.getPointer());
2739 /// A partial specialization of DominatingValue for llvm::Values that
2740 /// might be llvm::Instructions.
2741 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
2743 static type restore(CodeGenFunction &CGF, saved_type value) {
2744 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
2748 /// A specialization of DominatingValue for RValue.
2749 template <> struct DominatingValue<RValue> {
2750 typedef RValue type;
2752 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
2753 AggregateAddress, ComplexAddress };
2757 saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {}
2760 static bool needsSaving(RValue value);
2761 static saved_type save(CodeGenFunction &CGF, RValue value);
2762 RValue restore(CodeGenFunction &CGF);
2764 // implementations in CGExprCXX.cpp
2767 static bool needsSaving(type value) {
2768 return saved_type::needsSaving(value);
2770 static saved_type save(CodeGenFunction &CGF, type value) {
2771 return saved_type::save(CGF, value);
2773 static type restore(CodeGenFunction &CGF, saved_type value) {
2774 return value.restore(CGF);
2778 } // end namespace CodeGen
2779 } // end namespace clang