blob: d030a7d44cd5f3864777ebd39c3b1de8181b899d [file] [log] [blame]
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001//===-- WinEHPrepare - Prepare exception handling for code generation ---===//
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 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.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/CodeGen/Passes.h"
18#include "llvm/ADT/MapVector.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000019#include "llvm/ADT/STLExtras.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000020#include "llvm/ADT/SmallSet.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000021#include "llvm/ADT/TinyPtrVector.h"
22#include "llvm/Analysis/LibCallSemantics.h"
David Majnemercde33032015-03-30 22:58:10 +000023#include "llvm/CodeGen/WinEHFuncInfo.h"
Andrew Kaylor64622aa2015-04-01 17:21:25 +000024#include "llvm/IR/Dominators.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000025#include "llvm/IR/Function.h"
26#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/Instructions.h"
28#include "llvm/IR/IntrinsicInst.h"
29#include "llvm/IR/Module.h"
30#include "llvm/IR/PatternMatch.h"
31#include "llvm/Pass.h"
Reid Kleckner0f9e27a2015-03-18 20:26:53 +000032#include "llvm/Support/CommandLine.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000033#include "llvm/Support/Debug.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000034#include "llvm/Support/raw_ostream.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000035#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000036#include "llvm/Transforms/Utils/Cloning.h"
37#include "llvm/Transforms/Utils/Local.h"
Andrew Kaylor64622aa2015-04-01 17:21:25 +000038#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000039#include <memory>
40
41using namespace llvm;
42using namespace llvm::PatternMatch;
43
44#define DEBUG_TYPE "winehprepare"
45
46namespace {
47
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000048// This map is used to model frame variable usage during outlining, to
49// construct a structure type to hold the frame variables in a frame
50// allocation block, and to remap the frame variable allocas (including
51// spill locations as needed) to GEPs that get the variable from the
52// frame allocation structure.
Reid Klecknercfb9ce52015-03-05 18:26:34 +000053typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000054
Reid Kleckner3567d272015-04-02 21:13:31 +000055// TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
56// quite null.
57AllocaInst *getCatchObjectSentinel() {
58 return static_cast<AllocaInst *>(nullptr) + 1;
59}
60
Andrew Kaylor6b67d422015-03-11 23:22:06 +000061typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
62
Andrew Kaylor6b67d422015-03-11 23:22:06 +000063class LandingPadActions;
Andrew Kaylor6b67d422015-03-11 23:22:06 +000064class LandingPadMap;
65
66typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
67typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
68
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000069class WinEHPrepare : public FunctionPass {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000070public:
71 static char ID; // Pass identification, replacement for typeid.
72 WinEHPrepare(const TargetMachine *TM = nullptr)
Andrew Kaylor64622aa2015-04-01 17:21:25 +000073 : FunctionPass(ID), DT(nullptr) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000074
75 bool runOnFunction(Function &Fn) override;
76
77 bool doFinalization(Module &M) override;
78
79 void getAnalysisUsage(AnalysisUsage &AU) const override;
80
81 const char *getPassName() const override {
82 return "Windows exception handling preparation";
83 }
84
85private:
Reid Kleckner0f9e27a2015-03-18 20:26:53 +000086 bool prepareExceptionHandlers(Function &F,
87 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor64622aa2015-04-01 17:21:25 +000088 void promoteLandingPadValues(LandingPadInst *LPad);
Andrew Kayloraa92ab02015-04-03 19:37:50 +000089 void completeNestedLandingPad(Function *ParentFn,
90 LandingPadInst *OutlinedLPad,
91 const LandingPadInst *OriginalLPad,
92 FrameVarInfoMap &VarInfo);
Andrew Kaylor6b67d422015-03-11 23:22:06 +000093 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
94 LandingPadInst *LPad, BasicBlock *StartBB,
Reid Klecknercfb9ce52015-03-05 18:26:34 +000095 FrameVarInfoMap &VarInfo);
Andrew Kaylor6b67d422015-03-11 23:22:06 +000096
97 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
98 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
99 VisitedBlockSet &VisitedBlocks);
100 CleanupHandler *findCleanupHandler(BasicBlock *StartBB, BasicBlock *EndBB);
101
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000102 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
103
104 // All fields are reset by runOnFunction.
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000105 DominatorTree *DT;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000106 EHPersonality Personality;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000107 CatchHandlerMapTy CatchHandlerMap;
108 CleanupHandlerMapTy CleanupHandlerMap;
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000109 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000110
111 // This maps landing pad instructions found in outlined handlers to
112 // the landing pad instruction in the parent function from which they
113 // were cloned. The cloned/nested landing pad is used as the key
114 // because the landing pad may be cloned into multiple handlers.
115 // This map will be used to add the llvm.eh.actions call to the nested
116 // landing pads after all handlers have been outlined.
117 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
118
119 // This maps blocks in the parent function which are destinations of
120 // catch handlers to cloned blocks in (other) outlined handlers. This
121 // handles the case where a nested landing pads has a catch handler that
122 // returns to a handler function rather than the parent function.
123 // The original block is used as the key here because there should only
124 // ever be one handler function from which the cloned block is not pruned.
125 // The original block will be pruned from the parent function after all
126 // handlers have been outlined. This map will be used to adjust the
127 // return instructions of handlers which return to the block that was
128 // outlined into a handler. This is done after all handlers have been
129 // outlined but before the outlined code is pruned from the parent function.
130 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000131};
132
133class WinEHFrameVariableMaterializer : public ValueMaterializer {
134public:
135 WinEHFrameVariableMaterializer(Function *OutlinedFn,
136 FrameVarInfoMap &FrameVarInfo);
137 ~WinEHFrameVariableMaterializer() {}
138
139 virtual Value *materializeValueFor(Value *V) override;
140
Reid Kleckner3567d272015-04-02 21:13:31 +0000141 void escapeCatchObject(Value *V);
142
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000143private:
144 FrameVarInfoMap &FrameVarInfo;
145 IRBuilder<> Builder;
146};
147
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000148class LandingPadMap {
149public:
150 LandingPadMap() : OriginLPad(nullptr) {}
151 void mapLandingPad(const LandingPadInst *LPad);
152
153 bool isInitialized() { return OriginLPad != nullptr; }
154
Andrew Kaylorf7118ae2015-03-27 22:31:12 +0000155 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000156 bool isLandingPadSpecificInst(const Instruction *Inst) const;
157
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000158 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
159 Value *SelectorValue) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000160
161private:
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000162 const LandingPadInst *OriginLPad;
163 // We will normally only see one of each of these instructions, but
164 // if more than one occurs for some reason we can handle that.
165 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
166 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000167};
168
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000169class WinEHCloningDirectorBase : public CloningDirector {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000170public:
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000171 WinEHCloningDirectorBase(Function *HandlerFn, FrameVarInfoMap &VarInfo,
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000172 LandingPadMap &LPadMap)
173 : Materializer(HandlerFn, VarInfo),
174 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
175 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
176 LPadMap(LPadMap) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000177
178 CloningAction handleInstruction(ValueToValueMapTy &VMap,
179 const Instruction *Inst,
180 BasicBlock *NewBB) override;
181
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000182 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
183 const Instruction *Inst,
184 BasicBlock *NewBB) = 0;
185 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
186 const Instruction *Inst,
187 BasicBlock *NewBB) = 0;
188 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
189 const Instruction *Inst,
190 BasicBlock *NewBB) = 0;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000191 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
192 const InvokeInst *Invoke,
193 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000194 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
195 const ResumeInst *Resume,
196 BasicBlock *NewBB) = 0;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000197 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
198 const LandingPadInst *LPad,
199 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000200
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000201 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
202
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000203protected:
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000204 WinEHFrameVariableMaterializer Materializer;
205 Type *SelectorIDType;
206 Type *Int8PtrType;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000207 LandingPadMap &LPadMap;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000208};
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000209
210class WinEHCatchDirector : public WinEHCloningDirectorBase {
211public:
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000212 WinEHCatchDirector(
213 Function *CatchFn, Value *Selector, FrameVarInfoMap &VarInfo,
214 LandingPadMap &LPadMap,
215 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads)
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000216 : WinEHCloningDirectorBase(CatchFn, VarInfo, LPadMap),
217 CurrentSelector(Selector->stripPointerCasts()),
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000218 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000219
220 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
221 const Instruction *Inst,
222 BasicBlock *NewBB) override;
223 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
224 BasicBlock *NewBB) override;
225 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
226 const Instruction *Inst,
227 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000228 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
229 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000230 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
231 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000232 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
233 const LandingPadInst *LPad,
234 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000235
Reid Kleckner3567d272015-04-02 21:13:31 +0000236 Value *getExceptionVar() { return ExceptionObjectVar; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000237 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
238
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000239private:
240 Value *CurrentSelector;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000241
Reid Kleckner3567d272015-04-02 21:13:31 +0000242 Value *ExceptionObjectVar;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000243 TinyPtrVector<BasicBlock *> ReturnTargets;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000244
245 // This will be a reference to the field of the same name in the WinEHPrepare
246 // object which instantiates this WinEHCatchDirector object.
247 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000248};
249
250class WinEHCleanupDirector : public WinEHCloningDirectorBase {
251public:
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000252 WinEHCleanupDirector(Function *CleanupFn, FrameVarInfoMap &VarInfo,
253 LandingPadMap &LPadMap)
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000254 : WinEHCloningDirectorBase(CleanupFn, VarInfo, LPadMap) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000255
256 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
257 const Instruction *Inst,
258 BasicBlock *NewBB) override;
259 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
260 BasicBlock *NewBB) override;
261 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
262 const Instruction *Inst,
263 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000264 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
265 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000266 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
267 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000268 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
269 const LandingPadInst *LPad,
270 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000271};
272
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000273class LandingPadActions {
274public:
275 LandingPadActions() : HasCleanupHandlers(false) {}
276
277 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
278 void insertCleanupHandler(CleanupHandler *Action) {
279 Actions.push_back(Action);
280 HasCleanupHandlers = true;
281 }
282
283 bool includesCleanup() const { return HasCleanupHandlers; }
284
David Majnemercde33032015-03-30 22:58:10 +0000285 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000286 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
287 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
288
289private:
290 // Note that this class does not own the ActionHandler objects in this vector.
291 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
292 // in the WinEHPrepare class.
293 SmallVector<ActionHandler *, 4> Actions;
294 bool HasCleanupHandlers;
295};
296
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000297} // end anonymous namespace
298
299char WinEHPrepare::ID = 0;
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000300INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
301 false, false)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000302
303FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
304 return new WinEHPrepare(TM);
305}
306
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000307// FIXME: Remove this once the backend can handle the prepared IR.
308static cl::opt<bool>
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000309 SEHPrepare("sehprepare", cl::Hidden,
310 cl::desc("Prepare functions with SEH personalities"));
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000311
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000312bool WinEHPrepare::runOnFunction(Function &Fn) {
313 SmallVector<LandingPadInst *, 4> LPads;
314 SmallVector<ResumeInst *, 4> Resumes;
315 for (BasicBlock &BB : Fn) {
316 if (auto *LP = BB.getLandingPadInst())
317 LPads.push_back(LP);
318 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
319 Resumes.push_back(Resume);
320 }
321
322 // No need to prepare functions that lack landing pads.
323 if (LPads.empty())
324 return false;
325
326 // Classify the personality to see what kind of preparation we need.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000327 Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000328
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000329 // Do nothing if this is not an MSVC personality.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000330 if (!isMSVCEHPersonality(Personality))
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000331 return false;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000332
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000333 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
334
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000335 if (isAsynchronousEHPersonality(Personality) && !SEHPrepare) {
336 // Replace all resume instructions with unreachable.
337 // FIXME: Remove this once the backend can handle the prepared IR.
338 for (ResumeInst *Resume : Resumes) {
339 IRBuilder<>(Resume).CreateUnreachable();
340 Resume->eraseFromParent();
341 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000342 return true;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000343 }
344
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000345 // If there were any landing pads, prepareExceptionHandlers will make changes.
346 prepareExceptionHandlers(Fn, LPads);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000347 return true;
348}
349
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000350bool WinEHPrepare::doFinalization(Module &M) { return false; }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000351
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000352void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
353 AU.addRequired<DominatorTreeWrapperPass>();
354}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000355
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000356bool WinEHPrepare::prepareExceptionHandlers(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000357 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
358 // These containers are used to re-map frame variables that are used in
359 // outlined catch and cleanup handlers. They will be populated as the
360 // handlers are outlined.
361 FrameVarInfoMap FrameVarInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000362
363 bool HandlersOutlined = false;
364
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000365 Module *M = F.getParent();
366 LLVMContext &Context = M->getContext();
367
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000368 // Create a new function to receive the handler contents.
369 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
370 Type *Int32Type = Type::getInt32Ty(Context);
Reid Kleckner52b07792015-03-12 01:45:37 +0000371 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000372
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000373 for (LandingPadInst *LPad : LPads) {
374 // Look for evidence that this landingpad has already been processed.
375 bool LPadHasActionList = false;
376 BasicBlock *LPadBB = LPad->getParent();
Reid Klecknerc759fe92015-03-19 22:31:02 +0000377 for (Instruction &Inst : *LPadBB) {
Reid Kleckner52b07792015-03-12 01:45:37 +0000378 if (auto *IntrinCall = dyn_cast<IntrinsicInst>(&Inst)) {
379 if (IntrinCall->getIntrinsicID() == Intrinsic::eh_actions) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000380 LPadHasActionList = true;
381 break;
382 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000383 }
384 // FIXME: This is here to help with the development of nested landing pad
385 // outlining. It should be removed when that is finished.
386 if (isa<UnreachableInst>(Inst)) {
387 LPadHasActionList = true;
388 break;
389 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000390 }
391
392 // If we've already outlined the handlers for this landingpad,
393 // there's nothing more to do here.
394 if (LPadHasActionList)
395 continue;
396
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000397 // If either of the values in the aggregate returned by the landing pad is
398 // extracted and stored to memory, promote the stored value to a register.
399 promoteLandingPadValues(LPad);
400
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000401 LandingPadActions Actions;
402 mapLandingPadBlocks(LPad, Actions);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000403
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000404 for (ActionHandler *Action : Actions) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000405 if (Action->hasBeenProcessed())
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000406 continue;
407 BasicBlock *StartBB = Action->getStartBlock();
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000408
409 // SEH doesn't do any outlining for catches. Instead, pass the handler
410 // basic block addr to llvm.eh.actions and list the block as a return
411 // target.
412 if (isAsynchronousEHPersonality(Personality)) {
413 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
414 processSEHCatchHandler(CatchAction, StartBB);
415 HandlersOutlined = true;
416 continue;
417 }
418 }
419
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000420 if (outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo)) {
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000421 HandlersOutlined = true;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000422 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000423 } // End for each Action
424
425 // FIXME: We need a guard against partially outlined functions.
426 if (!HandlersOutlined)
427 continue;
428
429 // Replace the landing pad with a new llvm.eh.action based landing pad.
430 BasicBlock *NewLPadBB = BasicBlock::Create(Context, "lpad", &F, LPadBB);
431 assert(!isa<PHINode>(LPadBB->begin()));
David Majnemercde33032015-03-30 22:58:10 +0000432 auto *NewLPad = cast<LandingPadInst>(LPad->clone());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000433 NewLPadBB->getInstList().push_back(NewLPad);
434 while (!pred_empty(LPadBB)) {
435 auto *pred = *pred_begin(LPadBB);
436 InvokeInst *Invoke = cast<InvokeInst>(pred->getTerminator());
437 Invoke->setUnwindDest(NewLPadBB);
438 }
439
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000440 // Replace the mapping of any nested landing pad that previously mapped
441 // to this landing pad with a referenced to the cloned version.
442 for (auto &LPadPair : NestedLPtoOriginalLP) {
443 const LandingPadInst *OriginalLPad = LPadPair.second;
444 if (OriginalLPad == LPad) {
445 LPadPair.second = NewLPad;
446 }
447 }
448
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000449 // Replace uses of the old lpad in phis with this block and delete the old
450 // block.
451 LPadBB->replaceSuccessorsPhiUsesWith(NewLPadBB);
452 LPadBB->getTerminator()->eraseFromParent();
453 new UnreachableInst(LPadBB->getContext(), LPadBB);
454
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000455 // Add a call to describe the actions for this landing pad.
456 std::vector<Value *> ActionArgs;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000457 for (ActionHandler *Action : Actions) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000458 // Action codes from docs are: 0 cleanup, 1 catch.
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000459 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000460 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000461 ActionArgs.push_back(CatchAction->getSelector());
Reid Kleckner3567d272015-04-02 21:13:31 +0000462 // Find the frame escape index of the exception object alloca in the
463 // parent.
464 int FrameEscapeIdx = -1;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000465 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
Reid Kleckner3567d272015-04-02 21:13:31 +0000466 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
467 auto I = FrameVarInfo.find(EHObj);
468 assert(I != FrameVarInfo.end() &&
469 "failed to map llvm.eh.begincatch var");
470 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
471 }
472 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000473 } else {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000474 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000475 }
Reid Klecknerc759fe92015-03-19 22:31:02 +0000476 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000477 }
478 CallInst *Recover =
479 CallInst::Create(ActionIntrin, ActionArgs, "recover", NewLPadBB);
480
481 // Add an indirect branch listing possible successors of the catch handlers.
482 IndirectBrInst *Branch = IndirectBrInst::Create(Recover, 0, NewLPadBB);
483 for (ActionHandler *Action : Actions) {
484 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
485 for (auto *Target : CatchAction->getReturnTargets()) {
486 Branch->addDestination(Target);
487 }
488 }
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000489 }
490 } // End for each landingpad
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000491
492 // If nothing got outlined, there is no more processing to be done.
493 if (!HandlersOutlined)
494 return false;
495
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000496 // Replace any nested landing pad stubs with the correct action handler.
497 // This must be done before we remove unreachable blocks because it
498 // cleans up references to outlined blocks that will be deleted.
499 for (auto &LPadPair : NestedLPtoOriginalLP)
500 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
501
David Majnemercde33032015-03-30 22:58:10 +0000502 F.addFnAttr("wineh-parent", F.getName());
503
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000504 // Delete any blocks that were only used by handlers that were outlined above.
505 removeUnreachableBlocks(F);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000506
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000507 BasicBlock *Entry = &F.getEntryBlock();
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000508 IRBuilder<> Builder(F.getParent()->getContext());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000509 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000510
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000511 Function *FrameEscapeFn =
512 Intrinsic::getDeclaration(M, Intrinsic::frameescape);
513 Function *RecoverFrameFn =
514 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000515
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000516 // Finally, replace all of the temporary allocas for frame variables used in
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000517 // the outlined handlers with calls to llvm.framerecover.
518 BasicBlock::iterator II = Entry->getFirstInsertionPt();
Andrew Kaylor72029c62015-03-03 00:41:03 +0000519 Instruction *AllocaInsertPt = II;
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000520 SmallVector<Value *, 8> AllocasToEscape;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000521 for (auto &VarInfoEntry : FrameVarInfo) {
Andrew Kaylor72029c62015-03-03 00:41:03 +0000522 Value *ParentVal = VarInfoEntry.first;
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000523 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000524
Andrew Kaylor72029c62015-03-03 00:41:03 +0000525 // If the mapped value isn't already an alloca, we need to spill it if it
526 // is a computed value or copy it if it is an argument.
527 AllocaInst *ParentAlloca = dyn_cast<AllocaInst>(ParentVal);
528 if (!ParentAlloca) {
529 if (auto *Arg = dyn_cast<Argument>(ParentVal)) {
530 // Lower this argument to a copy and then demote that to the stack.
531 // We can't just use the argument location because the handler needs
532 // it to be in the frame allocation block.
533 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
534 Value *TrueValue = ConstantInt::getTrue(Context);
535 Value *UndefValue = UndefValue::get(Arg->getType());
536 Instruction *SI =
537 SelectInst::Create(TrueValue, Arg, UndefValue,
538 Arg->getName() + ".tmp", AllocaInsertPt);
539 Arg->replaceAllUsesWith(SI);
540 // Reset the select operand, because it was clobbered by the RAUW above.
541 SI->setOperand(1, Arg);
542 ParentAlloca = DemoteRegToStack(*SI, true, SI);
543 } else if (auto *PN = dyn_cast<PHINode>(ParentVal)) {
544 ParentAlloca = DemotePHIToStack(PN, AllocaInsertPt);
545 } else {
546 Instruction *ParentInst = cast<Instruction>(ParentVal);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000547 // FIXME: This is a work-around to temporarily handle the case where an
548 // instruction that is only used in handlers is not sunk.
549 // Without uses, DemoteRegToStack would just eliminate the value.
550 // This will fail if ParentInst is an invoke.
551 if (ParentInst->getNumUses() == 0) {
552 BasicBlock::iterator InsertPt = ParentInst;
553 ++InsertPt;
554 ParentAlloca =
555 new AllocaInst(ParentInst->getType(), nullptr,
556 ParentInst->getName() + ".reg2mem", InsertPt);
557 new StoreInst(ParentInst, ParentAlloca, InsertPt);
558 } else {
559 ParentAlloca = DemoteRegToStack(*ParentInst, true, ParentInst);
560 }
Andrew Kaylor72029c62015-03-03 00:41:03 +0000561 }
562 }
563
Reid Kleckner3567d272015-04-02 21:13:31 +0000564 // If the parent alloca is used by exactly one handler and is not a catch
565 // parameter, erase the parent and leave the copy in the outlined handler.
566 // Catch parameters are indicated by a single null pointer in Allocas.
567 if (ParentAlloca->getNumUses() == 0 && Allocas.size() == 1 &&
568 Allocas[0] != getCatchObjectSentinel()) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000569 ParentAlloca->eraseFromParent();
Reid Kleckner3567d272015-04-02 21:13:31 +0000570 // FIXME: Put a null entry in the llvm.frameescape call because we've
571 // already created llvm.eh.actions calls with indices into it.
572 AllocasToEscape.push_back(Constant::getNullValue(Int8PtrType));
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000573 continue;
574 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000575
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000576 // Add this alloca to the list of things to escape.
577 AllocasToEscape.push_back(ParentAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000578
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000579 // Next replace all outlined allocas that are mapped to it.
580 for (AllocaInst *TempAlloca : Allocas) {
Reid Kleckner3567d272015-04-02 21:13:31 +0000581 if (TempAlloca == getCatchObjectSentinel())
582 continue; // Skip catch parameter sentinels.
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000583 Function *HandlerFn = TempAlloca->getParent()->getParent();
584 // FIXME: Sink this GEP into the blocks where it is used.
585 Builder.SetInsertPoint(TempAlloca);
586 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
587 Value *RecoverArgs[] = {
588 Builder.CreateBitCast(&F, Int8PtrType, ""),
589 &(HandlerFn->getArgumentList().back()),
590 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000591 Value *RecoveredAlloca = Builder.CreateCall(RecoverFrameFn, RecoverArgs);
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000592 // Add a pointer bitcast if the alloca wasn't an i8.
593 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
594 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
595 RecoveredAlloca =
596 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000597 }
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000598 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
599 TempAlloca->removeFromParent();
600 RecoveredAlloca->takeName(TempAlloca);
601 delete TempAlloca;
602 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000603 } // End for each FrameVarInfo entry.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000604
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000605 // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
606 // block.
607 Builder.SetInsertPoint(&F.getEntryBlock().back());
608 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
609
Reid Kleckner7e9546b2015-03-25 20:10:36 +0000610 // Insert an alloca for the EH state in the entry block. On x86, we will also
611 // insert stores to update the EH state, but on other ISAs, the runtime does
612 // it for us.
613 // FIXME: This record is different on x86.
614 Type *UnwindHelpTy = Type::getInt64Ty(Context);
615 AllocaInst *UnwindHelp =
616 new AllocaInst(UnwindHelpTy, "unwindhelp", &F.getEntryBlock().front());
David Majnemercde33032015-03-30 22:58:10 +0000617 Builder.CreateStore(llvm::ConstantInt::get(UnwindHelpTy, -2), UnwindHelp,
618 /*isVolatile=*/true);
Reid Kleckner7e9546b2015-03-25 20:10:36 +0000619 Function *UnwindHelpFn =
620 Intrinsic::getDeclaration(M, Intrinsic::eh_unwindhelp);
621 Builder.CreateCall(UnwindHelpFn,
622 Builder.CreateBitCast(UnwindHelp, Int8PtrType));
623
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000624 // Clean up the handler action maps we created for this function
625 DeleteContainerSeconds(CatchHandlerMap);
626 CatchHandlerMap.clear();
627 DeleteContainerSeconds(CleanupHandlerMap);
628 CleanupHandlerMap.clear();
629
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000630 return HandlersOutlined;
631}
632
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000633void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
634 // If the return values of the landing pad instruction are extracted and
635 // stored to memory, we want to promote the store locations to reg values.
636 SmallVector<AllocaInst *, 2> EHAllocas;
637
638 // The landingpad instruction returns an aggregate value. Typically, its
639 // value will be passed to a pair of extract value instructions and the
640 // results of those extracts are often passed to store instructions.
641 // In unoptimized code the stored value will often be loaded and then stored
642 // again.
643 for (auto *U : LPad->users()) {
644 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
645 if (!Extract)
646 continue;
647
648 for (auto *EU : Extract->users()) {
649 if (auto *Store = dyn_cast<StoreInst>(EU)) {
650 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
651 EHAllocas.push_back(AV);
652 }
653 }
654 }
655
656 // We can't do this without a dominator tree.
657 assert(DT);
658
659 if (!EHAllocas.empty()) {
660 PromoteMemToReg(EHAllocas, *DT);
661 EHAllocas.clear();
662 }
663}
664
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000665void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
666 LandingPadInst *OutlinedLPad,
667 const LandingPadInst *OriginalLPad,
668 FrameVarInfoMap &FrameVarInfo) {
669 // Get the nested block and erase the unreachable instruction that was
670 // temporarily inserted as its terminator.
671 LLVMContext &Context = ParentFn->getContext();
672 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
673 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
674 OutlinedBB->getTerminator()->eraseFromParent();
675 // That should leave OutlinedLPad as the last instruction in its block.
676 assert(&OutlinedBB->back() == OutlinedLPad);
677
678 // The original landing pad will have already had its action intrinsic
679 // built by the outlining loop. We need to clone that into the outlined
680 // location. It may also be necessary to add references to the exception
681 // variables to the outlined handler in which this landing pad is nested
682 // and remap return instructions in the nested handlers that should return
683 // to an address in the outlined handler.
684 Function *OutlinedHandlerFn = OutlinedBB->getParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000685 BasicBlock::const_iterator II = OriginalLPad;
686 ++II;
687 // The instruction after the landing pad should now be a call to eh.actions.
688 const Instruction *Recover = II;
689 assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
690 IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
691
692 // Remap the exception variables into the outlined function.
693 WinEHFrameVariableMaterializer Materializer(OutlinedHandlerFn, FrameVarInfo);
694 SmallVector<BlockAddress *, 4> ActionTargets;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000695 SmallVector<ActionHandler *, 4> ActionList;
696 parseEHActions(EHActions, ActionList);
697 for (auto *Action : ActionList) {
698 auto *Catch = dyn_cast<CatchHandler>(Action);
699 if (!Catch)
700 continue;
701 // The dyn_cast to function here selects C++ catch handlers and skips
702 // SEH catch handlers.
703 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
704 if (!Handler)
705 continue;
706 // Visit all the return instructions, looking for places that return
707 // to a location within OutlinedHandlerFn.
708 for (BasicBlock &NestedHandlerBB : *Handler) {
709 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
710 if (!Ret)
711 continue;
712
713 // Handler functions must always return a block address.
714 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
715 // The original target will have been in the main parent function,
716 // but if it is the address of a block that has been outlined, it
717 // should be a block that was outlined into OutlinedHandlerFn.
718 assert(BA->getFunction() == ParentFn);
719
720 // Ignore targets that aren't part of OutlinedHandlerFn.
721 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
722 continue;
723
724 // If the return value is the address ofF a block that we
725 // previously outlined into the parent handler function, replace
726 // the return instruction and add the mapped target to the list
727 // of possible return addresses.
728 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
729 assert(MappedBB->getParent() == OutlinedHandlerFn);
730 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
731 Ret->eraseFromParent();
732 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
733 ActionTargets.push_back(NewBA);
734 }
735 }
Andrew Kaylor7a0cec32015-04-03 21:44:17 +0000736 DeleteContainerPointers(ActionList);
737 ActionList.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000738 OutlinedBB->getInstList().push_back(EHActions);
739
740 // Insert an indirect branch into the outlined landing pad BB.
741 IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
742 // Add the previously collected action targets.
743 for (auto *Target : ActionTargets)
744 IBr->addDestination(Target->getBasicBlock());
745}
746
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000747// This function examines a block to determine whether the block ends with a
748// conditional branch to a catch handler based on a selector comparison.
749// This function is used both by the WinEHPrepare::findSelectorComparison() and
750// WinEHCleanupDirector::handleTypeIdFor().
751static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
752 Constant *&Selector, BasicBlock *&NextBB) {
753 ICmpInst::Predicate Pred;
754 BasicBlock *TBB, *FBB;
755 Value *LHS, *RHS;
756
757 if (!match(BB->getTerminator(),
758 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
759 return false;
760
761 if (!match(LHS,
762 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
763 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
764 return false;
765
766 if (Pred == CmpInst::ICMP_EQ) {
767 CatchHandler = TBB;
768 NextBB = FBB;
769 return true;
770 }
771
772 if (Pred == CmpInst::ICMP_NE) {
773 CatchHandler = FBB;
774 NextBB = TBB;
775 return true;
776 }
777
778 return false;
779}
780
781bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
782 LandingPadInst *LPad, BasicBlock *StartBB,
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000783 FrameVarInfoMap &VarInfo) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000784 Module *M = SrcFn->getParent();
785 LLVMContext &Context = M->getContext();
786
787 // Create a new function to receive the handler contents.
788 Type *Int8PtrType = Type::getInt8PtrTy(Context);
789 std::vector<Type *> ArgTys;
790 ArgTys.push_back(Int8PtrType);
791 ArgTys.push_back(Int8PtrType);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000792 Function *Handler;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000793 if (Action->getType() == Catch) {
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000794 FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
795 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
796 SrcFn->getName() + ".catch", M);
797 } else {
798 FunctionType *FnType =
799 FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
800 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
801 SrcFn->getName() + ".cleanup", M);
802 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000803
David Majnemercde33032015-03-30 22:58:10 +0000804 Handler->addFnAttr("wineh-parent", SrcFn->getName());
805
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000806 // Generate a standard prolog to setup the frame recovery structure.
807 IRBuilder<> Builder(Context);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000808 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
809 Handler->getBasicBlockList().push_front(Entry);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000810 Builder.SetInsertPoint(Entry);
811 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
812
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000813 std::unique_ptr<WinEHCloningDirectorBase> Director;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000814
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000815 ValueToValueMapTy VMap;
816
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000817 LandingPadMap &LPadMap = LPadMaps[LPad];
818 if (!LPadMap.isInitialized())
819 LPadMap.mapLandingPad(LPad);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000820 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
821 Constant *Sel = CatchAction->getSelector();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000822 Director.reset(new WinEHCatchDirector(Handler, Sel, VarInfo, LPadMap,
823 NestedLPtoOriginalLP));
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000824 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
825 ConstantInt::get(Type::getInt32Ty(Context), 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000826 } else {
827 Director.reset(new WinEHCleanupDirector(Handler, VarInfo, LPadMap));
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000828 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
829 UndefValue::get(Type::getInt32Ty(Context)));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000830 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000831
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000832 SmallVector<ReturnInst *, 8> Returns;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000833 ClonedCodeInfo OutlinedFunctionInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000834
Andrew Kaylor3170e562015-03-20 21:42:54 +0000835 // If the start block contains PHI nodes, we need to map them.
836 BasicBlock::iterator II = StartBB->begin();
837 while (auto *PN = dyn_cast<PHINode>(II)) {
838 bool Mapped = false;
839 // Look for PHI values that we have already mapped (such as the selector).
840 for (Value *Val : PN->incoming_values()) {
841 if (VMap.count(Val)) {
842 VMap[PN] = VMap[Val];
843 Mapped = true;
844 }
845 }
846 // If we didn't find a match for this value, map it as an undef.
847 if (!Mapped) {
848 VMap[PN] = UndefValue::get(PN->getType());
849 }
850 ++II;
851 }
852
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000853 // Skip over PHIs and, if applicable, landingpad instructions.
Andrew Kaylor3170e562015-03-20 21:42:54 +0000854 II = StartBB->getFirstInsertionPt();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000855
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000856 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000857 /*ModuleLevelChanges=*/false, Returns, "",
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000858 &OutlinedFunctionInfo, Director.get());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000859
860 // Move all the instructions in the first cloned block into our entry block.
861 BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
862 Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
863 FirstClonedBB->eraseFromParent();
864
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000865 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
866 WinEHCatchDirector *CatchDirector =
867 reinterpret_cast<WinEHCatchDirector *>(Director.get());
868 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
869 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000870
871 // Look for blocks that are not part of the landing pad that we just
872 // outlined but terminate with a call to llvm.eh.endcatch and a
873 // branch to a block that is in the handler we just outlined.
874 // These blocks will be part of a nested landing pad that intends to
875 // return to an address in this handler. This case is best handled
876 // after both landing pads have been outlined, so for now we'll just
877 // save the association of the blocks in LPadTargetBlocks. The
878 // return instructions which are created from these branches will be
879 // replaced after all landing pads have been outlined.
Andrew Kaylora12eb152015-04-03 19:55:30 +0000880 for (const auto &MapEntry : VMap) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000881 // VMap maps all values and blocks that were just cloned, but dead
882 // blocks which were pruned will map to nullptr.
883 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
884 continue;
885 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
886 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
887 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
888 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
889 continue;
890 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
891 --II;
892 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
893 // This would indicate that a nested landing pad wants to return
894 // to a block that is outlined into two different handlers.
895 assert(!LPadTargetBlocks.count(MappedBB));
896 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
897 }
898 }
899 }
900 } // End if (CatchAction)
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000901
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000902 Action->setHandlerBlockOrFunc(Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000903
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000904 return true;
905}
906
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000907/// This BB must end in a selector dispatch. All we need to do is pass the
908/// handler block to llvm.eh.actions and list it as a possible indirectbr
909/// target.
910void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
911 BasicBlock *StartBB) {
912 BasicBlock *HandlerBB;
913 BasicBlock *NextBB;
914 Constant *Selector;
915 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
916 if (Res) {
917 // If this was EH dispatch, this must be a conditional branch to the handler
918 // block.
919 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
920 // leading to crashes if some optimization hoists stuff here.
921 assert(CatchAction->getSelector() && HandlerBB &&
922 "expected catch EH dispatch");
923 } else {
924 // This must be a catch-all. Split the block after the landingpad.
925 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
926 HandlerBB =
927 StartBB->splitBasicBlock(StartBB->getFirstInsertionPt(), "catch.all");
928 }
929 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
930 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
931 CatchAction->setReturnTargets(Targets);
932}
933
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000934void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
935 // Each instance of this class should only ever be used to map a single
936 // landing pad.
937 assert(OriginLPad == nullptr || OriginLPad == LPad);
938
939 // If the landing pad has already been mapped, there's nothing more to do.
940 if (OriginLPad == LPad)
941 return;
942
943 OriginLPad = LPad;
944
945 // The landingpad instruction returns an aggregate value. Typically, its
946 // value will be passed to a pair of extract value instructions and the
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000947 // results of those extracts will have been promoted to reg values before
948 // this routine is called.
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000949 for (auto *U : LPad->users()) {
950 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
951 if (!Extract)
952 continue;
953 assert(Extract->getNumIndices() == 1 &&
954 "Unexpected operation: extracting both landing pad values");
955 unsigned int Idx = *(Extract->idx_begin());
956 assert((Idx == 0 || Idx == 1) &&
957 "Unexpected operation: extracting an unknown landing pad element");
958 if (Idx == 0) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000959 ExtractedEHPtrs.push_back(Extract);
960 } else if (Idx == 1) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000961 ExtractedSelectors.push_back(Extract);
962 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000963 }
964}
965
Andrew Kaylorf7118ae2015-03-27 22:31:12 +0000966bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
967 return BB->getLandingPadInst() == OriginLPad;
968}
969
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000970bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
971 if (Inst == OriginLPad)
972 return true;
973 for (auto *Extract : ExtractedEHPtrs) {
974 if (Inst == Extract)
975 return true;
976 }
977 for (auto *Extract : ExtractedSelectors) {
978 if (Inst == Extract)
979 return true;
980 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000981 return false;
982}
983
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000984void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
985 Value *SelectorValue) const {
986 // Remap all landing pad extract instructions to the specified values.
987 for (auto *Extract : ExtractedEHPtrs)
988 VMap[Extract] = EHPtrValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000989 for (auto *Extract : ExtractedSelectors)
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000990 VMap[Extract] = SelectorValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000991}
992
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000993CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000994 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000995 // If this is one of the boilerplate landing pad instructions, skip it.
996 // The instruction will have already been remapped in VMap.
997 if (LPadMap.isLandingPadSpecificInst(Inst))
998 return CloningDirector::SkipInstruction;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000999
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001000 // Nested landing pads will be cloned as stubs, with just the
1001 // landingpad instruction and an unreachable instruction. When
1002 // all landingpads have been outlined, we'll replace this with the
1003 // llvm.eh.actions call and indirect branch created when the
1004 // landing pad was outlined.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001005 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1006 return handleLandingPad(VMap, LPad, NewBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001007 }
1008
1009 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1010 return handleInvoke(VMap, Invoke, NewBB);
1011
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001012 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1013 return handleResume(VMap, Resume, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001014
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001015 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1016 return handleBeginCatch(VMap, Inst, NewBB);
1017 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1018 return handleEndCatch(VMap, Inst, NewBB);
1019 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1020 return handleTypeIdFor(VMap, Inst, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001021
1022 // Continue with the default cloning behavior.
1023 return CloningDirector::CloneInstruction;
1024}
1025
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001026CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1027 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1028 Instruction *NewInst = LPad->clone();
1029 if (LPad->hasName())
1030 NewInst->setName(LPad->getName());
1031 // Save this correlation for later processing.
1032 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1033 VMap[LPad] = NewInst;
1034 BasicBlock::InstListType &InstList = NewBB->getInstList();
1035 InstList.push_back(NewInst);
1036 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1037 return CloningDirector::StopCloningBB;
1038}
1039
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001040CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1041 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1042 // The argument to the call is some form of the first element of the
1043 // landingpad aggregate value, but that doesn't matter. It isn't used
1044 // here.
Reid Kleckner42366532015-03-03 23:20:30 +00001045 // The second argument is an outparameter where the exception object will be
1046 // stored. Typically the exception object is a scalar, but it can be an
1047 // aggregate when catching by value.
1048 // FIXME: Leave something behind to indicate where the exception object lives
1049 // for this handler. Should it be part of llvm.eh.actions?
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001050 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1051 "llvm.eh.begincatch found while "
1052 "outlining catch handler.");
1053 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
Reid Kleckner3567d272015-04-02 21:13:31 +00001054 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1055 return CloningDirector::SkipInstruction;
Reid Kleckneraab30e12015-04-03 18:18:06 +00001056 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1057 "catch parameter is not static alloca");
Reid Kleckner3567d272015-04-02 21:13:31 +00001058 Materializer.escapeCatchObject(ExceptionObjectVar);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001059 return CloningDirector::SkipInstruction;
1060}
1061
1062CloningDirector::CloningAction
1063WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1064 const Instruction *Inst, BasicBlock *NewBB) {
1065 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1066 // It might be interesting to track whether or not we are inside a catch
1067 // function, but that might make the algorithm more brittle than it needs
1068 // to be.
1069
1070 // The end catch call can occur in one of two places: either in a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001071 // landingpad block that is part of the catch handlers exception mechanism,
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001072 // or at the end of the catch block. However, a catch-all handler may call
1073 // end catch from the original landing pad. If the call occurs in a nested
1074 // landing pad block, we must skip it and continue so that the landing pad
1075 // gets cloned.
1076 auto *ParentBB = IntrinCall->getParent();
1077 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001078 return CloningDirector::SkipInstruction;
1079
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001080 // If an end catch occurs anywhere else we want to terminate the handler
1081 // with a return to the code that follows the endcatch call. If the
1082 // next instruction is not an unconditional branch, we need to split the
1083 // block to provide a clear target for the return instruction.
1084 BasicBlock *ContinueBB;
1085 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1086 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1087 if (!Branch || !Branch->isUnconditional()) {
1088 // We're interrupting the cloning process at this location, so the
1089 // const_cast we're doing here will not cause a problem.
1090 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1091 const_cast<Instruction *>(cast<Instruction>(Next)));
1092 } else {
1093 ContinueBB = Branch->getSuccessor(0);
1094 }
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001095
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001096 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1097 ReturnTargets.push_back(ContinueBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001098
1099 // We just added a terminator to the cloned block.
1100 // Tell the caller to stop processing the current basic block so that
1101 // the branch instruction will be skipped.
1102 return CloningDirector::StopCloningBB;
1103}
1104
1105CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1106 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1107 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1108 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1109 // This causes a replacement that will collapse the landing pad CFG based
1110 // on the filter function we intend to match.
1111 if (Selector == CurrentSelector)
1112 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1113 else
1114 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1115 // Tell the caller not to clone this instruction.
1116 return CloningDirector::SkipInstruction;
1117}
1118
1119CloningDirector::CloningAction
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001120WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1121 const InvokeInst *Invoke, BasicBlock *NewBB) {
1122 return CloningDirector::CloneInstruction;
1123}
1124
1125CloningDirector::CloningAction
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001126WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1127 const ResumeInst *Resume, BasicBlock *NewBB) {
1128 // Resume instructions shouldn't be reachable from catch handlers.
1129 // We still need to handle it, but it will be pruned.
1130 BasicBlock::InstListType &InstList = NewBB->getInstList();
1131 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1132 return CloningDirector::StopCloningBB;
1133}
1134
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001135CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1136 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1137 // The MS runtime will terminate the process if an exception occurs in a
1138 // cleanup handler, so we shouldn't encounter landing pads in the actual
1139 // cleanup code, but they may appear in catch blocks. Depending on where
1140 // we started cloning we may see one, but it will get dropped during dead
1141 // block pruning.
1142 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1143 VMap[LPad] = NewInst;
1144 BasicBlock::InstListType &InstList = NewBB->getInstList();
1145 InstList.push_back(NewInst);
1146 return CloningDirector::StopCloningBB;
1147}
1148
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001149CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1150 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1151 // Catch blocks within cleanup handlers will always be unreachable.
1152 // We'll insert an unreachable instruction now, but it will be pruned
1153 // before the cloning process is complete.
1154 BasicBlock::InstListType &InstList = NewBB->getInstList();
1155 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1156 return CloningDirector::StopCloningBB;
1157}
1158
1159CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1160 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1161 // Catch blocks within cleanup handlers will always be unreachable.
1162 // We'll insert an unreachable instruction now, but it will be pruned
1163 // before the cloning process is complete.
1164 BasicBlock::InstListType &InstList = NewBB->getInstList();
1165 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1166 return CloningDirector::StopCloningBB;
1167}
1168
1169CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1170 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001171 // If we encounter a selector comparison while cloning a cleanup handler,
1172 // we want to stop cloning immediately. Anything after the dispatch
1173 // will be outlined into a different handler.
1174 BasicBlock *CatchHandler;
1175 Constant *Selector;
1176 BasicBlock *NextBB;
1177 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1178 CatchHandler, Selector, NextBB)) {
1179 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1180 return CloningDirector::StopCloningBB;
1181 }
1182 // If eg.typeid.for is called for any other reason, it can be ignored.
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001183 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001184 return CloningDirector::SkipInstruction;
1185}
1186
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001187CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1188 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1189 // All invokes in cleanup handlers can be replaced with calls.
1190 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1191 // Insert a normal call instruction...
1192 CallInst *NewCall =
1193 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1194 Invoke->getName(), NewBB);
1195 NewCall->setCallingConv(Invoke->getCallingConv());
1196 NewCall->setAttributes(Invoke->getAttributes());
1197 NewCall->setDebugLoc(Invoke->getDebugLoc());
1198 VMap[Invoke] = NewCall;
1199
1200 // Insert an unconditional branch to the normal destination.
1201 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1202
1203 // The unwind destination won't be cloned into the new function, so
1204 // we don't need to clean up its phi nodes.
1205
1206 // We just added a terminator to the cloned block.
1207 // Tell the caller to stop processing the current basic block.
1208 return CloningDirector::StopCloningBB;
1209}
1210
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001211CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1212 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1213 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1214
1215 // We just added a terminator to the cloned block.
1216 // Tell the caller to stop processing the current basic block so that
1217 // the branch instruction will be skipped.
1218 return CloningDirector::StopCloningBB;
1219}
1220
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001221WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1222 Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
1223 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001224 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1225 Builder.SetInsertPoint(EntryBB, EntryBB->getFirstInsertionPt());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001226}
1227
1228Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
Andrew Kaylor72029c62015-03-03 00:41:03 +00001229 // If we're asked to materialize a value that is an instruction, we
1230 // temporarily create an alloca in the outlined function and add this
1231 // to the FrameVarInfo map. When all the outlining is complete, we'll
1232 // collect these into a structure, spilling non-alloca values in the
1233 // parent frame as necessary, and replace these temporary allocas with
1234 // GEPs referencing the frame allocation block.
1235
1236 // If the value is an alloca, the mapping is direct.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001237 if (auto *AV = dyn_cast<AllocaInst>(V)) {
Andrew Kaylor72029c62015-03-03 00:41:03 +00001238 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1239 Builder.Insert(NewAlloca, AV->getName());
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001240 FrameVarInfo[AV].push_back(NewAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001241 return NewAlloca;
1242 }
1243
Andrew Kaylor72029c62015-03-03 00:41:03 +00001244 // For other types of instructions or arguments, we need an alloca based on
1245 // the value's type and a load of the alloca. The alloca will be replaced
1246 // by a GEP, but the load will stay. In the parent function, the value will
1247 // be spilled to a location in the frame allocation block.
1248 if (isa<Instruction>(V) || isa<Argument>(V)) {
1249 AllocaInst *NewAlloca =
1250 Builder.CreateAlloca(V->getType(), nullptr, "eh.temp.alloca");
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001251 FrameVarInfo[V].push_back(NewAlloca);
Andrew Kaylor72029c62015-03-03 00:41:03 +00001252 LoadInst *NewLoad = Builder.CreateLoad(NewAlloca, V->getName() + ".reload");
1253 return NewLoad;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001254 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001255
Andrew Kaylor72029c62015-03-03 00:41:03 +00001256 // Don't materialize other values.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001257 return nullptr;
1258}
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001259
Reid Kleckner3567d272015-04-02 21:13:31 +00001260void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1261 // Catch parameter objects have to live in the parent frame. When we see a use
1262 // of a catch parameter, add a sentinel to the multimap to indicate that it's
1263 // used from another handler. This will prevent us from trying to sink the
1264 // alloca into the handler and ensure that the catch parameter is present in
1265 // the call to llvm.frameescape.
1266 FrameVarInfo[V].push_back(getCatchObjectSentinel());
1267}
1268
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001269// This function maps the catch and cleanup handlers that are reachable from the
1270// specified landing pad. The landing pad sequence will have this basic shape:
1271//
1272// <cleanup handler>
1273// <selector comparison>
1274// <catch handler>
1275// <cleanup handler>
1276// <selector comparison>
1277// <catch handler>
1278// <cleanup handler>
1279// ...
1280//
1281// Any of the cleanup slots may be absent. The cleanup slots may be occupied by
1282// any arbitrary control flow, but all paths through the cleanup code must
1283// eventually reach the next selector comparison and no path can skip to a
1284// different selector comparisons, though some paths may terminate abnormally.
1285// Therefore, we will use a depth first search from the start of any given
1286// cleanup block and stop searching when we find the next selector comparison.
1287//
1288// If the landingpad instruction does not have a catch clause, we will assume
1289// that any instructions other than selector comparisons and catch handlers can
1290// be ignored. In practice, these will only be the boilerplate instructions.
1291//
1292// The catch handlers may also have any control structure, but we are only
1293// interested in the start of the catch handlers, so we don't need to actually
1294// follow the flow of the catch handlers. The start of the catch handlers can
1295// be located from the compare instructions, but they can be skipped in the
1296// flow by following the contrary branch.
1297void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1298 LandingPadActions &Actions) {
1299 unsigned int NumClauses = LPad->getNumClauses();
1300 unsigned int HandlersFound = 0;
1301 BasicBlock *BB = LPad->getParent();
1302
1303 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1304
1305 if (NumClauses == 0) {
1306 // This landing pad contains only cleanup code.
1307 CleanupHandler *Action = new CleanupHandler(BB);
1308 CleanupHandlerMap[BB] = Action;
1309 Actions.insertCleanupHandler(Action);
1310 DEBUG(dbgs() << " Assuming cleanup code in block " << BB->getName()
1311 << "\n");
1312 assert(LPad->isCleanup());
1313 return;
1314 }
1315
1316 VisitedBlockSet VisitedBlocks;
1317
1318 while (HandlersFound != NumClauses) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001319 BasicBlock *NextBB = nullptr;
1320
1321 // See if the clause we're looking for is a catch-all.
1322 // If so, the catch begins immediately.
1323 if (isa<ConstantPointerNull>(LPad->getClause(HandlersFound))) {
1324 // The catch all must occur last.
1325 assert(HandlersFound == NumClauses - 1);
1326
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001327 // For C++ EH, check if there is any interesting cleanup code before we
1328 // begin the catch. This is important because cleanups cannot rethrow
1329 // exceptions but code called from catches can. For SEH, it isn't
1330 // important if some finally code before a catch-all is executed out of
1331 // line or after recovering from the exception.
1332 if (Personality == EHPersonality::MSVC_CXX) {
1333 if (auto *CleanupAction = findCleanupHandler(BB, BB)) {
1334 // Add a cleanup entry to the list
1335 Actions.insertCleanupHandler(CleanupAction);
1336 DEBUG(dbgs() << " Found cleanup code in block "
1337 << CleanupAction->getStartBlock()->getName() << "\n");
1338 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001339 }
1340
1341 // Add the catch handler to the action list.
1342 CatchHandler *Action =
1343 new CatchHandler(BB, LPad->getClause(HandlersFound), nullptr);
1344 CatchHandlerMap[BB] = Action;
1345 Actions.insertCatchHandler(Action);
1346 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
1347 ++HandlersFound;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001348
1349 // Once we reach a catch-all, don't expect to hit a resume instruction.
1350 BB = nullptr;
1351 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001352 }
1353
1354 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1355 // See if there is any interesting code executed before the dispatch.
1356 if (auto *CleanupAction =
1357 findCleanupHandler(BB, CatchAction->getStartBlock())) {
1358 // Add a cleanup entry to the list
1359 Actions.insertCleanupHandler(CleanupAction);
1360 DEBUG(dbgs() << " Found cleanup code in block "
1361 << CleanupAction->getStartBlock()->getName() << "\n");
1362 }
1363
1364 assert(CatchAction);
1365 ++HandlersFound;
1366
1367 // Add the catch handler to the action list.
1368 Actions.insertCatchHandler(CatchAction);
1369 DEBUG(dbgs() << " Found catch dispatch in block "
1370 << CatchAction->getStartBlock()->getName() << "\n");
1371
1372 // Move on to the block after the catch handler.
1373 BB = NextBB;
1374 }
1375
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001376 // If we didn't wind up in a catch-all, see if there is any interesting code
1377 // executed before the resume.
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001378 if (auto *CleanupAction = findCleanupHandler(BB, BB)) {
1379 // Add a cleanup entry to the list
1380 Actions.insertCleanupHandler(CleanupAction);
1381 DEBUG(dbgs() << " Found cleanup code in block "
1382 << CleanupAction->getStartBlock()->getName() << "\n");
1383 }
1384
1385 // It's possible that some optimization moved code into a landingpad that
1386 // wasn't
1387 // previously being used for cleanup. If that happens, we need to execute
1388 // that
1389 // extra code from a cleanup handler.
1390 if (Actions.includesCleanup() && !LPad->isCleanup())
1391 LPad->setCleanup(true);
1392}
1393
1394// This function searches starting with the input block for the next
1395// block that terminates with a branch whose condition is based on a selector
1396// comparison. This may be the input block. See the mapLandingPadBlocks
1397// comments for a discussion of control flow assumptions.
1398//
1399CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1400 BasicBlock *&NextBB,
1401 VisitedBlockSet &VisitedBlocks) {
1402 // See if we've already found a catch handler use it.
1403 // Call count() first to avoid creating a null entry for blocks
1404 // we haven't seen before.
1405 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1406 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1407 NextBB = Action->getNextBB();
1408 return Action;
1409 }
1410
1411 // VisitedBlocks applies only to the current search. We still
1412 // need to consider blocks that we've visited while mapping other
1413 // landing pads.
1414 VisitedBlocks.insert(BB);
1415
1416 BasicBlock *CatchBlock = nullptr;
1417 Constant *Selector = nullptr;
1418
1419 // If this is the first time we've visited this block from any landing pad
1420 // look to see if it is a selector dispatch block.
1421 if (!CatchHandlerMap.count(BB)) {
1422 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1423 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1424 CatchHandlerMap[BB] = Action;
1425 return Action;
1426 }
1427 }
1428
1429 // Visit each successor, looking for the dispatch.
1430 // FIXME: We expect to find the dispatch quickly, so this will probably
1431 // work better as a breadth first search.
1432 for (BasicBlock *Succ : successors(BB)) {
1433 if (VisitedBlocks.count(Succ))
1434 continue;
1435
1436 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1437 if (Action)
1438 return Action;
1439 }
1440 return nullptr;
1441}
1442
1443// These are helper functions to combine repeated code from findCleanupHandler.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001444static CleanupHandler *
1445createCleanupHandler(CleanupHandlerMapTy &CleanupHandlerMap, BasicBlock *BB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001446 CleanupHandler *Action = new CleanupHandler(BB);
1447 CleanupHandlerMap[BB] = Action;
1448 return Action;
1449}
1450
1451// This function searches starting with the input block for the next block that
1452// contains code that is not part of a catch handler and would not be eliminated
1453// during handler outlining.
1454//
1455CleanupHandler *WinEHPrepare::findCleanupHandler(BasicBlock *StartBB,
1456 BasicBlock *EndBB) {
1457 // Here we will skip over the following:
1458 //
1459 // landing pad prolog:
1460 //
1461 // Unconditional branches
1462 //
1463 // Selector dispatch
1464 //
1465 // Resume pattern
1466 //
1467 // Anything else marks the start of an interesting block
1468
1469 BasicBlock *BB = StartBB;
1470 // Anything other than an unconditional branch will kick us out of this loop
1471 // one way or another.
1472 while (BB) {
1473 // If we've already scanned this block, don't scan it again. If it is
1474 // a cleanup block, there will be an action in the CleanupHandlerMap.
1475 // If we've scanned it and it is not a cleanup block, there will be a
1476 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
1477 // be no entry in the CleanupHandlerMap. We must call count() first to
1478 // avoid creating a null entry for blocks we haven't scanned.
1479 if (CleanupHandlerMap.count(BB)) {
1480 if (auto *Action = CleanupHandlerMap[BB]) {
1481 return cast<CleanupHandler>(Action);
1482 } else {
1483 // Here we handle the case where the cleanup handler map contains a
1484 // value for this block but the value is a nullptr. This means that
1485 // we have previously analyzed the block and determined that it did
1486 // not contain any cleanup code. Based on the earlier analysis, we
1487 // know the the block must end in either an unconditional branch, a
1488 // resume or a conditional branch that is predicated on a comparison
1489 // with a selector. Either the resume or the selector dispatch
1490 // would terminate the search for cleanup code, so the unconditional
1491 // branch is the only case for which we might need to continue
1492 // searching.
1493 if (BB == EndBB)
1494 return nullptr;
1495 BasicBlock *SuccBB;
1496 if (!match(BB->getTerminator(), m_UnconditionalBr(SuccBB)))
1497 return nullptr;
1498 BB = SuccBB;
1499 continue;
1500 }
1501 }
1502
1503 // Create an entry in the cleanup handler map for this block. Initially
1504 // we create an entry that says this isn't a cleanup block. If we find
1505 // cleanup code, the caller will replace this entry.
1506 CleanupHandlerMap[BB] = nullptr;
1507
1508 TerminatorInst *Terminator = BB->getTerminator();
1509
1510 // Landing pad blocks have extra instructions we need to accept.
1511 LandingPadMap *LPadMap = nullptr;
1512 if (BB->isLandingPad()) {
1513 LandingPadInst *LPad = BB->getLandingPadInst();
1514 LPadMap = &LPadMaps[LPad];
1515 if (!LPadMap->isInitialized())
1516 LPadMap->mapLandingPad(LPad);
1517 }
1518
1519 // Look for the bare resume pattern:
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001520 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
1521 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001522 // resume { i8*, i32 } %lpad.val2
1523 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
1524 InsertValueInst *Insert1 = nullptr;
1525 InsertValueInst *Insert2 = nullptr;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001526 Value *ResumeVal = Resume->getOperand(0);
1527 // If there is only one landingpad, we may use the lpad directly with no
1528 // insertions.
1529 if (isa<LandingPadInst>(ResumeVal))
1530 return nullptr;
1531 if (!isa<PHINode>(ResumeVal)) {
1532 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001533 if (!Insert2)
1534 return createCleanupHandler(CleanupHandlerMap, BB);
1535 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
1536 if (!Insert1)
1537 return createCleanupHandler(CleanupHandlerMap, BB);
1538 }
1539 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1540 II != IE; ++II) {
1541 Instruction *Inst = II;
1542 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1543 continue;
1544 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
1545 continue;
1546 if (!Inst->hasOneUse() ||
1547 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
1548 return createCleanupHandler(CleanupHandlerMap, BB);
1549 }
1550 }
1551 return nullptr;
1552 }
1553
1554 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001555 if (Branch && Branch->isConditional()) {
1556 // Look for the selector dispatch.
1557 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
1558 // %matches = icmp eq i32 %sel, %2
1559 // br i1 %matches, label %catch14, label %eh.resume
1560 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
1561 if (!Compare || !Compare->isEquality())
1562 return createCleanupHandler(CleanupHandlerMap, BB);
1563 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(),
1564 IE = BB->end();
1565 II != IE; ++II) {
1566 Instruction *Inst = II;
1567 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1568 continue;
1569 if (Inst == Compare || Inst == Branch)
1570 continue;
1571 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1572 continue;
1573 return createCleanupHandler(CleanupHandlerMap, BB);
1574 }
1575 // The selector dispatch block should always terminate our search.
1576 assert(BB == EndBB);
1577 return nullptr;
1578 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001579
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001580 // Anything else is either a catch block or interesting cleanup code.
1581 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(),
1582 IE = BB->end();
1583 II != IE; ++II) {
1584 Instruction *Inst = II;
1585 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1586 continue;
1587 // Unconditional branches fall through to this loop.
1588 if (Inst == Branch)
1589 continue;
1590 // If this is a catch block, there is no cleanup code to be found.
1591 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1592 return nullptr;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001593 // If this a nested landing pad, it may contain an endcatch call.
1594 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1595 return nullptr;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001596 // Anything else makes this interesting cleanup code.
1597 return createCleanupHandler(CleanupHandlerMap, BB);
1598 }
1599
1600 // Only unconditional branches in empty blocks should get this far.
1601 assert(Branch && Branch->isUnconditional());
1602 if (BB == EndBB)
1603 return nullptr;
1604 BB = Branch->getSuccessor(0);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001605 }
1606 return nullptr;
1607}
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001608
1609// This is a public function, declared in WinEHFuncInfo.h and is also
1610// referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
1611void llvm::parseEHActions(const IntrinsicInst *II,
1612 SmallVectorImpl<ActionHandler *> &Actions) {
1613 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
1614 uint64_t ActionKind =
1615 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
1616 if (ActionKind == /*catch=*/1) {
1617 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
1618 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
1619 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
1620 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
1621 I += 4;
1622 auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
1623 CH->setHandlerBlockOrFunc(Handler);
1624 CH->setExceptionVarIndex(EHObjIndexVal);
1625 Actions.push_back(CH);
1626 }
1627 else {
1628 assert(ActionKind == 0 && "expected a cleanup or a catch action!");
1629 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
1630 I += 2;
1631 auto *CH = new CleanupHandler(/*BB=*/nullptr);
1632 CH->setHandlerBlockOrFunc(Handler);
1633 Actions.push_back(CH);
1634 }
1635 }
1636 std::reverse(Actions.begin(), Actions.end());
1637}
1638