CodeGenFunction.cpp revision c7ff8e19081c2e974f05f66c4fa9b40750fc655f
15f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
25f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
35f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//                     The LLVM Compiler Infrastructure
45f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
50bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// This file is distributed under the University of Illinois Open Source
60bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// License. See LICENSE.TXT for details.
75f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
85f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===//
95f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
105f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// This coordinates the per-function state used while generating code.
115f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
125f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===//
135f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
145f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "CodeGenFunction.h"
155f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "CodeGenModule.h"
163f2af1002249c8acc9ce17f1fc50324864feb8e1Eli Friedman#include "CGDebugInfo.h"
175f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/Basic/TargetInfo.h"
1831a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner#include "clang/AST/APValue.h"
19de7fb8413b13651fd85b7125d08b3c9ac2816d9dDaniel Dunbar#include "clang/AST/ASTContext.h"
20c4a1dea2dc56bd1357ec91b829a0b9e68229a13eDaniel Dunbar#include "clang/AST/Decl.h"
212b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson#include "clang/AST/DeclCXX.h"
224e7a1f7682d94811bd41fca8aefccc38f686db23Mike Stump#include "llvm/Target/TargetData.h"
235f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace clang;
245f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace CodeGen;
255f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
265f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid SpencerCodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
27a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump  : BlockFunction(cgm, *this, Builder), CGM(cgm),
28a4f668f3b7e03629066a01b04e415cb2b4655dafMike Stump    Target(CGM.getContext().Target),
29aac8705c046f01a264a4f82832895a5d9e695633Owen Anderson    Builder(cgm.getModule().getContext()),
302b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
312b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    CXXThisDecl(0) {
324e7a1f7682d94811bd41fca8aefccc38f686db23Mike Stump  LLVMIntTy = ConvertType(getContext().IntTy);
334e7a1f7682d94811bd41fca8aefccc38f686db23Mike Stump  LLVMPointerWidth = Target.getPointerWidth(0);
344111024be81e7c0525e42dadcc126d27e5bf2425Chris Lattner}
355f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
365f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid SpencerASTContext &CodeGenFunction::getContext() const {
375f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  return CGM.getContext();
385f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
395f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
405f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
415f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerllvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
425f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  llvm::BasicBlock *&BB = LabelMap[S];
435f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  if (BB) return BB;
445f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
455f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  // Create, but don't insert, the new block.
4655e874299f2ad827646a4ca9ea38c402aaeb38c9Daniel Dunbar  return BB = createBasicBlock(S->getName());
475f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
485f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
490096acf421c4609ce7f43e8b05f8c5ca866d4611Daniel Dunbarllvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
500096acf421c4609ce7f43e8b05f8c5ca866d4611Daniel Dunbar  llvm::Value *Res = LocalDeclMap[VD];
510096acf421c4609ce7f43e8b05f8c5ca866d4611Daniel Dunbar  assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
520096acf421c4609ce7f43e8b05f8c5ca866d4611Daniel Dunbar  return Res;
53813733577d33ec56479667b49e1bff42dc6bba90Lauro Ramos Venancio}
545f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
550096acf421c4609ce7f43e8b05f8c5ca866d4611Daniel Dunbarllvm::Constant *
560096acf421c4609ce7f43e8b05f8c5ca866d4611Daniel DunbarCodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
570096acf421c4609ce7f43e8b05f8c5ca866d4611Daniel Dunbar  return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
58dde0a94120915fa925d1ffcdb997c7b44dc9fa21Anders Carlsson}
59dde0a94120915fa925d1ffcdb997c7b44dc9fa21Anders Carlsson
608b1a343b6b360d63d5dc8a6beb841ce4414c1e00Daniel Dunbarconst llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
618b1a343b6b360d63d5dc8a6beb841ce4414c1e00Daniel Dunbar  return CGM.getTypes().ConvertTypeForMem(T);
628b1a343b6b360d63d5dc8a6beb841ce4414c1e00Daniel Dunbar}
638b1a343b6b360d63d5dc8a6beb841ce4414c1e00Daniel Dunbar
645f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerconst llvm::Type *CodeGenFunction::ConvertType(QualType T) {
655f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  return CGM.getTypes().ConvertType(T);
665f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
675f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
684111024be81e7c0525e42dadcc126d27e5bf2425Chris Lattnerbool CodeGenFunction::hasAggregateLLVMType(QualType T) {
69f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump  // FIXME: Use positive checks instead of negative ones to be more robust in
70f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump  // the face of extension.
718958891f5fa1e593c4519a36b3df427ee019d70bDaniel Dunbar  return !T->hasPointerRepresentation() &&!T->isRealType() &&
728958891f5fa1e593c4519a36b3df427ee019d70bDaniel Dunbar    !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() &&
73a782ca76cc7dfdd69e331a4fa722fc23b18d5c34Daniel Dunbar    !T->isBlockPointerType();
744111024be81e7c0525e42dadcc126d27e5bf2425Chris Lattner}
75391d77a26382dddf25da73e29fc1fa5aaaea4c6fChris Lattner
761c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbarvoid CodeGenFunction::EmitReturnBlock() {
771c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar  // For cleanliness, we try to avoid emitting the return block for
781c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar  // simple cases.
791c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
801c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar
811c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar  if (CurBB) {
821c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar    assert(!CurBB->getTerminator() && "Unexpected terminated block.");
831c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar
8496e18b05ea6b55aa92a1a576f29e9cee73a7e20bDaniel Dunbar    // We have a valid insert point, reuse it if it is empty or there are no
8596e18b05ea6b55aa92a1a576f29e9cee73a7e20bDaniel Dunbar    // explicit jumps to the return block.
8696e18b05ea6b55aa92a1a576f29e9cee73a7e20bDaniel Dunbar    if (CurBB->empty() || ReturnBlock->use_empty()) {
8796e18b05ea6b55aa92a1a576f29e9cee73a7e20bDaniel Dunbar      ReturnBlock->replaceAllUsesWith(CurBB);
881c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar      delete ReturnBlock;
8996e18b05ea6b55aa92a1a576f29e9cee73a7e20bDaniel Dunbar    } else
901c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar      EmitBlock(ReturnBlock);
911c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar    return;
921c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar  }
931c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar
941c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar  // Otherwise, if the return block is the target of a single direct
951c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar  // branch then we can just put the code in that block instead. This
961c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar  // cleans up functions which started with a unified return block.
971c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar  if (ReturnBlock->hasOneUse()) {
981c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar    llvm::BranchInst *BI =
991c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar      dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
1001c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar    if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
1011c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar      // Reset insertion point and delete the branch.
1021c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar      Builder.SetInsertPoint(BI->getParent());
1031c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar      BI->eraseFromParent();
1041c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar      delete ReturnBlock;
1051c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar      return;
1061c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar    }
1071c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar  }
1081c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar
109f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump  // FIXME: We are at an unreachable point, there is no reason to emit the block
110f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump  // unless it has uses. However, we still need a place to put the debug
111f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump  // region.end for now.
1121c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar
1131c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar  EmitBlock(ReturnBlock);
1141c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar}
1151c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar
116af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbarvoid CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
1170ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar  // Finish emission of indirect switches.
1180ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar  EmitIndirectSwitches();
1190ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar
120391d77a26382dddf25da73e29fc1fa5aaaea4c6fChris Lattner  assert(BreakContinueStack.empty() &&
121391d77a26382dddf25da73e29fc1fa5aaaea4c6fChris Lattner         "mismatched push/pop in break/continue stack!");
122bd6fa3d032acd7eafc6c10827c41103df45beab7Anders Carlsson  assert(BlockScopes.empty() &&
123bd6fa3d032acd7eafc6c10827c41103df45beab7Anders Carlsson         "did not remove all blocks from block scope map!");
124bd6fa3d032acd7eafc6c10827c41103df45beab7Anders Carlsson  assert(CleanupEntries.empty() &&
125bd6fa3d032acd7eafc6c10827c41103df45beab7Anders Carlsson         "mismatched push/pop in cleanup stack!");
126bd6fa3d032acd7eafc6c10827c41103df45beab7Anders Carlsson
1271c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar  // Emit function epilog (to return).
1281c1d6074f5a0296dd273362655b1b8f9057289e3Daniel Dunbar  EmitReturnBlock();
129f5bd45c8e6fa7519cdc17ec3ff4917e279c6a041Daniel Dunbar
130f5bd45c8e6fa7519cdc17ec3ff4917e279c6a041Daniel Dunbar  // Emit debug descriptor for function end.
131e896d98548b02223c7740d807a0aa6e20fba7079Anders Carlsson  if (CGDebugInfo *DI = getDebugInfo()) {
132f5bd45c8e6fa7519cdc17ec3ff4917e279c6a041Daniel Dunbar    DI->setLocation(EndLoc);
133f5bd45c8e6fa7519cdc17ec3ff4917e279c6a041Daniel Dunbar    DI->EmitRegionEnd(CurFn, Builder);
134f5bd45c8e6fa7519cdc17ec3ff4917e279c6a041Daniel Dunbar  }
135f5bd45c8e6fa7519cdc17ec3ff4917e279c6a041Daniel Dunbar
13688b5396b0897f28d22ae3debf4a0d97b33b6c362Daniel Dunbar  EmitFunctionEpilog(*CurFnInfo, ReturnValue);
1375ca2084cf9b529563209429857f01fdae9dcdfa5Daniel Dunbar
138391d77a26382dddf25da73e29fc1fa5aaaea4c6fChris Lattner  // Remove the AllocaInsertPt instruction, which is just a convenience for us.
139481769b5dc102b0256b35581e787909ad5edfab5Chris Lattner  llvm::Instruction *Ptr = AllocaInsertPt;
140391d77a26382dddf25da73e29fc1fa5aaaea4c6fChris Lattner  AllocaInsertPt = 0;
141481769b5dc102b0256b35581e787909ad5edfab5Chris Lattner  Ptr->eraseFromParent();
142c8aa5f1f264fb230c38182adab944232bb160c2bChris Lattner}
143c8aa5f1f264fb230c38182adab944232bb160c2bChris Lattner
1447c086516f3cc9fba2733b1919973206c6ba4b171Daniel Dunbarvoid CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
1457c086516f3cc9fba2733b1919973206c6ba4b171Daniel Dunbar                                    llvm::Function *Fn,
1462284ac9ec80299fcdefae9a2787cf85105a0f203Daniel Dunbar                                    const FunctionArgList &Args,
1472284ac9ec80299fcdefae9a2787cf85105a0f203Daniel Dunbar                                    SourceLocation StartLoc) {
1484cc1a4703363ff940b6273aeef9d96a87edeb04bAnders Carlsson  DidCallStackSave = false;
149b5437d238752dc297e42410e98d38d5250fe0463Chris Lattner  CurCodeDecl = CurFuncDecl = D;
1507c086516f3cc9fba2733b1919973206c6ba4b171Daniel Dunbar  FnRetTy = RetTy;
151bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  CurFn = Fn;
1525f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  assert(CurFn->isDeclaration() && "Function already has body?");
153ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner
15455e874299f2ad827646a4ca9ea38c402aaeb38c9Daniel Dunbar  llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
1555ca2084cf9b529563209429857f01fdae9dcdfa5Daniel Dunbar
1565f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  // Create a marker to make it easy to insert allocas into the entryblock
15755352a2d616cf9fbb621d10faf8b960b4b268bd8Chris Lattner  // later.  Don't create this with the builder, because we don't want it
15855352a2d616cf9fbb621d10faf8b960b4b268bd8Chris Lattner  // folded.
15903e205031b08669f05c41eed5b896fc94c4a12bbOwen Anderson  llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
160f1466848dce9c4c75d96a6cabdc8db560e26aac8Chris Lattner  AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "",
16155352a2d616cf9fbb621d10faf8b960b4b268bd8Chris Lattner                                         EntryBB);
162f1466848dce9c4c75d96a6cabdc8db560e26aac8Chris Lattner  if (Builder.isNamePreserving())
163f1466848dce9c4c75d96a6cabdc8db560e26aac8Chris Lattner    AllocaInsertPt->setName("allocapt");
164f1466848dce9c4c75d96a6cabdc8db560e26aac8Chris Lattner
16555e874299f2ad827646a4ca9ea38c402aaeb38c9Daniel Dunbar  ReturnBlock = createBasicBlock("return");
1665ca2084cf9b529563209429857f01fdae9dcdfa5Daniel Dunbar  ReturnValue = 0;
1677c086516f3cc9fba2733b1919973206c6ba4b171Daniel Dunbar  if (!RetTy->isVoidType())
1687c086516f3cc9fba2733b1919973206c6ba4b171Daniel Dunbar    ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
1695ca2084cf9b529563209429857f01fdae9dcdfa5Daniel Dunbar
17055352a2d616cf9fbb621d10faf8b960b4b268bd8Chris Lattner  Builder.SetInsertPoint(EntryBB);
1714111024be81e7c0525e42dadcc126d27e5bf2425Chris Lattner
172af99417156c652a6f04dff643925036dc3241d60Sanjiv Gupta  // Emit subprogram debug descriptor.
1737c086516f3cc9fba2733b1919973206c6ba4b171Daniel Dunbar  // FIXME: The cast here is a huge hack.
174e896d98548b02223c7740d807a0aa6e20fba7079Anders Carlsson  if (CGDebugInfo *DI = getDebugInfo()) {
1752284ac9ec80299fcdefae9a2787cf85105a0f203Daniel Dunbar    DI->setLocation(StartLoc);
1762284ac9ec80299fcdefae9a2787cf85105a0f203Daniel Dunbar    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1776ec3668a2608b63473207319f5ceff9bbd22ea51Douglas Gregor      DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder);
1782284ac9ec80299fcdefae9a2787cf85105a0f203Daniel Dunbar    } else {
1792284ac9ec80299fcdefae9a2787cf85105a0f203Daniel Dunbar      // Just use LLVM function name.
18042719fc8145cb0da244b1826551e6b441db89209Daniel Dunbar
18142719fc8145cb0da244b1826551e6b441db89209Daniel Dunbar      // FIXME: Remove unnecessary conversion to std::string when API settles.
18242719fc8145cb0da244b1826551e6b441db89209Daniel Dunbar      DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
1832284ac9ec80299fcdefae9a2787cf85105a0f203Daniel Dunbar                            RetTy, CurFn, Builder);
184af99417156c652a6f04dff643925036dc3241d60Sanjiv Gupta    }
185af99417156c652a6f04dff643925036dc3241d60Sanjiv Gupta  }
186af99417156c652a6f04dff643925036dc3241d60Sanjiv Gupta
18788b5396b0897f28d22ae3debf4a0d97b33b6c362Daniel Dunbar  // FIXME: Leaked.
188541b63b1a9db77e4a8670e9823711c2c12e58afbDaniel Dunbar  CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
18988b5396b0897f28d22ae3debf4a0d97b33b6c362Daniel Dunbar  EmitFunctionProlog(*CurFnInfo, CurFn, Args);
190751358ff73b155f5384e151e1d18aa3f6e7b061cAnders Carlsson
191751358ff73b155f5384e151e1d18aa3f6e7b061cAnders Carlsson  // If any of the arguments have a variably modified type, make sure to
192751358ff73b155f5384e151e1d18aa3f6e7b061cAnders Carlsson  // emit the type size.
193751358ff73b155f5384e151e1d18aa3f6e7b061cAnders Carlsson  for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
194751358ff73b155f5384e151e1d18aa3f6e7b061cAnders Carlsson       i != e; ++i) {
195751358ff73b155f5384e151e1d18aa3f6e7b061cAnders Carlsson    QualType Ty = i->second;
196751358ff73b155f5384e151e1d18aa3f6e7b061cAnders Carlsson
197751358ff73b155f5384e151e1d18aa3f6e7b061cAnders Carlsson    if (Ty->isVariablyModifiedType())
198751358ff73b155f5384e151e1d18aa3f6e7b061cAnders Carlsson      EmitVLASize(Ty);
199751358ff73b155f5384e151e1d18aa3f6e7b061cAnders Carlsson  }
2007c086516f3cc9fba2733b1919973206c6ba4b171Daniel Dunbar}
201eb4b7051a596560ef4a1846e3714707f44e9dc30Eli Friedman
2027c086516f3cc9fba2733b1919973206c6ba4b171Daniel Dunbarvoid CodeGenFunction::GenerateCode(const FunctionDecl *FD,
2037c086516f3cc9fba2733b1919973206c6ba4b171Daniel Dunbar                                   llvm::Function *Fn) {
204e896d98548b02223c7740d807a0aa6e20fba7079Anders Carlsson  // Check if we should generate debug info for this function.
20540b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (CGM.getDebugInfo() && !FD->hasAttr<NodebugAttr>())
206e896d98548b02223c7740d807a0aa6e20fba7079Anders Carlsson    DebugInfo = CGM.getDebugInfo();
207e896d98548b02223c7740d807a0aa6e20fba7079Anders Carlsson
2087c086516f3cc9fba2733b1919973206c6ba4b171Daniel Dunbar  FunctionArgList Args;
2092b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson
2102b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
2112b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    if (MD->isInstance()) {
2122b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson      // Create the implicit 'this' decl.
2132b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson      // FIXME: I'm not entirely sure I like using a fake decl just for code
2142b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson      // generation. Maybe we can come up with a better way?
2152b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson      CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
2162b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson                                              &getContext().Idents.get("this"),
2172b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson                                              MD->getThisType(getContext()));
2182b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson      Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
2192b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    }
2202b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  }
2212b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson
222eb4b7051a596560ef4a1846e3714707f44e9dc30Eli Friedman  if (FD->getNumParams()) {
22372564e73277e29f6db3305d1f27ba408abb7ed88Douglas Gregor    const FunctionProtoType* FProto = FD->getType()->getAsFunctionProtoType();
224eb4b7051a596560ef4a1846e3714707f44e9dc30Eli Friedman    assert(FProto && "Function def must have prototype!");
2257c086516f3cc9fba2733b1919973206c6ba4b171Daniel Dunbar
2267c086516f3cc9fba2733b1919973206c6ba4b171Daniel Dunbar    for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
2277c086516f3cc9fba2733b1919973206c6ba4b171Daniel Dunbar      Args.push_back(std::make_pair(FD->getParamDecl(i),
2287c086516f3cc9fba2733b1919973206c6ba4b171Daniel Dunbar                                    FProto->getArgType(i)));
2295f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  }
230af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
231d3a413d3b8eb39bcee5944bc545d9997c1abe492Sebastian Redl  // FIXME: Support CXXTryStmt here, too.
2326fb0aee4f9dc261bbec72e1283ad8dc0557a6d96Argyrios Kyrtzidis  if (const CompoundStmt *S = FD->getCompoundBody()) {
233d3a413d3b8eb39bcee5944bc545d9997c1abe492Sebastian Redl    StartFunction(FD, FD->getResultType(), Fn, Args, S->getLBracLoc());
234ab3c0a2c879569bb00fa664ebaccf9442c0a9c5fFariborz Jahanian    if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
235ab3c0a2c879569bb00fa664ebaccf9442c0a9c5fFariborz Jahanian      EmitCtorPrologue(CD);
236d3a413d3b8eb39bcee5944bc545d9997c1abe492Sebastian Redl    EmitStmt(S);
237426cc3828ce07a2cff15c9837f5958e6fc4b7739Fariborz Jahanian    if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
238426cc3828ce07a2cff15c9837f5958e6fc4b7739Fariborz Jahanian      EmitDtorEpilogue(DD);
239d3a413d3b8eb39bcee5944bc545d9997c1abe492Sebastian Redl    FinishFunction(S->getRBracLoc());
240d3a413d3b8eb39bcee5944bc545d9997c1abe492Sebastian Redl  }
241c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian  else
242c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian    if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
243c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian      assert(
244c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian             !cast<CXXRecordDecl>(CD->getDeclContext())->
245c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian              hasUserDeclaredConstructor() &&
246c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian             "bogus constructor is being synthesize");
247c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian      StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
248c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian      EmitCtorPrologue(CD);
249c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian      FinishFunction();
250c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian    }
251c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian
2522b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  // Destroy the 'this' declaration.
2532b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  if (CXXThisDecl)
2542b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    CXXThisDecl->Destroy(getContext());
2555f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
2565f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
2570946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner/// ContainsLabel - Return true if the statement contains a label in it.  If
2580946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner/// this statement is not executed normally, it not containing a label means
2590946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner/// that we can just remove the code.
2600946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattnerbool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
2610946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner  // Null statement, not a label!
2620946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner  if (S == 0) return false;
2630946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner
2640946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner  // If this is a label, we have to emit the code, consider something like:
2650946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner  // if (0) {  ...  foo:  bar(); }  goto foo;
2660946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner  if (isa<LabelStmt>(S))
2670946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner    return true;
2680946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner
2690946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner  // If this is a case/default statement, and we haven't seen a switch, we have
2700946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner  // to emit the code.
2710946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner  if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
2720946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner    return true;
2730946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner
2740946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner  // If this is a switch statement, we want to ignore cases below it.
2750946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner  if (isa<SwitchStmt>(S))
2760946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner    IgnoreCaseStmts = true;
2770946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner
2780946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner  // Scan subexpressions for verboten labels.
2790946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner  for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
2800946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner       I != E; ++I)
2810946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner    if (ContainsLabel(*I, IgnoreCaseStmts))
2820946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner      return true;
2830946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner
2840946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner  return false;
2850946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner}
2860946ccd1e58c1f1da31ddbca67c5b6301ac8b255Chris Lattner
28731a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner
28831a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
28931a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner/// a constant, or if it does but contains a label, return 0.  If it constant
29031a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner/// folds to 'true' and does not contain a label, return 1, if it constant folds
29131a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner/// to 'false' and does not contain a label, return -1.
29231a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattnerint CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
29336bc14c3a1cf63ee306df5687ac8e85f924f8639Daniel Dunbar  // FIXME: Rename and handle conversion of other evaluatable things
29436bc14c3a1cf63ee306df5687ac8e85f924f8639Daniel Dunbar  // to bool.
29564712f196bffd41fb0552c2643b07a25c3e45082Anders Carlsson  Expr::EvalResult Result;
29664712f196bffd41fb0552c2643b07a25c3e45082Anders Carlsson  if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
29764712f196bffd41fb0552c2643b07a25c3e45082Anders Carlsson      Result.HasSideEffects)
298ef5a66d8171eb95e948107f8ee7707b360aaff25Anders Carlsson    return 0;  // Not foldable, not integer or not fully evaluatable.
29931a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner
30031a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner  if (CodeGenFunction::ContainsLabel(Cond))
30131a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner    return 0;  // Contains a label.
30231a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner
30364712f196bffd41fb0552c2643b07a25c3e45082Anders Carlsson  return Result.Val.getInt().getBoolValue() ? 1 : -1;
30431a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner}
30531a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner
30631a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner
30731a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
30831a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner/// statement) to the specified blocks.  Based on the condition, this might try
30931a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner/// to simplify the codegen of the conditional based on the branch.
31031a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner///
31131a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattnervoid CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
31231a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner                                           llvm::BasicBlock *TrueBlock,
31331a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner                                           llvm::BasicBlock *FalseBlock) {
31431a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner  if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
31531a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner    return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
31631a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner
31731a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner  if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
31831a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner    // Handle X && Y in a condition.
31931a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner    if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
32031a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      // If we have "1 && X", simplify the code.  "0 && X" would have constant
32131a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      // folded if the case was simple enough.
32231a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
32331a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner        // br(1 && X) -> br(X).
32431a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner        return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
32531a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      }
32631a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner
32731a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      // If we have "X && 1", simplify the code to use an uncond branch.
32831a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      // "X && 0" would have been constant folded to 0.
32931a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
33031a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner        // br(X && 1) -> br(X).
33131a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner        return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
33231a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      }
33331a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner
33431a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      // Emit the LHS as a conditional.  If the LHS conditional is false, we
33531a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      // want to jump to the FalseBlock.
3369615ecb44f549ae9fa2b4db6ff46bc78befbf62cDaniel Dunbar      llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
33731a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
33831a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      EmitBlock(LHSTrue);
33931a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner
34031a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
34131a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      return;
34231a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner    } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
34331a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      // If we have "0 || X", simplify the code.  "1 || X" would have constant
34431a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      // folded if the case was simple enough.
34531a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
34631a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner        // br(0 || X) -> br(X).
34731a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner        return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
34831a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      }
34931a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner
35031a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      // If we have "X || 0", simplify the code to use an uncond branch.
35131a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      // "X || 1" would have been constant folded to 1.
35231a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
35331a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner        // br(X || 0) -> br(X).
35431a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner        return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
35531a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      }
35631a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner
35731a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      // Emit the LHS as a conditional.  If the LHS conditional is true, we
35831a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      // want to jump to the TrueBlock.
3599615ecb44f549ae9fa2b4db6ff46bc78befbf62cDaniel Dunbar      llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
36031a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
36131a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      EmitBlock(LHSFalse);
36231a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner
36331a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
36431a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner      return;
36531a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner    }
366552f4c45ba4f4a01f86d585edabd871a27829867Chris Lattner  }
367552f4c45ba4f4a01f86d585edabd871a27829867Chris Lattner
368552f4c45ba4f4a01f86d585edabd871a27829867Chris Lattner  if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
369552f4c45ba4f4a01f86d585edabd871a27829867Chris Lattner    // br(!x, t, f) -> br(x, f, t)
370552f4c45ba4f4a01f86d585edabd871a27829867Chris Lattner    if (CondUOp->getOpcode() == UnaryOperator::LNot)
371552f4c45ba4f4a01f86d585edabd871a27829867Chris Lattner      return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
37231a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner  }
37331a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner
37409b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar  if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
37509b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar    // Handle ?: operator.
37609b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar
37709b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar    // Just ignore GNU ?: extension.
37809b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar    if (CondOp->getLHS()) {
37909b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar      // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
38009b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar      llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
38109b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar      llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
38209b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar      EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
38309b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar      EmitBlock(LHSBlock);
38409b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar      EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
38509b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar      EmitBlock(RHSBlock);
38609b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar      EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
38709b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar      return;
38809b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar    }
38909b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar  }
39009b14899039d828094c06ac25d60de62608e57b7Daniel Dunbar
39131a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner  // Emit the code with the fully general case.
39231a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner  llvm::Value *CondV = EvaluateExprAsBool(Cond);
39331a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner  Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
39431a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner}
39531a0984b5cb4af99d2407c0f25bf5af68df681c6Chris Lattner
39688a981b47c7face1b1fdaa9074256245107b9ca9Devang Patel/// getCGRecordLayout - Return record layout info.
39788a981b47c7face1b1fdaa9074256245107b9ca9Devang Patelconst CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
398af31913e48c96fddb45a0fd33f25617546502cbbChris Lattner                                                         QualType Ty) {
3996217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek  const RecordType *RTy = Ty->getAs<RecordType>();
400af31913e48c96fddb45a0fd33f25617546502cbbChris Lattner  assert (RTy && "Unexpected type. RecordType expected here.");
401b84a06e68ffd71da22e3c75b6e4bbdba37816413Devang Patel
402af31913e48c96fddb45a0fd33f25617546502cbbChris Lattner  return CGT.getCGRecordLayout(RTy->getDecl());
403b84a06e68ffd71da22e3c75b6e4bbdba37816413Devang Patel}
404dc5e8268292046114ffe02e48773572a91a310f1Chris Lattner
405488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
406dc5e8268292046114ffe02e48773572a91a310f1Chris Lattner/// specified stmt yet.
40790df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
40890df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                       bool OmitOnError) {
40990df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  CGM.ErrorUnsupported(S, Type, OmitOnError);
410dc5e8268292046114ffe02e48773572a91a310f1Chris Lattner}
411dc5e8268292046114ffe02e48773572a91a310f1Chris Lattner
4120ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbarunsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
4130ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar  // Use LabelIDs.size() as the new ID if one hasn't been assigned.
4140ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar  return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
4150ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar}
4160ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar
41788207c9ca218486b93ae7df14e9764cd0c2c3383Chris Lattnervoid CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
41896e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
4193d8400d9a61aa4b63ff35e5cede405b32a41425eAnders Carlsson  if (DestPtr->getType() != BP)
4203d8400d9a61aa4b63ff35e5cede405b32a41425eAnders Carlsson    DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
4213d8400d9a61aa4b63ff35e5cede405b32a41425eAnders Carlsson
4223d8400d9a61aa4b63ff35e5cede405b32a41425eAnders Carlsson  // Get size and alignment info for this aggregate.
4233d8400d9a61aa4b63ff35e5cede405b32a41425eAnders Carlsson  std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
4243d8400d9a61aa4b63ff35e5cede405b32a41425eAnders Carlsson
42588207c9ca218486b93ae7df14e9764cd0c2c3383Chris Lattner  // Don't bother emitting a zero-byte memset.
42688207c9ca218486b93ae7df14e9764cd0c2c3383Chris Lattner  if (TypeInfo.first == 0)
42788207c9ca218486b93ae7df14e9764cd0c2c3383Chris Lattner    return;
42888207c9ca218486b93ae7df14e9764cd0c2c3383Chris Lattner
4293d8400d9a61aa4b63ff35e5cede405b32a41425eAnders Carlsson  // FIXME: Handle variable sized types.
43096e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
4313d8400d9a61aa4b63ff35e5cede405b32a41425eAnders Carlsson
4323d8400d9a61aa4b63ff35e5cede405b32a41425eAnders Carlsson  Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
43369243825cb5c91ec7207256aa57ae327cfaf8cb2Owen Anderson                      getLLVMContext().getNullValue(llvm::Type::Int8Ty),
4343d8400d9a61aa4b63ff35e5cede405b32a41425eAnders Carlsson                      // TypeInfo.first describes size in bits.
4354a28d5deeba33722aa009eab488591fb9055cc7eOwen Anderson                      llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
4364a28d5deeba33722aa009eab488591fb9055cc7eOwen Anderson                      llvm::ConstantInt::get(llvm::Type::Int32Ty,
4373d8400d9a61aa4b63ff35e5cede405b32a41425eAnders Carlsson                                             TypeInfo.second/8));
4383d8400d9a61aa4b63ff35e5cede405b32a41425eAnders Carlsson}
4393d8400d9a61aa4b63ff35e5cede405b32a41425eAnders Carlsson
4400ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbarvoid CodeGenFunction::EmitIndirectSwitches() {
4410ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar  llvm::BasicBlock *Default;
4420ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar
44376526a5245ec2283b0c85fcef507d4c2dec90715Daniel Dunbar  if (IndirectSwitches.empty())
44476526a5245ec2283b0c85fcef507d4c2dec90715Daniel Dunbar    return;
44576526a5245ec2283b0c85fcef507d4c2dec90715Daniel Dunbar
4460ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar  if (!LabelIDs.empty()) {
4470ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar    Default = getBasicBlockForLabel(LabelIDs.begin()->first);
4480ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar  } else {
4490ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar    // No possible targets for indirect goto, just emit an infinite
4500ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar    // loop.
45155e874299f2ad827646a4ca9ea38c402aaeb38c9Daniel Dunbar    Default = createBasicBlock("indirectgoto.loop", CurFn);
4520ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar    llvm::BranchInst::Create(Default, Default);
4530ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar  }
4540ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar
4550ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar  for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
4560ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar         e = IndirectSwitches.end(); i != e; ++i) {
4570ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar    llvm::SwitchInst *I = *i;
4580ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar
4590ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar    I->setSuccessor(0, Default);
4600ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar    for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
4610ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar           LE = LabelIDs.end(); LI != LE; ++LI) {
4624a28d5deeba33722aa009eab488591fb9055cc7eOwen Anderson      I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
4630ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar                                        LI->second),
4640ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar                 getBasicBlockForLabel(LI->first));
4650ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar    }
4660ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar  }
4670ffb125996336fc7602b162c0a9e392f1a93060fDaniel Dunbar}
468ddf7cac45d85b73127adbbd91a2b28fc7291c57eAnders Carlsson
469d286f05f1234bac289173f0eed88d7ecbaea0099Daniel Dunbarllvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
470dcc90d87e6430c643b4311ae5b0089535bca41f7Anders Carlsson  llvm::Value *&SizeEntry = VLASizeMap[VAT];
471dcc90d87e6430c643b4311ae5b0089535bca41f7Anders Carlsson
472f666b7780d04186521adcaedb0e15dfa4d5e6933Anders Carlsson  assert(SizeEntry && "Did not emit size for type");
473f666b7780d04186521adcaedb0e15dfa4d5e6933Anders Carlsson  return SizeEntry;
474f666b7780d04186521adcaedb0e15dfa4d5e6933Anders Carlsson}
475dcc90d87e6430c643b4311ae5b0089535bca41f7Anders Carlsson
476d286f05f1234bac289173f0eed88d7ecbaea0099Daniel Dunbarllvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
47760d35413662ebdcd1d31e34a8a7c665eb6977f1eAnders Carlsson  assert(Ty->isVariablyModifiedType() &&
47860d35413662ebdcd1d31e34a8a7c665eb6977f1eAnders Carlsson         "Must pass variably modified type to EmitVLASizes!");
479f666b7780d04186521adcaedb0e15dfa4d5e6933Anders Carlsson
480d286f05f1234bac289173f0eed88d7ecbaea0099Daniel Dunbar  EnsureInsertPoint();
481d286f05f1234bac289173f0eed88d7ecbaea0099Daniel Dunbar
48260d35413662ebdcd1d31e34a8a7c665eb6977f1eAnders Carlsson  if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
48360d35413662ebdcd1d31e34a8a7c665eb6977f1eAnders Carlsson    llvm::Value *&SizeEntry = VLASizeMap[VAT];
48460d35413662ebdcd1d31e34a8a7c665eb6977f1eAnders Carlsson
485fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson    if (!SizeEntry) {
486fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson      // Get the element size;
487fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson      llvm::Value *ElemSize;
48860d35413662ebdcd1d31e34a8a7c665eb6977f1eAnders Carlsson
489fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson      QualType ElemTy = VAT->getElementType();
49096f214776c0f69069fee4d67557c8c7f416009a8Anders Carlsson
49196f214776c0f69069fee4d67557c8c7f416009a8Anders Carlsson      const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
49296f214776c0f69069fee4d67557c8c7f416009a8Anders Carlsson
493fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson      if (ElemTy->isVariableArrayType())
494fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson        ElemSize = EmitVLASize(ElemTy);
495fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson      else {
4964a28d5deeba33722aa009eab488591fb9055cc7eOwen Anderson        ElemSize = llvm::ConstantInt::get(SizeTy,
497fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson                                          getContext().getTypeSize(ElemTy) / 8);
498fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson      }
49960d35413662ebdcd1d31e34a8a7c665eb6977f1eAnders Carlsson
500fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson      llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
50196f214776c0f69069fee4d67557c8c7f416009a8Anders Carlsson      NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
50296f214776c0f69069fee4d67557c8c7f416009a8Anders Carlsson
503fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson      SizeEntry = Builder.CreateMul(ElemSize, NumElements);
504fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson    }
50560d35413662ebdcd1d31e34a8a7c665eb6977f1eAnders Carlsson
50660d35413662ebdcd1d31e34a8a7c665eb6977f1eAnders Carlsson    return SizeEntry;
507bdad6b69f1214fb20116795f8e8cbf881e3017c6Eli Friedman  } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
508bdad6b69f1214fb20116795f8e8cbf881e3017c6Eli Friedman    EmitVLASize(AT->getElementType());
5096217b80b7a1379b74cced1c076338262c3c980b3Ted Kremenek  } else if (const PointerType *PT = Ty->getAs<PointerType>())
51060d35413662ebdcd1d31e34a8a7c665eb6977f1eAnders Carlsson    EmitVLASize(PT->getPointeeType());
511f666b7780d04186521adcaedb0e15dfa4d5e6933Anders Carlsson  else {
51260d35413662ebdcd1d31e34a8a7c665eb6977f1eAnders Carlsson    assert(0 && "unknown VM type!");
513dcc90d87e6430c643b4311ae5b0089535bca41f7Anders Carlsson  }
51460d35413662ebdcd1d31e34a8a7c665eb6977f1eAnders Carlsson
51560d35413662ebdcd1d31e34a8a7c665eb6977f1eAnders Carlsson  return 0;
516dcc90d87e6430c643b4311ae5b0089535bca41f7Anders Carlsson}
5174fd0aa5803357d8c72eeac2cae15e12649ea08feEli Friedman
5184fd0aa5803357d8c72eeac2cae15e12649ea08feEli Friedmanllvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
5194fd0aa5803357d8c72eeac2cae15e12649ea08feEli Friedman  if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
5204fd0aa5803357d8c72eeac2cae15e12649ea08feEli Friedman    return EmitScalarExpr(E);
5214fd0aa5803357d8c72eeac2cae15e12649ea08feEli Friedman  }
5224fd0aa5803357d8c72eeac2cae15e12649ea08feEli Friedman  return EmitLValue(E).getAddress();
5234fd0aa5803357d8c72eeac2cae15e12649ea08feEli Friedman}
5246ccc47698d0311ddabf32fa0f6db8e4f09ac96f8Anders Carlsson
5256fc559136b8ef98bfb824a0fd49df385405f2879Anders Carlssonvoid CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
5266ccc47698d0311ddabf32fa0f6db8e4f09ac96f8Anders Carlsson{
5276ccc47698d0311ddabf32fa0f6db8e4f09ac96f8Anders Carlsson  CleanupEntries.push_back(CleanupEntry(CleanupBlock));
5286ccc47698d0311ddabf32fa0f6db8e4f09ac96f8Anders Carlsson}
529c71c845fe77ee1f891d60232ec320912d88557eeAnders Carlsson
530c71c845fe77ee1f891d60232ec320912d88557eeAnders Carlssonvoid CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
531c71c845fe77ee1f891d60232ec320912d88557eeAnders Carlsson{
532c71c845fe77ee1f891d60232ec320912d88557eeAnders Carlsson  assert(CleanupEntries.size() >= OldCleanupStackSize &&
533c71c845fe77ee1f891d60232ec320912d88557eeAnders Carlsson         "Cleanup stack mismatch!");
534c71c845fe77ee1f891d60232ec320912d88557eeAnders Carlsson
535c71c845fe77ee1f891d60232ec320912d88557eeAnders Carlsson  while (CleanupEntries.size() > OldCleanupStackSize)
536c71c845fe77ee1f891d60232ec320912d88557eeAnders Carlsson    EmitCleanupBlock();
537c71c845fe77ee1f891d60232ec320912d88557eeAnders Carlsson}
538c71c845fe77ee1f891d60232ec320912d88557eeAnders Carlsson
539bb66f9f2e454135b86462d121629275b6ac38e96Anders CarlssonCodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
540c71c845fe77ee1f891d60232ec320912d88557eeAnders Carlsson{
541bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson  CleanupEntry &CE = CleanupEntries.back();
542bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson
543bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson  llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
544bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson
545bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson  std::vector<llvm::BasicBlock *> Blocks;
546bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson  std::swap(Blocks, CE.Blocks);
547bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson
548bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson  std::vector<llvm::BranchInst *> BranchFixups;
549bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson  std::swap(BranchFixups, CE.BranchFixups);
550bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson
551bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson  CleanupEntries.pop_back();
552bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson
553ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson  // Check if any branch fixups pointed to the scope we just popped. If so,
554ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson  // we can remove them.
555ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson  for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
556ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson    llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
557ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson    BlockScopeMap::iterator I = BlockScopes.find(Dest);
558d66a9f9019c00d889990c947e16a8f019aa2c1f8Anders Carlsson
559ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson    if (I == BlockScopes.end())
560ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson      continue;
5611093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson
562ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson    assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
563d66a9f9019c00d889990c947e16a8f019aa2c1f8Anders Carlsson
564ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson    if (I->second == CleanupEntries.size()) {
565ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson      // We don't need to do this branch fixup.
566ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson      BranchFixups[i] = BranchFixups.back();
567ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson      BranchFixups.pop_back();
568ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson      i--;
569ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson      e--;
570ad9d00e371f4f4e63a540f4e4c501797db2a43deAnders Carlsson      continue;
5711093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson    }
5721093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson  }
573d66a9f9019c00d889990c947e16a8f019aa2c1f8Anders Carlsson
574bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson  llvm::BasicBlock *SwitchBlock = 0;
575bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson  llvm::BasicBlock *EndBlock = 0;
5761093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson  if (!BranchFixups.empty()) {
577bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson    SwitchBlock = createBasicBlock("cleanup.switch");
578bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson    EndBlock = createBasicBlock("cleanup.end");
5791093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson
580bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson    llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
5810ae7b2b2f964bd6145d65ef52dc2a28025b2bd06Anders Carlsson
582bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson    Builder.SetInsertPoint(SwitchBlock);
583bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson
5841093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson    llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
5851093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson                                                "cleanup.dst");
5861093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson    llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
5871093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson
5881093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson    // Create a switch instruction to determine where to jump next.
589bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson    llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
5901093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson                                                BranchFixups.size());
591bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson
59246831a93e1805ddaebd68f37cdb5496a86b44cf0Anders Carlsson    // Restore the current basic block (if any)
5930ae7b2b2f964bd6145d65ef52dc2a28025b2bd06Anders Carlsson    if (CurBB) {
59446831a93e1805ddaebd68f37cdb5496a86b44cf0Anders Carlsson      Builder.SetInsertPoint(CurBB);
5950ae7b2b2f964bd6145d65ef52dc2a28025b2bd06Anders Carlsson
5960ae7b2b2f964bd6145d65ef52dc2a28025b2bd06Anders Carlsson      // If we had a current basic block, we also need to emit an instruction
5970ae7b2b2f964bd6145d65ef52dc2a28025b2bd06Anders Carlsson      // to initialize the cleanup destination.
59869243825cb5c91ec7207256aa57ae327cfaf8cb2Owen Anderson      Builder.CreateStore(getLLVMContext().getNullValue(llvm::Type::Int32Ty),
5990ae7b2b2f964bd6145d65ef52dc2a28025b2bd06Anders Carlsson                          DestCodePtr);
6000ae7b2b2f964bd6145d65ef52dc2a28025b2bd06Anders Carlsson    } else
60146831a93e1805ddaebd68f37cdb5496a86b44cf0Anders Carlsson      Builder.ClearInsertionPoint();
602bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson
6031093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson    for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
6041093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson      llvm::BranchInst *BI = BranchFixups[i];
6051093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson      llvm::BasicBlock *Dest = BI->getSuccessor(0);
6061093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson
6071093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson      // Fixup the branch instruction to point to the cleanup block.
6081093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson      BI->setSuccessor(0, CleanupBlock);
609d66a9f9019c00d889990c947e16a8f019aa2c1f8Anders Carlsson
6101093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson      if (CleanupEntries.empty()) {
611cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson        llvm::ConstantInt *ID;
612cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson
613cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson        // Check if we already have a destination for this block.
614cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson        if (Dest == SI->getDefaultDest())
6154a28d5deeba33722aa009eab488591fb9055cc7eOwen Anderson          ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
616cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson        else {
617cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson          ID = SI->findCaseDest(Dest);
618cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson          if (!ID) {
619cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson            // No code found, get a new unique one by using the number of
620cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson            // switch successors.
6214a28d5deeba33722aa009eab488591fb9055cc7eOwen Anderson            ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
622cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson                                        SI->getNumSuccessors());
623cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson            SI->addCase(ID, Dest);
624cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson          }
625cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson        }
626cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson
627cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson        // Store the jump destination before the branch instruction.
628cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson        new llvm::StoreInst(ID, DestCodePtr, BI);
6291093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson      } else {
6301093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson        // We need to jump through another cleanup block. Create a pad block
6311093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson        // with a branch instruction that jumps to the final destination and
6321093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson        // add it as a branch fixup to the current cleanup scope.
6331093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson
6341093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson        // Create the pad block.
6351093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson        llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
636cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson
637cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson        // Create a unique case ID.
6384a28d5deeba33722aa009eab488591fb9055cc7eOwen Anderson        llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
639cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson                                                       SI->getNumSuccessors());
640cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson
641cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson        // Store the jump destination before the branch instruction.
642cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson        new llvm::StoreInst(ID, DestCodePtr, BI);
643cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson
6441093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson        // Add it as the destination.
645cc8992021caf316a282116d509d2a4fb54349341Anders Carlsson        SI->addCase(ID, CleanupPad);
6461093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson
6471093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson        // Create the branch to the final destination.
6481093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson        llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
6491093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson        CleanupPad->getInstList().push_back(BI);
6501093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson
6511093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson        // And add it as a branch fixup.
6521093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson        CleanupEntries.back().BranchFixups.push_back(BI);
6531093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson      }
6541093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson    }
6551093c2c40a7c262d206d724e912b32cbad2d4e14Anders Carlsson  }
656d66a9f9019c00d889990c947e16a8f019aa2c1f8Anders Carlsson
657bd6fa3d032acd7eafc6c10827c41103df45beab7Anders Carlsson  // Remove all blocks from the block scope map.
658bd6fa3d032acd7eafc6c10827c41103df45beab7Anders Carlsson  for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
659bd6fa3d032acd7eafc6c10827c41103df45beab7Anders Carlsson    assert(BlockScopes.count(Blocks[i]) &&
660bd6fa3d032acd7eafc6c10827c41103df45beab7Anders Carlsson           "Did not find block in scope map!");
661bd6fa3d032acd7eafc6c10827c41103df45beab7Anders Carlsson
662bd6fa3d032acd7eafc6c10827c41103df45beab7Anders Carlsson    BlockScopes.erase(Blocks[i]);
663bd6fa3d032acd7eafc6c10827c41103df45beab7Anders Carlsson  }
664d66a9f9019c00d889990c947e16a8f019aa2c1f8Anders Carlsson
665bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson  return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
666d66a9f9019c00d889990c947e16a8f019aa2c1f8Anders Carlsson}
667d66a9f9019c00d889990c947e16a8f019aa2c1f8Anders Carlsson
668d66a9f9019c00d889990c947e16a8f019aa2c1f8Anders Carlssonvoid CodeGenFunction::EmitCleanupBlock()
669d66a9f9019c00d889990c947e16a8f019aa2c1f8Anders Carlsson{
670bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson  CleanupBlockInfo Info = PopCleanupBlock();
671d66a9f9019c00d889990c947e16a8f019aa2c1f8Anders Carlsson
672eb6437a9b23b3d98a4590ba5557111e14eba2edfAnders Carlsson  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
673eb6437a9b23b3d98a4590ba5557111e14eba2edfAnders Carlsson  if (CurBB && !CurBB->getTerminator() &&
674eb6437a9b23b3d98a4590ba5557111e14eba2edfAnders Carlsson      Info.CleanupBlock->getNumUses() == 0) {
675eb6437a9b23b3d98a4590ba5557111e14eba2edfAnders Carlsson    CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
676eb6437a9b23b3d98a4590ba5557111e14eba2edfAnders Carlsson    delete Info.CleanupBlock;
677eb6437a9b23b3d98a4590ba5557111e14eba2edfAnders Carlsson  } else
678eb6437a9b23b3d98a4590ba5557111e14eba2edfAnders Carlsson    EmitBlock(Info.CleanupBlock);
679d66a9f9019c00d889990c947e16a8f019aa2c1f8Anders Carlsson
680bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson  if (Info.SwitchBlock)
681bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson    EmitBlock(Info.SwitchBlock);
682bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson  if (Info.EndBlock)
683bb66f9f2e454135b86462d121629275b6ac38e96Anders Carlsson    EmitBlock(Info.EndBlock);
684d66a9f9019c00d889990c947e16a8f019aa2c1f8Anders Carlsson}
685d66a9f9019c00d889990c947e16a8f019aa2c1f8Anders Carlsson
68687eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlssonvoid CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
68787eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson{
68887eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson  assert(!CleanupEntries.empty() &&
68987eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson         "Trying to add branch fixup without cleanup block!");
69087eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson
691f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump  // FIXME: We could be more clever here and check if there's already a branch
692f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump  // fixup for this destination and recycle it.
69387eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson  CleanupEntries.back().BranchFixups.push_back(BI);
69487eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson}
69587eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson
69687eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlssonvoid CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
69787eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson{
69846831a93e1805ddaebd68f37cdb5496a86b44cf0Anders Carlsson  if (!HaveInsertPoint())
69946831a93e1805ddaebd68f37cdb5496a86b44cf0Anders Carlsson    return;
70046831a93e1805ddaebd68f37cdb5496a86b44cf0Anders Carlsson
70187eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson  llvm::BranchInst* BI = Builder.CreateBr(Dest);
70287eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson
70346831a93e1805ddaebd68f37cdb5496a86b44cf0Anders Carlsson  Builder.ClearInsertionPoint();
70446831a93e1805ddaebd68f37cdb5496a86b44cf0Anders Carlsson
70587eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson  // The stack is empty, no need to do any cleanup.
70687eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson  if (CleanupEntries.empty())
70787eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson    return;
70887eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson
70987eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson  if (!Dest->getParent()) {
71087eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson    // We are trying to branch to a block that hasn't been inserted yet.
71187eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson    AddBranchFixup(BI);
71287eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson    return;
71387eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson  }
71487eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson
71587eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson  BlockScopeMap::iterator I = BlockScopes.find(Dest);
71687eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson  if (I == BlockScopes.end()) {
71787eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson    // We are trying to jump to a block that is outside of any cleanup scope.
71887eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson    AddBranchFixup(BI);
71987eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson    return;
72087eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson  }
72187eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson
72287eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson  assert(I->second < CleanupEntries.size() &&
72387eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson         "Trying to branch into cleanup region");
72487eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson
72587eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson  if (I->second == CleanupEntries.size() - 1) {
72687eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson    // We have a branch to a block in the same scope.
72787eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson    return;
72887eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson  }
72987eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson
73087eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson  AddBranchFixup(BI);
73187eaf17cc88516277e4389dfa15df93ecfdce559Anders Carlsson}
732