]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SjLjEHPrepare.cpp
Merge llvm, clang, lld and lldb trunk r291012, and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / CodeGen / SjLjEHPrepare.cpp
1 //===- SjLjEHPrepare.cpp - Eliminate Invoke & Unwind instructions ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This transformation is designed for use by code generators which use SjLj
11 // based exception handling.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/Passes.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 using namespace llvm;
32
33 #define DEBUG_TYPE "sjljehprepare"
34
35 STATISTIC(NumInvokes, "Number of invokes replaced");
36 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
37
38 namespace {
39 class SjLjEHPrepare : public FunctionPass {
40   Type *doubleUnderDataTy;
41   Type *doubleUnderJBufTy;
42   Type *FunctionContextTy;
43   Constant *RegisterFn;
44   Constant *UnregisterFn;
45   Constant *BuiltinSetupDispatchFn;
46   Constant *FrameAddrFn;
47   Constant *StackAddrFn;
48   Constant *StackRestoreFn;
49   Constant *LSDAAddrFn;
50   Constant *CallSiteFn;
51   Constant *FuncCtxFn;
52   AllocaInst *FuncCtx;
53
54 public:
55   static char ID; // Pass identification, replacement for typeid
56   explicit SjLjEHPrepare() : FunctionPass(ID) {}
57   bool doInitialization(Module &M) override;
58   bool runOnFunction(Function &F) override;
59
60   void getAnalysisUsage(AnalysisUsage &AU) const override {}
61   StringRef getPassName() const override {
62     return "SJLJ Exception Handling preparation";
63   }
64
65 private:
66   bool setupEntryBlockAndCallSites(Function &F);
67   void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal, Value *SelVal);
68   Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst *> LPads);
69   void lowerIncomingArguments(Function &F);
70   void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst *> Invokes);
71   void insertCallSiteStore(Instruction *I, int Number);
72 };
73 } // end anonymous namespace
74
75 char SjLjEHPrepare::ID = 0;
76 INITIALIZE_PASS(SjLjEHPrepare, "sjljehprepare", "Prepare SjLj exceptions",
77                 false, false)
78
79 // Public Interface To the SjLjEHPrepare pass.
80 FunctionPass *llvm::createSjLjEHPreparePass() { return new SjLjEHPrepare(); }
81 // doInitialization - Set up decalarations and types needed to process
82 // exceptions.
83 bool SjLjEHPrepare::doInitialization(Module &M) {
84   // Build the function context structure.
85   // builtin_setjmp uses a five word jbuf
86   Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
87   Type *Int32Ty = Type::getInt32Ty(M.getContext());
88   doubleUnderDataTy = ArrayType::get(Int32Ty, 4);
89   doubleUnderJBufTy = ArrayType::get(VoidPtrTy, 5);
90   FunctionContextTy = StructType::get(VoidPtrTy,         // __prev
91                                       Int32Ty,           // call_site
92                                       doubleUnderDataTy, // __data
93                                       VoidPtrTy,         // __personality
94                                       VoidPtrTy,         // __lsda
95                                       doubleUnderJBufTy, // __jbuf
96                                       nullptr);
97
98   return true;
99 }
100
101 /// insertCallSiteStore - Insert a store of the call-site value to the
102 /// function context
103 void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
104   IRBuilder<> Builder(I);
105
106   // Get a reference to the call_site field.
107   Type *Int32Ty = Type::getInt32Ty(I->getContext());
108   Value *Zero = ConstantInt::get(Int32Ty, 0);
109   Value *One = ConstantInt::get(Int32Ty, 1);
110   Value *Idxs[2] = { Zero, One };
111   Value *CallSite =
112       Builder.CreateGEP(FunctionContextTy, FuncCtx, Idxs, "call_site");
113
114   // Insert a store of the call-site number
115   ConstantInt *CallSiteNoC =
116       ConstantInt::get(Type::getInt32Ty(I->getContext()), Number);
117   Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);
118 }
119
120 /// MarkBlocksLiveIn - Insert BB and all of its predecessors into LiveBBs until
121 /// we reach blocks we've already seen.
122 static void MarkBlocksLiveIn(BasicBlock *BB,
123                              SmallPtrSetImpl<BasicBlock *> &LiveBBs) {
124   if (!LiveBBs.insert(BB).second)
125     return; // already been here.
126
127   for (BasicBlock *PredBB : predecessors(BB))
128     MarkBlocksLiveIn(PredBB, LiveBBs);
129 }
130
131 /// substituteLPadValues - Substitute the values returned by the landingpad
132 /// instruction with those returned by the personality function.
133 void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
134                                          Value *SelVal) {
135   SmallVector<Value *, 8> UseWorkList(LPI->user_begin(), LPI->user_end());
136   while (!UseWorkList.empty()) {
137     Value *Val = UseWorkList.pop_back_val();
138     auto *EVI = dyn_cast<ExtractValueInst>(Val);
139     if (!EVI)
140       continue;
141     if (EVI->getNumIndices() != 1)
142       continue;
143     if (*EVI->idx_begin() == 0)
144       EVI->replaceAllUsesWith(ExnVal);
145     else if (*EVI->idx_begin() == 1)
146       EVI->replaceAllUsesWith(SelVal);
147     if (EVI->use_empty())
148       EVI->eraseFromParent();
149   }
150
151   if (LPI->use_empty())
152     return;
153
154   // There are still some uses of LPI. Construct an aggregate with the exception
155   // values and replace the LPI with that aggregate.
156   Type *LPadType = LPI->getType();
157   Value *LPadVal = UndefValue::get(LPadType);
158   auto *SelI = cast<Instruction>(SelVal);
159   IRBuilder<> Builder(SelI->getParent(), std::next(SelI->getIterator()));
160   LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
161   LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
162
163   LPI->replaceAllUsesWith(LPadVal);
164 }
165
166 /// setupFunctionContext - Allocate the function context on the stack and fill
167 /// it with all of the data that we know at this point.
168 Value *SjLjEHPrepare::setupFunctionContext(Function &F,
169                                            ArrayRef<LandingPadInst *> LPads) {
170   BasicBlock *EntryBB = &F.front();
171
172   // Create an alloca for the incoming jump buffer ptr and the new jump buffer
173   // that needs to be restored on all exits from the function. This is an alloca
174   // because the value needs to be added to the global context list.
175   auto &DL = F.getParent()->getDataLayout();
176   unsigned Align = DL.getPrefTypeAlignment(FunctionContextTy);
177   FuncCtx = new AllocaInst(FunctionContextTy, nullptr, Align, "fn_context",
178                            &EntryBB->front());
179
180   // Fill in the function context structure.
181   for (LandingPadInst *LPI : LPads) {
182     IRBuilder<> Builder(LPI->getParent(),
183                         LPI->getParent()->getFirstInsertionPt());
184
185     // Reference the __data field.
186     Value *FCData =
187         Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 2, "__data");
188
189     // The exception values come back in context->__data[0].
190     Value *ExceptionAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
191                                                       0, 0, "exception_gep");
192     Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
193     ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
194
195     Value *SelectorAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
196                                                      0, 1, "exn_selector_gep");
197     Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
198
199     substituteLPadValues(LPI, ExnVal, SelVal);
200   }
201
202   // Personality function
203   IRBuilder<> Builder(EntryBB->getTerminator());
204   Value *PersonalityFn = F.getPersonalityFn();
205   Value *PersonalityFieldPtr = Builder.CreateConstGEP2_32(
206       FunctionContextTy, FuncCtx, 0, 3, "pers_fn_gep");
207   Builder.CreateStore(
208       Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
209       PersonalityFieldPtr, /*isVolatile=*/true);
210
211   // LSDA address
212   Value *LSDA = Builder.CreateCall(LSDAAddrFn, {}, "lsda_addr");
213   Value *LSDAFieldPtr =
214       Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 4, "lsda_gep");
215   Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
216
217   return FuncCtx;
218 }
219
220 /// lowerIncomingArguments - To avoid having to handle incoming arguments
221 /// specially, we lower each arg to a copy instruction in the entry block. This
222 /// ensures that the argument value itself cannot be live out of the entry
223 /// block.
224 void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
225   BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
226   while (isa<AllocaInst>(AfterAllocaInsPt) &&
227          cast<AllocaInst>(AfterAllocaInsPt)->isStaticAlloca())
228     ++AfterAllocaInsPt;
229   assert(AfterAllocaInsPt != F.front().end());
230
231   for (auto &AI : F.args()) {
232     Type *Ty = AI.getType();
233
234     // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
235     Value *TrueValue = ConstantInt::getTrue(F.getContext());
236     Value *UndefValue = UndefValue::get(Ty);
237     Instruction *SI = SelectInst::Create(
238         TrueValue, &AI, UndefValue, AI.getName() + ".tmp", &*AfterAllocaInsPt);
239     AI.replaceAllUsesWith(SI);
240
241     // Reset the operand, because it  was clobbered by the RAUW above.
242     SI->setOperand(1, &AI);
243   }
244 }
245
246 /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
247 /// edge and spill them.
248 void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
249                                            ArrayRef<InvokeInst *> Invokes) {
250   // Finally, scan the code looking for instructions with bad live ranges.
251   for (BasicBlock &BB : F) {
252     for (Instruction &Inst : BB) {
253       // Ignore obvious cases we don't have to handle. In particular, most
254       // instructions either have no uses or only have a single use inside the
255       // current block. Ignore them quickly.
256       if (Inst.use_empty())
257         continue;
258       if (Inst.hasOneUse() &&
259           cast<Instruction>(Inst.user_back())->getParent() == &BB &&
260           !isa<PHINode>(Inst.user_back()))
261         continue;
262
263       // If this is an alloca in the entry block, it's not a real register
264       // value.
265       if (auto *AI = dyn_cast<AllocaInst>(&Inst))
266         if (AI->isStaticAlloca())
267           continue;
268
269       // Avoid iterator invalidation by copying users to a temporary vector.
270       SmallVector<Instruction *, 16> Users;
271       for (User *U : Inst.users()) {
272         Instruction *UI = cast<Instruction>(U);
273         if (UI->getParent() != &BB || isa<PHINode>(UI))
274           Users.push_back(UI);
275       }
276
277       // Find all of the blocks that this value is live in.
278       SmallPtrSet<BasicBlock *, 32> LiveBBs;
279       LiveBBs.insert(&BB);
280       while (!Users.empty()) {
281         Instruction *U = Users.pop_back_val();
282
283         if (!isa<PHINode>(U)) {
284           MarkBlocksLiveIn(U->getParent(), LiveBBs);
285         } else {
286           // Uses for a PHI node occur in their predecessor block.
287           PHINode *PN = cast<PHINode>(U);
288           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
289             if (PN->getIncomingValue(i) == &Inst)
290               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
291         }
292       }
293
294       // Now that we know all of the blocks that this thing is live in, see if
295       // it includes any of the unwind locations.
296       bool NeedsSpill = false;
297       for (InvokeInst *Invoke : Invokes) {
298         BasicBlock *UnwindBlock = Invoke->getUnwindDest();
299         if (UnwindBlock != &BB && LiveBBs.count(UnwindBlock)) {
300           DEBUG(dbgs() << "SJLJ Spill: " << Inst << " around "
301                        << UnwindBlock->getName() << "\n");
302           NeedsSpill = true;
303           break;
304         }
305       }
306
307       // If we decided we need a spill, do it.
308       // FIXME: Spilling this way is overkill, as it forces all uses of
309       // the value to be reloaded from the stack slot, even those that aren't
310       // in the unwind blocks. We should be more selective.
311       if (NeedsSpill) {
312         DemoteRegToStack(Inst, true);
313         ++NumSpilled;
314       }
315     }
316   }
317
318   // Go through the landing pads and remove any PHIs there.
319   for (InvokeInst *Invoke : Invokes) {
320     BasicBlock *UnwindBlock = Invoke->getUnwindDest();
321     LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
322
323     // Place PHIs into a set to avoid invalidating the iterator.
324     SmallPtrSet<PHINode *, 8> PHIsToDemote;
325     for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
326       PHIsToDemote.insert(cast<PHINode>(PN));
327     if (PHIsToDemote.empty())
328       continue;
329
330     // Demote the PHIs to the stack.
331     for (PHINode *PN : PHIsToDemote)
332       DemotePHIToStack(PN);
333
334     // Move the landingpad instruction back to the top of the landing pad block.
335     LPI->moveBefore(&UnwindBlock->front());
336   }
337 }
338
339 /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
340 /// the function context and marking the call sites with the appropriate
341 /// values. These values are used by the DWARF EH emitter.
342 bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
343   SmallVector<ReturnInst *, 16> Returns;
344   SmallVector<InvokeInst *, 16> Invokes;
345   SmallSetVector<LandingPadInst *, 16> LPads;
346
347   // Look through the terminators of the basic blocks to find invokes.
348   for (BasicBlock &BB : F)
349     if (auto *II = dyn_cast<InvokeInst>(BB.getTerminator())) {
350       if (Function *Callee = II->getCalledFunction())
351         if (Callee->getIntrinsicID() == Intrinsic::donothing) {
352           // Remove the NOP invoke.
353           BranchInst::Create(II->getNormalDest(), II);
354           II->eraseFromParent();
355           continue;
356         }
357
358       Invokes.push_back(II);
359       LPads.insert(II->getUnwindDest()->getLandingPadInst());
360     } else if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
361       Returns.push_back(RI);
362     }
363
364   if (Invokes.empty())
365     return false;
366
367   NumInvokes += Invokes.size();
368
369   lowerIncomingArguments(F);
370   lowerAcrossUnwindEdges(F, Invokes);
371
372   Value *FuncCtx =
373       setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
374   BasicBlock *EntryBB = &F.front();
375   IRBuilder<> Builder(EntryBB->getTerminator());
376
377   // Get a reference to the jump buffer.
378   Value *JBufPtr =
379       Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 5, "jbuf_gep");
380
381   // Save the frame pointer.
382   Value *FramePtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 0,
383                                                "jbuf_fp_gep");
384
385   Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
386   Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
387
388   // Save the stack pointer.
389   Value *StackPtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 2,
390                                                "jbuf_sp_gep");
391
392   Val = Builder.CreateCall(StackAddrFn, {}, "sp");
393   Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
394
395   // Call the setup_dispatch instrinsic. It fills in the rest of the jmpbuf.
396   Builder.CreateCall(BuiltinSetupDispatchFn, {});
397
398   // Store a pointer to the function context so that the back-end will know
399   // where to look for it.
400   Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
401   Builder.CreateCall(FuncCtxFn, FuncCtxArg);
402
403   // At this point, we are all set up, update the invoke instructions to mark
404   // their call_site values.
405   for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
406     insertCallSiteStore(Invokes[I], I + 1);
407
408     ConstantInt *CallSiteNum =
409         ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
410
411     // Record the call site value for the back end so it stays associated with
412     // the invoke.
413     CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
414   }
415
416   // Mark call instructions that aren't nounwind as no-action (call_site ==
417   // -1). Skip the entry block, as prior to then, no function context has been
418   // created for this function and any unexpected exceptions thrown will go
419   // directly to the caller's context, which is what we want anyway, so no need
420   // to do anything here.
421   for (BasicBlock &BB : F) {
422     if (&BB == &F.front())
423       continue;
424     for (Instruction &I : BB)
425       if (I.mayThrow())
426         insertCallSiteStore(&I, -1);
427   }
428
429   // Register the function context and make sure it's known to not throw
430   CallInst *Register =
431       CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
432   Register->setDoesNotThrow();
433
434   // Following any allocas not in the entry block, update the saved SP in the
435   // jmpbuf to the new value.
436   for (BasicBlock &BB : F) {
437     if (&BB == &F.front())
438       continue;
439     for (Instruction &I : BB) {
440       if (auto *CI = dyn_cast<CallInst>(&I)) {
441         if (CI->getCalledFunction() != StackRestoreFn)
442           continue;
443       } else if (!isa<AllocaInst>(&I)) {
444         continue;
445       }
446       Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
447       StackAddr->insertAfter(&I);
448       Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
449       StoreStackAddr->insertAfter(StackAddr);
450     }
451   }
452
453   // Finally, for any returns from this function, if this function contains an
454   // invoke, add a call to unregister the function context.
455   for (ReturnInst *Return : Returns)
456     CallInst::Create(UnregisterFn, FuncCtx, "", Return);
457
458   return true;
459 }
460
461 bool SjLjEHPrepare::runOnFunction(Function &F) {
462   Module &M = *F.getParent();
463   RegisterFn = M.getOrInsertFunction(
464       "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
465       PointerType::getUnqual(FunctionContextTy), nullptr);
466   UnregisterFn = M.getOrInsertFunction(
467       "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
468       PointerType::getUnqual(FunctionContextTy), nullptr);
469   FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
470   StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
471   StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
472   BuiltinSetupDispatchFn =
473     Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setup_dispatch);
474   LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
475   CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
476   FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
477
478   bool Res = setupEntryBlockAndCallSites(F);
479   return Res;
480 }