1 //===-- WinEHPrepare - Prepare exception handling for code generation ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass lowers LLVM IR exception handling into something closer to what the
11 // backend wants. It snifs the personality function to see which kind of
12 // preparation is necessary. If the personality function uses the Itanium LSDA,
13 // this pass delegates to the DWARF EH preparation pass.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/Analysis/LibCallSemantics.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/IRBuilder.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Transforms/Utils/Cloning.h"
27 #include "llvm/Transforms/Utils/Local.h"
31 using namespace llvm::PatternMatch;
33 #define DEBUG_TYPE "winehprepare"
36 class WinEHPrepare : public FunctionPass {
37 std::unique_ptr<FunctionPass> DwarfPrepare;
40 static char ID; // Pass identification, replacement for typeid.
41 WinEHPrepare(const TargetMachine *TM = nullptr)
42 : FunctionPass(ID), DwarfPrepare(createDwarfEHPass(TM)) {}
44 bool runOnFunction(Function &Fn) override;
46 bool doFinalization(Module &M) override;
48 void getAnalysisUsage(AnalysisUsage &AU) const override;
50 const char *getPassName() const override {
51 return "Windows exception handling preparation";
55 bool prepareCPPEHHandlers(Function &F,
56 SmallVectorImpl<LandingPadInst *> &LPads);
57 bool outlineCatchHandler(Function *SrcFn, Constant *SelectorType,
58 LandingPadInst *LPad, StructType *EHDataStructTy);
61 class WinEHCatchDirector : public CloningDirector {
63 WinEHCatchDirector(LandingPadInst *LPI, Value *Selector, Value *EHObj)
64 : LPI(LPI), CurrentSelector(Selector->stripPointerCasts()), EHObj(EHObj),
65 SelectorIDType(Type::getInt32Ty(LPI->getContext())),
66 Int8PtrType(Type::getInt8PtrTy(LPI->getContext())) {}
68 CloningAction handleInstruction(ValueToValueMapTy &VMap,
69 const Instruction *Inst,
70 BasicBlock *NewBB) override;
74 Value *CurrentSelector;
79 const Value *ExtractedEHPtr;
80 const Value *ExtractedSelector;
81 const Value *EHPtrStoreAddr;
82 const Value *SelectorStoreAddr;
84 } // end anonymous namespace
86 char WinEHPrepare::ID = 0;
87 INITIALIZE_TM_PASS_BEGIN(WinEHPrepare, "winehprepare",
88 "Prepare Windows exceptions", false, false)
89 INITIALIZE_PASS_DEPENDENCY(DwarfEHPrepare)
90 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
91 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
92 INITIALIZE_TM_PASS_END(WinEHPrepare, "winehprepare",
93 "Prepare Windows exceptions", false, false)
95 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
96 return new WinEHPrepare(TM);
99 static bool isMSVCPersonality(EHPersonality Pers) {
100 return Pers == EHPersonality::MSVC_Win64SEH ||
101 Pers == EHPersonality::MSVC_CXX;
104 bool WinEHPrepare::runOnFunction(Function &Fn) {
105 SmallVector<LandingPadInst *, 4> LPads;
106 SmallVector<ResumeInst *, 4> Resumes;
107 for (BasicBlock &BB : Fn) {
108 if (auto *LP = BB.getLandingPadInst())
110 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
111 Resumes.push_back(Resume);
114 // No need to prepare functions that lack landing pads.
118 // Classify the personality to see what kind of preparation we need.
119 EHPersonality Pers = classifyEHPersonality(LPads.back()->getPersonalityFn());
121 // Delegate through to the DWARF pass if this is unrecognized.
122 if (!isMSVCPersonality(Pers)) {
123 // Use the resolver from our pass manager in the dwarf pass.
124 assert(getResolver());
125 DwarfPrepare->setResolver(getResolver());
126 return DwarfPrepare->runOnFunction(Fn);
129 // FIXME: This only returns true if the C++ EH handlers were outlined.
130 // When that code is complete, it should always return whatever
131 // prepareCPPEHHandlers returns.
132 if (Pers == EHPersonality::MSVC_CXX && prepareCPPEHHandlers(Fn, LPads))
135 // FIXME: SEH Cleanups are unimplemented. Replace them with unreachable.
139 for (ResumeInst *Resume : Resumes) {
140 IRBuilder<>(Resume).CreateUnreachable();
141 Resume->eraseFromParent();
147 bool WinEHPrepare::doFinalization(Module &M) {
148 return DwarfPrepare->doFinalization(M);
151 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
152 DwarfPrepare->getAnalysisUsage(AU);
155 bool WinEHPrepare::prepareCPPEHHandlers(
156 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
157 // FIXME: Find all frame variable references in the handlers
158 // to populate the structure elements.
159 SmallVector<Type *, 2> AllocStructTys;
160 AllocStructTys.push_back(Type::getInt32Ty(F.getContext())); // EH state
161 AllocStructTys.push_back(Type::getInt8PtrTy(F.getContext())); // EH object
162 StructType *EHDataStructTy =
163 StructType::create(F.getContext(), AllocStructTys,
164 "struct." + F.getName().str() + ".ehdata");
165 bool HandlersOutlined = false;
167 for (LandingPadInst *LPad : LPads) {
168 // Look for evidence that this landingpad has already been processed.
169 bool LPadHasActionList = false;
170 BasicBlock *LPadBB = LPad->getParent();
171 for (Instruction &Inst : LPadBB->getInstList()) {
172 // FIXME: Make this an intrinsic.
173 if (auto *Call = dyn_cast<CallInst>(&Inst))
174 if (Call->getCalledFunction()->getName() == "llvm.eh.actions") {
175 LPadHasActionList = true;
180 // If we've already outlined the handlers for this landingpad,
181 // there's nothing more to do here.
182 if (LPadHasActionList)
185 for (unsigned Idx = 0, NumClauses = LPad->getNumClauses(); Idx < NumClauses;
187 if (LPad->isCatch(Idx))
189 outlineCatchHandler(&F, LPad->getClause(Idx), LPad, EHDataStructTy);
190 } // End for each clause
191 } // End for each landingpad
193 return HandlersOutlined;
196 bool WinEHPrepare::outlineCatchHandler(Function *SrcFn, Constant *SelectorType,
197 LandingPadInst *LPad,
198 StructType *EHDataStructTy) {
199 Module *M = SrcFn->getParent();
200 LLVMContext &Context = M->getContext();
202 // Create a new function to receive the handler contents.
203 Type *Int8PtrType = Type::getInt8PtrTy(Context);
204 std::vector<Type *> ArgTys;
205 ArgTys.push_back(Int8PtrType);
206 ArgTys.push_back(Int8PtrType);
207 FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
208 Function *CatchHandler = Function::Create(
209 FnType, GlobalVariable::ExternalLinkage, SrcFn->getName() + ".catch", M);
211 // Generate a standard prolog to setup the frame recovery structure.
212 IRBuilder<> Builder(Context);
213 BasicBlock *Entry = BasicBlock::Create(Context, "catch.entry");
214 CatchHandler->getBasicBlockList().push_front(Entry);
215 Builder.SetInsertPoint(Entry);
216 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
218 // The outlined handler will be called with the parent's frame pointer as
219 // its second argument. To enable the handler to access variables from
220 // the parent frame, we use that pointer to get locate a special block
221 // of memory that was allocated using llvm.eh.allocateframe for this
222 // purpose. During the outlining process we will determine which frame
223 // variables are used in handlers and create a structure that maps these
224 // variables into the frame allocation block.
226 // The frame allocation block also contains an exception state variable
227 // used by the runtime and a pointer to the exception object pointer
228 // which will be filled in by the runtime for use in the handler.
229 Function *RecoverFrameFn =
230 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
231 Value *RecoverArgs[] = {Builder.CreateBitCast(SrcFn, Int8PtrType, ""),
232 &(CatchHandler->getArgumentList().back())};
234 Builder.CreateCall(RecoverFrameFn, RecoverArgs, "eh.alloc");
236 Builder.CreateBitCast(EHAlloc, EHDataStructTy->getPointerTo(), "ehdata");
238 Builder.CreateConstInBoundsGEP2_32(EHData, 0, 1, "eh.obj.ptr");
240 // This will give us a raw pointer to the exception object, which
241 // corresponds to the formal parameter of the catch statement. If the
242 // handler uses this object, we will generate code during the outlining
243 // process to cast the pointer to the appropriate type and deference it
244 // as necessary. The un-outlined landing pad code represents the
245 // exception object as the result of the llvm.eh.begincatch call.
246 Value *EHObj = Builder.CreateLoad(EHObjPtr, false, "eh.obj");
248 ValueToValueMapTy VMap;
250 // FIXME: Map other values referenced in the filter handler.
252 WinEHCatchDirector Director(LPad, SelectorType, EHObj);
254 SmallVector<ReturnInst *, 8> Returns;
255 ClonedCodeInfo InlinedFunctionInfo;
257 BasicBlock::iterator II = LPad;
259 CloneAndPruneIntoFromInst(CatchHandler, SrcFn, ++II, VMap,
260 /*ModuleLevelChanges=*/false, Returns, "",
261 &InlinedFunctionInfo,
262 SrcFn->getParent()->getDataLayout(), &Director);
264 // Move all the instructions in the first cloned block into our entry block.
265 BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
266 Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
267 FirstClonedBB->eraseFromParent();
272 CloningDirector::CloningAction WinEHCatchDirector::handleInstruction(
273 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
274 // Intercept instructions which extract values from the landing pad aggregate.
275 if (auto *Extract = dyn_cast<ExtractValueInst>(Inst)) {
276 if (Extract->getAggregateOperand() == LPI) {
277 assert(Extract->getNumIndices() == 1 &&
278 "Unexpected operation: extracting both landing pad values");
279 assert((*(Extract->idx_begin()) == 0 || *(Extract->idx_begin()) == 1) &&
280 "Unexpected operation: extracting an unknown landing pad element");
282 if (*(Extract->idx_begin()) == 0) {
283 // Element 0 doesn't directly corresponds to anything in the WinEH scheme.
284 // It will be stored to a memory location, then later loaded and finally
285 // the loaded value will be used as the argument to an llvm.eh.begincatch
286 // call. We're tracking it here so that we can skip the store and load.
287 ExtractedEHPtr = Inst;
289 // Element 1 corresponds to the filter selector. We'll map it to 1 for
290 // matching purposes, but it will also probably be stored to memory and
291 // reloaded, so we need to track the instuction so that we can map the
293 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
294 ExtractedSelector = Inst;
297 // Tell the caller not to clone this instruction.
298 return CloningDirector::SkipInstruction;
300 // Other extract value instructions just get cloned.
301 return CloningDirector::CloneInstruction;
304 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
305 // Look for and suppress stores of the extracted landingpad values.
306 const Value *StoredValue = Store->getValueOperand();
307 if (StoredValue == ExtractedEHPtr) {
308 EHPtrStoreAddr = Store->getPointerOperand();
309 return CloningDirector::SkipInstruction;
311 if (StoredValue == ExtractedSelector) {
312 SelectorStoreAddr = Store->getPointerOperand();
313 return CloningDirector::SkipInstruction;
316 // Any other store just gets cloned.
317 return CloningDirector::CloneInstruction;
320 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
321 // Look for loads of (previously suppressed) landingpad values.
322 // The EHPtr load can be ignored (it should only be used as
323 // an argument to llvm.eh.begincatch), but the selector value
324 // needs to be mapped to a constant value of 1 to be used to
325 // simplify the branching to always flow to the current handler.
326 const Value *LoadAddr = Load->getPointerOperand();
327 if (LoadAddr == EHPtrStoreAddr) {
328 VMap[Inst] = UndefValue::get(Int8PtrType);
329 return CloningDirector::SkipInstruction;
331 if (LoadAddr == SelectorStoreAddr) {
332 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
333 return CloningDirector::SkipInstruction;
336 // Any other loads just get cloned.
337 return CloningDirector::CloneInstruction;
340 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>())) {
341 // The argument to the call is some form of the first element of the
342 // landingpad aggregate value, but that doesn't matter. It isn't used
344 // The return value of this instruction, however, is used to access the
345 // EH object pointer. We have generated an instruction to get that value
346 // from the EH alloc block, so we can just map to that here.
348 return CloningDirector::SkipInstruction;
350 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>())) {
351 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
352 // It might be interesting to track whether or not we are inside a catch
353 // function, but that might make the algorithm more brittle than it needs
356 // The end catch call can occur in one of two places: either in a
358 // block that is part of the catch handlers exception mechanism, or at the
359 // end of the catch block. If it occurs in a landing pad, we must skip it
360 // and continue so that the landing pad gets cloned.
361 // FIXME: This case isn't fully supported yet and shouldn't turn up in any
362 // of the test cases until it is.
363 if (IntrinCall->getParent()->isLandingPad())
364 return CloningDirector::SkipInstruction;
366 // If an end catch occurs anywhere else the next instruction should be an
367 // unconditional branch instruction that we want to replace with a return
368 // to the the address of the branch target.
369 const BasicBlock *EndCatchBB = IntrinCall->getParent();
370 const TerminatorInst *Terminator = EndCatchBB->getTerminator();
371 const BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
372 assert(Branch && Branch->isUnconditional());
373 assert(std::next(BasicBlock::const_iterator(IntrinCall)) ==
374 BasicBlock::const_iterator(Branch));
376 ReturnInst::Create(NewBB->getContext(),
377 BlockAddress::get(Branch->getSuccessor(0)), NewBB);
379 // We just added a terminator to the cloned block.
380 // Tell the caller to stop processing the current basic block so that
381 // the branch instruction will be skipped.
382 return CloningDirector::StopCloningBB;
384 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>())) {
385 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
386 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
387 // This causes a replacement that will collapse the landing pad CFG based
388 // on the filter function we intend to match.
389 if (Selector == CurrentSelector)
390 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
392 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
393 // Tell the caller not to clone this instruction.
394 return CloningDirector::SkipInstruction;
397 // Continue with the default cloning behavior.
398 return CloningDirector::CloneInstruction;