aboutsummaryrefslogtreecommitdiff
path: root/lib/Transforms/Utils/LowerInvoke.cpp
blob: bd9c8bcc3e3d4ece48745d5ba7d27f53735646cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
//===- LowerInvoke.cpp - Eliminate Invoke & Unwind instructions -----------===//
// 
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
// 
//===----------------------------------------------------------------------===//
//
// This transformation is designed for use by code generators which do not yet
// support stack unwinding.  This pass supports two models of exception handling
// lowering, the 'cheap' support and the 'expensive' support.
//
// 'Cheap' exception handling support gives the program the ability to execute
// any program which does not "throw an exception", by turning 'invoke'
// instructions into calls and by turning 'unwind' instructions into calls to
// abort().  If the program does dynamically use the unwind instruction, the
// program will print a message then abort.
//
// 'Expensive' exception handling support gives the full exception handling
// support to the program at making the 'invoke' instruction really expensive.
// It basically inserts setjmp/longjmp calls to emulate the exception handling
// as necessary.
//
// Because the 'expensive' support slows down programs a lot, and EH is only
// used for a subset of the programs, it must be specifically enabled by an
// option.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "Support/Statistic.h"
#include "Support/CommandLine.h"
#include <csetjmp>
using namespace llvm;

namespace {
  Statistic<> NumLowered("lowerinvoke", "Number of invoke & unwinds replaced");
  cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support", 
 cl::desc("Make the -lowerinvoke pass insert expensive, but correct, EH code"));

  class LowerInvoke : public FunctionPass {
    // Used for both models.
    Function *WriteFn;
    Function *AbortFn;
    Value *AbortMessage;
    unsigned AbortMessageLength;

    // Used for expensive EH support.
    const Type *JBLinkTy;
    GlobalVariable *JBListHead;
    Function *SetJmpFn, *LongJmpFn;
  public:
    bool doInitialization(Module &M);
    bool runOnFunction(Function &F);
  private:
    bool insertCheapEHSupport(Function &F);
    bool insertExpensiveEHSupport(Function &F);
  };

  RegisterOpt<LowerInvoke>
  X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
}

// Public Interface To the LowerInvoke pass.
FunctionPass *llvm::createLowerInvokePass() { return new LowerInvoke(); }

// doInitialization - Make sure that there is a prototype for abort in the
// current module.
bool LowerInvoke::doInitialization(Module &M) {
  const Type *VoidPtrTy = PointerType::get(Type::SByteTy);
  if (ExpensiveEHSupport) {
    // Insert a type for the linked list of jump buffers.  Unfortunately, we
    // don't know the size of the target's setjmp buffer, so we make a guess.
    // If this guess turns out to be too small, bad stuff could happen.
    unsigned JmpBufSize = 200;  // PPC has 192 words
    assert(sizeof(jmp_buf) <= JmpBufSize*sizeof(void*) &&
       "LowerInvoke doesn't know about targets with jmp_buf size > 200 words!");
    const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JmpBufSize);

    { // The type is recursive, so use a type holder.
      std::vector<const Type*> Elements;
      OpaqueType *OT = OpaqueType::get();
      Elements.push_back(PointerType::get(OT));
      Elements.push_back(JmpBufTy);
      PATypeHolder JBLType(StructType::get(Elements));
      OT->refineAbstractTypeTo(JBLType.get());  // Complete the cycle.
      JBLinkTy = JBLType.get();
    }

    const Type *PtrJBList = PointerType::get(JBLinkTy);

    // Now that we've done that, insert the jmpbuf list head global, unless it
    // already exists.
    if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList)))
      JBListHead = new GlobalVariable(PtrJBList, false,
                                      GlobalValue::LinkOnceLinkage,
                                      Constant::getNullValue(PtrJBList),
                                      "llvm.sjljeh.jblist", &M);
    SetJmpFn = M.getOrInsertFunction("setjmp", Type::IntTy,
                                     PointerType::get(JmpBufTy), 0);
    LongJmpFn = M.getOrInsertFunction("longjmp", Type::VoidTy,
                                      PointerType::get(JmpBufTy),
                                      Type::IntTy, 0);
    
    // The abort message for expensive EH support tells the user that the
    // program 'unwound' without an 'invoke' instruction.
    Constant *Msg =
      ConstantArray::get("ERROR: Exception thrown, but not caught!\n");
    AbortMessageLength = Msg->getNumOperands()-1;  // don't include \0
  
    GlobalVariable *MsgGV = M.getGlobalVariable("abort.msg", Msg->getType());
    if (MsgGV && (!MsgGV->hasInitializer() || MsgGV->getInitializer() != Msg))
      MsgGV = 0;
    if (!MsgGV)
      MsgGV = new GlobalVariable(Msg->getType(), true,
                                 GlobalValue::InternalLinkage,
                                 Msg, "abort.msg", &M);
    std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
    AbortMessage =
      ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);

  } else {
    // The abort message for cheap EH support tells the user that EH is not
    // enabled.
    Constant *Msg =
      ConstantArray::get("Exception handler needed, but not enabled.  Recompile"
                         " program with -enable-correct-eh-support.\n");
    AbortMessageLength = Msg->getNumOperands()-1;  // don't include \0
  
    GlobalVariable *MsgGV = M.getGlobalVariable("abort.msg", Msg->getType());
    if (MsgGV && (!MsgGV->hasInitializer() || MsgGV->getInitializer() != Msg))
      MsgGV = 0;

    if (!MsgGV)
      MsgGV = new GlobalVariable(Msg->getType(), true,
                                 GlobalValue::InternalLinkage,
                                 Msg, "abort.msg", &M);
    std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
    AbortMessage =
      ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
  }

  // We need the 'write' and 'abort' functions for both models.
  WriteFn = M.getOrInsertFunction("write", Type::VoidTy, Type::IntTy,
                                  VoidPtrTy, Type::IntTy, 0);
  AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, 0);
  return true;
}

bool LowerInvoke::insertCheapEHSupport(Function &F) {
  bool Changed = false;
  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
    if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
      // Insert a normal call instruction...
      std::string Name = II->getName(); II->setName("");
      Value *NewCall = new CallInst(II->getCalledValue(),
                                    std::vector<Value*>(II->op_begin()+3,
                                                        II->op_end()), Name,II);
      II->replaceAllUsesWith(NewCall);
      
      // Insert an unconditional branch to the normal destination.
      new BranchInst(II->getNormalDest(), II);

      // Remove any PHI node entries from the exception destination.
      II->getExceptionalDest()->removePredecessor(BB);

      // Remove the invoke instruction now.
      BB->getInstList().erase(II);

      ++NumLowered; Changed = true;
    } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
      // Insert a new call to write(2, AbortMessage, AbortMessageLength);
      std::vector<Value*> Args;
      Args.push_back(ConstantInt::get(Type::IntTy, 2));
      Args.push_back(AbortMessage);
      Args.push_back(ConstantInt::get(Type::IntTy, AbortMessageLength));
      new CallInst(WriteFn, Args, "", UI);

      // Insert a call to abort()
      new CallInst(AbortFn, std::vector<Value*>(), "", UI);

      // Insert a return instruction.  This really should be a "barrier", as it
      // is unreachable.
      new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
                            Constant::getNullValue(F.getReturnType()), UI);

      // Remove the unwind instruction now.
      BB->getInstList().erase(UI);

      ++NumLowered; Changed = true;
    }
  return Changed;
}

bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
  bool Changed = false;

  // If a function uses invoke, we have an alloca for the jump buffer.
  AllocaInst *JmpBuf = 0;

  // If this function contains an unwind instruction, two blocks get added: one
  // to actually perform the longjmp, and one to terminate the program if there
  // is no handler.
  BasicBlock *UnwindBlock = 0, *TermBlock = 0;
  std::vector<LoadInst*> JBPtrs;

  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
    if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
      if (JmpBuf == 0)
        JmpBuf <