526 lines · cpp
1//===- SjLjEHPrepare.cpp - Eliminate Invoke & Unwind instructions ---------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// This transformation is designed for use by code generators which use SjLj10// based exception handling.11//12//===----------------------------------------------------------------------===//13 14#include "llvm/CodeGen/SjLjEHPrepare.h"15#include "llvm/ADT/SetVector.h"16#include "llvm/ADT/SmallPtrSet.h"17#include "llvm/ADT/SmallVector.h"18#include "llvm/ADT/Statistic.h"19#include "llvm/CodeGen/Passes.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/InitializePasses.h"28#include "llvm/Pass.h"29#include "llvm/Support/Debug.h"30#include "llvm/Support/raw_ostream.h"31#include "llvm/Target/TargetMachine.h"32#include "llvm/Transforms/Utils/Local.h"33using namespace llvm;34 35#define DEBUG_TYPE "sjlj-eh-prepare"36 37STATISTIC(NumInvokes, "Number of invokes replaced");38STATISTIC(NumSpilled, "Number of registers live across unwind edges");39 40namespace {41class SjLjEHPrepareImpl {42 IntegerType *DataTy = nullptr;43 Type *doubleUnderDataTy = nullptr;44 Type *doubleUnderJBufTy = nullptr;45 Type *FunctionContextTy = nullptr;46 FunctionCallee RegisterFn;47 FunctionCallee UnregisterFn;48 Function *BuiltinSetupDispatchFn = nullptr;49 Function *FrameAddrFn = nullptr;50 Function *StackAddrFn = nullptr;51 Function *StackRestoreFn = nullptr;52 Function *LSDAAddrFn = nullptr;53 Function *CallSiteFn = nullptr;54 Function *FuncCtxFn = nullptr;55 AllocaInst *FuncCtx = nullptr;56 const TargetMachine *TM = nullptr;57 58public:59 explicit SjLjEHPrepareImpl(const TargetMachine *TM = nullptr) : TM(TM) {}60 bool doInitialization(Module &M);61 bool runOnFunction(Function &F);62 63private:64 bool setupEntryBlockAndCallSites(Function &F);65 void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal, Value *SelVal);66 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst *> LPads);67 void lowerIncomingArguments(Function &F);68 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst *> Invokes);69 void insertCallSiteStore(Instruction *I, int Number);70};71 72class SjLjEHPrepare : public FunctionPass {73 SjLjEHPrepareImpl Impl;74 75public:76 static char ID; // Pass identification, replacement for typeid77 explicit SjLjEHPrepare(const TargetMachine *TM = nullptr)78 : FunctionPass(ID), Impl(TM) {}79 bool doInitialization(Module &M) override { return Impl.doInitialization(M); }80 bool runOnFunction(Function &F) override { return Impl.runOnFunction(F); };81 82 StringRef getPassName() const override {83 return "SJLJ Exception Handling preparation";84 }85};86 87} // end anonymous namespace88 89PreservedAnalyses SjLjEHPreparePass::run(Function &F,90 FunctionAnalysisManager &FAM) {91 SjLjEHPrepareImpl Impl(TM);92 Impl.doInitialization(*F.getParent());93 bool Changed = Impl.runOnFunction(F);94 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();95}96 97char SjLjEHPrepare::ID = 0;98INITIALIZE_PASS(SjLjEHPrepare, DEBUG_TYPE, "Prepare SjLj exceptions",99 false, false)100 101// Public Interface To the SjLjEHPrepare pass.102FunctionPass *llvm::createSjLjEHPreparePass(const TargetMachine *TM) {103 return new SjLjEHPrepare(TM);104}105 106// doInitialization - Set up decalarations and types needed to process107// exceptions.108bool SjLjEHPrepareImpl::doInitialization(Module &M) {109 // Build the function context structure.110 // builtin_setjmp uses a five word jbuf111 Type *VoidPtrTy = PointerType::getUnqual(M.getContext());112 unsigned DataBits =113 TM ? TM->getSjLjDataSize() : TargetMachine::DefaultSjLjDataSize;114 DataTy = Type::getIntNTy(M.getContext(), DataBits);115 doubleUnderDataTy = ArrayType::get(DataTy, 4);116 doubleUnderJBufTy = ArrayType::get(VoidPtrTy, 5);117 FunctionContextTy = StructType::get(VoidPtrTy, // __prev118 DataTy, // call_site119 doubleUnderDataTy, // __data120 VoidPtrTy, // __personality121 VoidPtrTy, // __lsda122 doubleUnderJBufTy // __jbuf123 );124 125 return false;126}127 128/// insertCallSiteStore - Insert a store of the call-site value to the129/// function context130void SjLjEHPrepareImpl::insertCallSiteStore(Instruction *I, int Number) {131 IRBuilder<> Builder(I);132 133 // Get a reference to the call_site field.134 Type *Int32Ty = Type::getInt32Ty(I->getContext());135 Value *Zero = ConstantInt::get(Int32Ty, 0);136 Value *One = ConstantInt::get(Int32Ty, 1);137 Value *Idxs[2] = { Zero, One };138 Value *CallSite =139 Builder.CreateGEP(FunctionContextTy, FuncCtx, Idxs, "call_site");140 141 // Insert a store of the call-site number142 ConstantInt *CallSiteNoC = ConstantInt::get(DataTy, Number);143 Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);144}145 146/// MarkBlocksLiveIn - Insert BB and all of its predecessors into LiveBBs until147/// we reach blocks we've already seen.148static void MarkBlocksLiveIn(BasicBlock *BB,149 SmallPtrSetImpl<BasicBlock *> &LiveBBs) {150 if (!LiveBBs.insert(BB).second)151 return; // already been here.152 153 LiveBBs.insert_range(inverse_depth_first(BB));154}155 156/// substituteLPadValues - Substitute the values returned by the landingpad157/// instruction with those returned by the personality function.158void SjLjEHPrepareImpl::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,159 Value *SelVal) {160 SmallVector<Value *, 8> UseWorkList(LPI->users());161 while (!UseWorkList.empty()) {162 Value *Val = UseWorkList.pop_back_val();163 auto *EVI = dyn_cast<ExtractValueInst>(Val);164 if (!EVI)165 continue;166 if (EVI->getNumIndices() != 1)167 continue;168 if (*EVI->idx_begin() == 0)169 EVI->replaceAllUsesWith(ExnVal);170 else if (*EVI->idx_begin() == 1)171 EVI->replaceAllUsesWith(SelVal);172 if (EVI->use_empty())173 EVI->eraseFromParent();174 }175 176 if (LPI->use_empty())177 return;178 179 // There are still some uses of LPI. Construct an aggregate with the exception180 // values and replace the LPI with that aggregate.181 Type *LPadType = LPI->getType();182 Value *LPadVal = PoisonValue::get(LPadType);183 auto *SelI = cast<Instruction>(SelVal);184 IRBuilder<> Builder(SelI->getParent(), std::next(SelI->getIterator()));185 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");186 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");187 188 LPI->replaceAllUsesWith(LPadVal);189}190 191/// setupFunctionContext - Allocate the function context on the stack and fill192/// it with all of the data that we know at this point.193Value *194SjLjEHPrepareImpl::setupFunctionContext(Function &F,195 ArrayRef<LandingPadInst *> LPads) {196 BasicBlock *EntryBB = &F.front();197 198 // Create an alloca for the incoming jump buffer ptr and the new jump buffer199 // that needs to be restored on all exits from the function. This is an alloca200 // because the value needs to be added to the global context list.201 auto &DL = F.getDataLayout();202 const Align Alignment = DL.getPrefTypeAlign(FunctionContextTy);203 FuncCtx = new AllocaInst(FunctionContextTy, DL.getAllocaAddrSpace(), nullptr,204 Alignment, "fn_context", EntryBB->begin());205 206 // Fill in the function context structure.207 for (LandingPadInst *LPI : LPads) {208 IRBuilder<> Builder(LPI->getParent(),209 LPI->getParent()->getFirstInsertionPt());210 211 // Reference the __data field.212 Value *FCData =213 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 2, "__data");214 215 // The exception values come back in context->__data[0].216 Value *ExceptionAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,217 0, 0, "exception_gep");218 Value *ExnVal = Builder.CreateLoad(DataTy, ExceptionAddr, true, "exn_val");219 ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getPtrTy());220 221 Value *SelectorAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,222 0, 1, "exn_selector_gep");223 Value *SelVal =224 Builder.CreateLoad(DataTy, SelectorAddr, true, "exn_selector_val");225 226 // SelVal must be Int32Ty, so trunc it227 SelVal = Builder.CreateTrunc(SelVal, Type::getInt32Ty(F.getContext()));228 229 substituteLPadValues(LPI, ExnVal, SelVal);230 }231 232 // Personality function233 IRBuilder<> Builder(EntryBB->getTerminator());234 Value *PersonalityFn = F.getPersonalityFn();235 Value *PersonalityFieldPtr = Builder.CreateConstGEP2_32(236 FunctionContextTy, FuncCtx, 0, 3, "pers_fn_gep");237 Builder.CreateStore(PersonalityFn, PersonalityFieldPtr, /*isVolatile=*/true);238 239 // LSDA address240 Value *LSDA = Builder.CreateCall(LSDAAddrFn, {}, "lsda_addr");241 Value *LSDAFieldPtr =242 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 4, "lsda_gep");243 Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);244 245 return FuncCtx;246}247 248/// lowerIncomingArguments - To avoid having to handle incoming arguments249/// specially, we lower each arg to a copy instruction in the entry block. This250/// ensures that the argument value itself cannot be live out of the entry251/// block.252void SjLjEHPrepareImpl::lowerIncomingArguments(Function &F) {253 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();254 while (isa<AllocaInst>(AfterAllocaInsPt) &&255 cast<AllocaInst>(AfterAllocaInsPt)->isStaticAlloca())256 ++AfterAllocaInsPt;257 assert(AfterAllocaInsPt != F.front().end());258 259 for (auto &AI : F.args()) {260 // Swift error really is a register that we model as memory -- instruction261 // selection will perform mem-to-reg for us and spill/reload appropriately262 // around calls that clobber it. There is no need to spill this263 // value to the stack and doing so would not be allowed.264 if (AI.isSwiftError())265 continue;266 267 Type *Ty = AI.getType();268 269 // Use 'select i8 true, %arg, poison' to simulate a 'no-op' instruction.270 Value *TrueValue = ConstantInt::getTrue(F.getContext());271 Value *PoisonValue = PoisonValue::get(Ty);272 Instruction *SI = SelectInst::Create(273 TrueValue, &AI, PoisonValue, AI.getName() + ".tmp", AfterAllocaInsPt);274 AI.replaceAllUsesWith(SI);275 276 // Reset the operand, because it was clobbered by the RAUW above.277 SI->setOperand(1, &AI);278 }279}280 281/// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind282/// edge and spill them.283void SjLjEHPrepareImpl::lowerAcrossUnwindEdges(Function &F,284 ArrayRef<InvokeInst *> Invokes) {285 // Finally, scan the code looking for instructions with bad live ranges.286 for (BasicBlock &BB : F) {287 for (Instruction &Inst : BB) {288 // Ignore obvious cases we don't have to handle. In particular, most289 // instructions either have no uses or only have a single use inside the290 // current block. Ignore them quickly.291 if (Inst.use_empty())292 continue;293 if (Inst.hasOneUse() &&294 cast<Instruction>(Inst.user_back())->getParent() == &BB &&295 !isa<PHINode>(Inst.user_back()))296 continue;297 298 // If this is an alloca in the entry block, it's not a real register299 // value.300 if (auto *AI = dyn_cast<AllocaInst>(&Inst))301 if (AI->isStaticAlloca())302 continue;303 304 // Avoid iterator invalidation by copying users to a temporary vector.305 SmallVector<Instruction *, 16> Users;306 for (User *U : Inst.users()) {307 Instruction *UI = cast<Instruction>(U);308 if (UI->getParent() != &BB || isa<PHINode>(UI))309 Users.push_back(UI);310 }311 312 // Find all of the blocks that this value is live in.313 SmallPtrSet<BasicBlock *, 32> LiveBBs;314 LiveBBs.insert(&BB);315 while (!Users.empty()) {316 Instruction *U = Users.pop_back_val();317 318 if (!isa<PHINode>(U)) {319 MarkBlocksLiveIn(U->getParent(), LiveBBs);320 } else {321 // Uses for a PHI node occur in their predecessor block.322 PHINode *PN = cast<PHINode>(U);323 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)324 if (PN->getIncomingValue(i) == &Inst)325 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);326 }327 }328 329 // Now that we know all of the blocks that this thing is live in, see if330 // it includes any of the unwind locations.331 bool NeedsSpill = false;332 for (InvokeInst *Invoke : Invokes) {333 BasicBlock *UnwindBlock = Invoke->getUnwindDest();334 if (UnwindBlock != &BB && LiveBBs.count(UnwindBlock)) {335 LLVM_DEBUG(dbgs() << "SJLJ Spill: " << Inst << " around "336 << UnwindBlock->getName() << "\n");337 NeedsSpill = true;338 break;339 }340 }341 342 // If we decided we need a spill, do it.343 // FIXME: Spilling this way is overkill, as it forces all uses of344 // the value to be reloaded from the stack slot, even those that aren't345 // in the unwind blocks. We should be more selective.346 if (NeedsSpill) {347 DemoteRegToStack(Inst, true);348 ++NumSpilled;349 }350 }351 }352 353 // Go through the landing pads and remove any PHIs there.354 for (InvokeInst *Invoke : Invokes) {355 BasicBlock *UnwindBlock = Invoke->getUnwindDest();356 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();357 358 // Place PHIs into a set to avoid invalidating the iterator.359 SmallPtrSet<PHINode *, 8> PHIsToDemote;360 for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)361 PHIsToDemote.insert(cast<PHINode>(PN));362 if (PHIsToDemote.empty())363 continue;364 365 // Demote the PHIs to the stack.366 for (PHINode *PN : PHIsToDemote)367 DemotePHIToStack(PN);368 369 // Move the landingpad instruction back to the top of the landing pad block.370 LPI->moveBefore(UnwindBlock->begin());371 }372}373 374/// setupEntryBlockAndCallSites - Setup the entry block by creating and filling375/// the function context and marking the call sites with the appropriate376/// values. These values are used by the DWARF EH emitter.377bool SjLjEHPrepareImpl::setupEntryBlockAndCallSites(Function &F) {378 SmallVector<ReturnInst *, 16> Returns;379 SmallVector<InvokeInst *, 16> Invokes;380 SmallSetVector<LandingPadInst *, 16> LPads;381 382 // Look through the terminators of the basic blocks to find invokes.383 for (BasicBlock &BB : F)384 if (auto *II = dyn_cast<InvokeInst>(BB.getTerminator())) {385 if (Function *Callee = II->getCalledFunction())386 if (Callee->getIntrinsicID() == Intrinsic::donothing) {387 // Remove the NOP invoke.388 BranchInst::Create(II->getNormalDest(), II->getIterator());389 II->eraseFromParent();390 continue;391 }392 393 Invokes.push_back(II);394 LPads.insert(II->getUnwindDest()->getLandingPadInst());395 } else if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {396 Returns.push_back(RI);397 }398 399 if (Invokes.empty())400 return false;401 402 NumInvokes += Invokes.size();403 404 lowerIncomingArguments(F);405 lowerAcrossUnwindEdges(F, Invokes);406 407 Value *FuncCtx =408 setupFunctionContext(F, ArrayRef(LPads.begin(), LPads.end()));409 BasicBlock *EntryBB = &F.front();410 IRBuilder<> Builder(EntryBB->getTerminator());411 412 // Get a reference to the jump buffer.413 Value *JBufPtr =414 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 5, "jbuf_gep");415 416 // Save the frame pointer.417 Value *FramePtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 0,418 "jbuf_fp_gep");419 420 Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");421 Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);422 423 // Save the stack pointer.424 Value *StackPtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 2,425 "jbuf_sp_gep");426 427 Val = Builder.CreateCall(StackAddrFn, {}, "sp");428 Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);429 430 // Call the setup_dispatch intrinsic. It fills in the rest of the jmpbuf.431 Builder.CreateCall(BuiltinSetupDispatchFn, {});432 433 // Store a pointer to the function context so that the back-end will know434 // where to look for it.435 Builder.CreateCall(FuncCtxFn, FuncCtx);436 437 // Register the function context and make sure it's known to not throw.438 CallInst *Register = Builder.CreateCall(RegisterFn, FuncCtx, "");439 Register->setDoesNotThrow();440 441 // At this point, we are all set up, update the invoke instructions to mark442 // their call_site values.443 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {444 insertCallSiteStore(Invokes[I], I + 1);445 446 ConstantInt *CallSiteNum =447 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);448 449 // Record the call site value for the back end so it stays associated with450 // the invoke.451 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]->getIterator());452 }453 454 // Mark call instructions that aren't nounwind as no-action (call_site ==455 // -1). Skip the entry block, as prior to then, no function context has been456 // created for this function and any unexpected exceptions thrown will go457 // directly to the caller's context, which is what we want anyway, so no need458 // to do anything here.459 for (BasicBlock &BB : F) {460 if (&BB == &F.front())461 continue;462 for (Instruction &I : BB)463 if (!isa<InvokeInst>(I) && I.mayThrow())464 insertCallSiteStore(&I, -1);465 }466 467 // Following any allocas not in the entry block, update the saved SP in the468 // jmpbuf to the new value.469 for (BasicBlock &BB : F) {470 if (&BB == &F.front())471 continue;472 for (Instruction &I : BB) {473 if (auto *CI = dyn_cast<CallInst>(&I)) {474 if (CI->getCalledFunction() != StackRestoreFn)475 continue;476 } else if (!isa<AllocaInst>(&I)) {477 continue;478 }479 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");480 StackAddr->insertAfter(I.getIterator());481 new StoreInst(StackAddr, StackPtr, true,482 std::next(StackAddr->getIterator()));483 }484 }485 486 // Finally, for any returns from this function, if this function contains an487 // invoke, add a call to unregister the function context.488 for (ReturnInst *Return : Returns) {489 Instruction *InsertPoint = Return;490 if (CallInst *CI = Return->getParent()->getTerminatingMustTailCall())491 InsertPoint = CI;492 CallInst::Create(UnregisterFn, FuncCtx, "", InsertPoint->getIterator());493 }494 495 return true;496}497 498bool SjLjEHPrepareImpl::runOnFunction(Function &F) {499 Module &M = *F.getParent();500 RegisterFn = M.getOrInsertFunction(501 "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),502 PointerType::getUnqual(FunctionContextTy->getContext()));503 UnregisterFn = M.getOrInsertFunction(504 "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),505 PointerType::getUnqual(FunctionContextTy->getContext()));506 507 PointerType *AllocaPtrTy = M.getDataLayout().getAllocaPtrType(M.getContext());508 509 FrameAddrFn = Intrinsic::getOrInsertDeclaration(&M, Intrinsic::frameaddress,510 {AllocaPtrTy});511 StackAddrFn = Intrinsic::getOrInsertDeclaration(&M, Intrinsic::stacksave,512 {AllocaPtrTy});513 StackRestoreFn = Intrinsic::getOrInsertDeclaration(514 &M, Intrinsic::stackrestore, {AllocaPtrTy});515 BuiltinSetupDispatchFn =516 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::eh_sjlj_setup_dispatch);517 LSDAAddrFn = Intrinsic::getOrInsertDeclaration(&M, Intrinsic::eh_sjlj_lsda);518 CallSiteFn =519 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::eh_sjlj_callsite);520 FuncCtxFn =521 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);522 523 bool Res = setupEntryBlockAndCallSites(F);524 return Res;525}526