1 //===- LowerInvoke.cpp - Eliminate Invoke & Unwind instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This transformation is designed for use by code generators which do not yet
11 // support stack unwinding. This pass gives them the ability to execute any
12 // program which does not throw an exception, by turning 'invoke' instructions
13 // into calls and by turning 'unwind' instructions into calls to abort().
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Pass.h"
19 #include "llvm/iTerminators.h"
20 #include "llvm/iOther.h"
21 #include "llvm/Module.h"
22 #include "llvm/Type.h"
23 #include "llvm/Constant.h"
24 #include "Support/Statistic.h"
29 Statistic<> NumLowered("lowerinvoke", "Number of invoke & unwinds replaced");
31 class LowerInvoke : public FunctionPass {
34 bool doInitialization(Module &M);
35 bool runOnFunction(Function &F);
38 RegisterOpt<LowerInvoke>
39 X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
42 // Public Interface To the LowerInvoke pass.
43 FunctionPass *createLowerInvokePass() { return new LowerInvoke(); }
45 // doInitialization - Make sure that there is a prototype for abort in the
47 bool LowerInvoke::doInitialization(Module &M) {
48 AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, 0);
52 bool LowerInvoke::runOnFunction(Function &F) {
54 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
55 if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
56 // Insert a normal call instruction...
57 std::string Name = II->getName(); II->setName("");
58 Value *NewCall = new CallInst(II->getCalledValue(),
59 std::vector<Value*>(II->op_begin()+3,
60 II->op_end()), Name,II);
61 II->replaceAllUsesWith(NewCall);
63 // Insert an unconditional branch to the normal destination
64 new BranchInst(II->getNormalDest(), II);
66 // Remove the invoke instruction now.
67 I->getInstList().erase(II);
69 ++NumLowered; Changed = true;
70 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(I->getTerminator())) {
71 // Insert a call to abort()
72 new CallInst(AbortFn, std::vector<Value*>(), "", UI);
74 // Insert a return instruction.
75 new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
76 Constant::getNullValue(F.getReturnType()), UI);
78 // Remove the unwind instruction now.
79 I->getInstList().erase(UI);
81 ++NumLowered; Changed = true;
86 } // End llvm namespace