LLVM 24.0.0git
WinEHPrepare.cpp
Go to the documentation of this file.
1//===-- WinEHPrepare - Prepare exception handling for code generation ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass lowers LLVM IR exception handling into something closer to what the
10// backend wants for functions using a personality function from a runtime
11// provided by MSVC. Functions with other personality functions are left alone
12// and may be prepared by other passes. In particular, all supported MSVC
13// personality functions require cleanup code to be outlined, and the C++
14// personality requires catch handler code to be outlined.
15//
16//===----------------------------------------------------------------------===//
17
19#include "CodeGenOptions.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/MapVector.h"
22#include "llvm/ADT/STLExtras.h"
24#include "llvm/CodeGen/Passes.h"
26#include "llvm/IR/Constants.h"
29#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/Verifier.h"
34#include "llvm/Pass.h"
35#include "llvm/Support/Debug.h"
42
43using namespace llvm;
44
45#define DEBUG_TYPE "win-eh-prepare"
46
47static bool isMalformedCatchpad(const CatchPadInst *CPI,
48 EHPersonality Personality) {
49 switch (Personality) {
51 if (CPI->arg_size() != 3)
52 return true;
53
54 Constant *TypeInfo = dyn_cast<Constant>(CPI->getArgOperand(0));
55 if (!TypeInfo)
56 return true;
57 if (!TypeInfo->isNullValue() &&
59 return true;
60
61 if (!isa<ConstantInt>(CPI->getArgOperand(1)))
62 return true;
63
64 return false;
65 }
68 if (CPI->arg_size() == 0)
69 return true;
70
71 Constant *FilterOrNull = dyn_cast<Constant>(CPI->getArgOperand(0));
72 if (!FilterOrNull)
73 return true;
74
75 Constant *Filter = FilterOrNull->stripPointerCasts();
76 if (!Filter->isNullValue() && !isa<Function>(Filter))
77 return true;
78
79 return false;
80 }
82 if (CPI->arg_size() == 0)
83 return true;
84
85 if (!isa<ConstantInt>(CPI->getArgOperand(0)))
86 return true;
87
88 return false;
89 }
92 if (CPI->arg_size() == 1 && !isa<Constant>(CPI->getArgOperand(0)))
93 return true;
94
95 return false;
96 default:
97 llvm_unreachable("Unsupported Personality for WinEH");
98 }
99}
100
101namespace {
102
103class WinEHPrepareImpl {
104public:
105 explicit WinEHPrepareImpl(const CodeGenOptions &Opts) : Opts(Opts) {}
106 bool runOnFunction(Function &Fn);
107
108private:
109 void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
110 void
111 insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
112 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
113 AllocaInst *insertPHILoads(PHINode *PN, Function &F);
114 void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
115 DenseMap<BasicBlock *, Value *> &Loads, Function &F);
116 bool prepareExplicitEH(Function &F);
117 void colorFunclets(Function &F);
118
119 bool demotePHIsOnFunclets(Function &F, bool DemoteCatchSwitchPHIOnly);
120 bool cloneCommonBlocks(Function &F);
121 bool removeMalformedCatchswitch(Value *FuncletToken);
122 bool removeImplausibleInstructions(Function &F);
123 bool cleanupPreparedFunclets(Function &F);
124 void verifyPreparedFunclets(Function &F);
125
126 const CodeGenOptions &Opts;
127
128 // True for Wasm C++ personalities.
129 bool DemoteCatchSwitchPHIOnly = false;
130
131 // All fields are reset by runOnFunction.
132 EHPersonality Personality = EHPersonality::Unknown;
133
134 const DataLayout *DL = nullptr;
135 DenseMap<BasicBlock *, ColorVector> BlockColors;
136 MapVector<BasicBlock *, std::vector<BasicBlock *>> FuncletBlocks;
137};
138
139class WinEHPrepare : public FunctionPass {
140public:
141 static char ID; // Pass identification, replacement for typeid.
142
143 WinEHPrepare() : FunctionPass(ID) {}
144
145 StringRef getPassName() const override {
146 return "Windows exception handling preparation";
147 }
148
149 bool runOnFunction(Function &Fn) override {
150 return WinEHPrepareImpl(getCodeGenOptions(Fn)).runOnFunction(Fn);
151 }
152};
153
154} // end anonymous namespace
155
161
162char WinEHPrepare::ID = 0;
163INITIALIZE_PASS(WinEHPrepare, DEBUG_TYPE, "Prepare Windows exceptions", false,
164 false)
165
166FunctionPass *llvm::createWinEHPass() { return new WinEHPrepare(); }
167
168bool WinEHPrepareImpl::runOnFunction(Function &Fn) {
169 if (!Fn.hasPersonalityFn())
170 return false;
171
172 // Classify the personality to see what kind of preparation we need.
173 Personality = classifyEHPersonality(Fn.getPersonalityFn());
174
175 // Do nothing if this is not a scope-based personality.
176 if (!isScopedEHPersonality(Personality))
177 return false;
178
179 // Funclet personalities outline catch/cleanup bodies, so every funclet PHI
180 // must be demoted. A scoped-but-non-funclet personality (Wasm) keeps its pads
181 // inline and only needs the catchswitch dispatch PHIs demoted.
182 DemoteCatchSwitchPHIOnly = !isFuncletEHPersonality(Personality);
183
184 DL = &Fn.getDataLayout();
185 return prepareExplicitEH(Fn);
186}
187
188static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
189 const BasicBlock *BB) {
191 UME.ToState = ToState;
192 UME.Cleanup = BB;
193 FuncInfo.CxxUnwindMap.push_back(UME);
194 return FuncInfo.getLastStateNumber();
195}
196
197static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
198 int TryHigh, int CatchHigh,
201 TBME.TryLow = TryLow;
202 TBME.TryHigh = TryHigh;
203 TBME.CatchHigh = CatchHigh;
204 assert(TBME.TryLow <= TBME.TryHigh);
205 for (const CatchPadInst *CPI : Handlers) {
208 "Malformed CatchPadInst not caught by win-eh-prepare");
209 Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
210 if (TypeInfo->isNullValue())
211 HT.TypeDescriptor = nullptr;
212 else
214 HT.Adjectives = cast<ConstantInt>(CPI->getArgOperand(1))->getZExtValue();
215 HT.Handler = CPI->getParent();
216 if (auto *AI =
217 dyn_cast<AllocaInst>(CPI->getArgOperand(2)->stripPointerCasts()))
218 HT.CatchObj.Alloca = AI;
219 else
220 HT.CatchObj.Alloca = nullptr;
221 TBME.HandlerArray.push_back(HT);
222 }
223 FuncInfo.TryBlockMap.push_back(TBME);
224}
225
227 for (const User *U : CleanupPad->users())
228 if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
229 return CRI->getUnwindDest();
230 return nullptr;
231}
232
234 WinEHFuncInfo &FuncInfo) {
235 auto *F = const_cast<Function *>(Fn);
237 for (BasicBlock &BB : *F) {
238 auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
239 if (!II)
240 continue;
241
242 auto &BBColors = BlockColors[&BB];
243 assert(BBColors.size() == 1 && "multi-color BB not removed by preparation");
244 BasicBlock *FuncletEntryBB = BBColors.front();
245
246 BasicBlock *FuncletUnwindDest;
247 auto *FuncletPad =
249 assert(FuncletPad || FuncletEntryBB == &Fn->getEntryBlock());
250 if (!FuncletPad)
251 FuncletUnwindDest = nullptr;
252 else if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
253 FuncletUnwindDest = CatchPad->getCatchSwitch()->getUnwindDest();
254 else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(FuncletPad))
255 FuncletUnwindDest = getCleanupRetUnwindDest(CleanupPad);
256 else
257 llvm_unreachable("unexpected funclet pad!");
258
259 BasicBlock *InvokeUnwindDest = II->getUnwindDest();
260 int BaseState = -1;
261 if (FuncletUnwindDest == InvokeUnwindDest) {
262 auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad);
263 if (BaseStateI != FuncInfo.FuncletBaseStateMap.end())
264 BaseState = BaseStateI->second;
265 }
266
267 if (BaseState != -1) {
268 FuncInfo.InvokeStateMap[II] = BaseState;
269 } else {
270 Instruction *PadInst = &*InvokeUnwindDest->getFirstNonPHIIt();
271 assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
272 FuncInfo.InvokeStateMap[II] = FuncInfo.EHPadStateMap[PadInst];
273 }
274 }
275}
276
277// See comments below for calculateSEHStateForAsynchEH().
278// State - incoming State of normal paths
279struct WorkItem {
281 int State;
282 WorkItem(const BasicBlock *BB, int St) {
283 Block = BB;
284 State = St;
285 }
286};
288 WinEHFuncInfo &EHInfo) {
290 struct WorkItem *WI = new WorkItem(BB, State);
291 WorkList.push_back(WI);
292
293 while (!WorkList.empty()) {
294 WI = WorkList.pop_back_val();
295 const BasicBlock *BB = WI->Block;
296 int State = WI->State;
297 delete WI;
298 auto [StateIt, Inserted] = EHInfo.BlockToStateMap.try_emplace(BB);
299 if (!Inserted && StateIt->second <= State)
300 continue; // skip blocks already visited by lower State
301
303 const llvm::Instruction *TI = BB->getTerminator();
304 if (It->isEHPad())
305 State = EHInfo.EHPadStateMap[&*It];
306 StateIt->second = State; // Record state, also flag visiting
307
308 if ((isa<CleanupReturnInst>(TI) || isa<CatchReturnInst>(TI)) && State > 0) {
309 // Retrive the new State
310 State = EHInfo.CxxUnwindMap[State].ToState; // Retrive next State
311 } else if (isa<InvokeInst>(TI)) {
312 auto *Call = cast<CallBase>(TI);
313 const Function *Fn = Call->getCalledFunction();
314 if (Fn && Fn->isIntrinsic() &&
315 (Fn->getIntrinsicID() == Intrinsic::seh_scope_begin ||
316 Fn->getIntrinsicID() == Intrinsic::seh_try_begin))
317 // Retrive the new State from seh_scope_begin
318 State = EHInfo.InvokeStateMap[cast<InvokeInst>(TI)];
319 else if (Fn && Fn->isIntrinsic() &&
320 (Fn->getIntrinsicID() == Intrinsic::seh_scope_end ||
321 Fn->getIntrinsicID() == Intrinsic::seh_try_end)) {
322 // In case of conditional ctor, let's retrieve State from Invoke
323 State = EHInfo.InvokeStateMap[cast<InvokeInst>(TI)];
324 // end of current state, retrive new state from UnwindMap
325 State = EHInfo.CxxUnwindMap[State].ToState;
326 }
327 }
328 // Continue push successors into worklist
329 for (auto *SuccBB : successors(BB)) {
330 WI = new WorkItem(SuccBB, State);
331 WorkList.push_back(WI);
332 }
333 }
334}
335
336// The central theory of this routine is based on the following:
337// A _try scope is always a SEME (Single Entry Multiple Exits) region
338// as jumping into a _try is not allowed
339// The single entry must start with a seh_try_begin() invoke with a
340// correct State number that is the initial state of the SEME.
341// Through control-flow, state number is propagated into all blocks.
342// Side exits marked by seh_try_end() will unwind to parent state via
343// existing SEHUnwindMap[].
344// Side exits can ONLY jump into parent scopes (lower state number).
345// Thus, when a block succeeds various states from its predecessors,
346// the lowest State trumphs others.
347// If some exits flow to unreachable, propagation on those paths terminate,
348// not affecting remaining blocks.
350 WinEHFuncInfo &EHInfo) {
352 struct WorkItem *WI = new WorkItem(BB, State);
353 WorkList.push_back(WI);
354
355 while (!WorkList.empty()) {
356 WI = WorkList.pop_back_val();
357 const BasicBlock *BB = WI->Block;
358 int State = WI->State;
359 delete WI;
360 if (auto It = EHInfo.BlockToStateMap.find(BB);
361 It != EHInfo.BlockToStateMap.end() && It->second <= State)
362 continue; // skip blocks already visited by lower State
363
365 const llvm::Instruction *TI = BB->getTerminator();
366 if (It->isEHPad())
367 State = EHInfo.EHPadStateMap[&*It];
368 EHInfo.BlockToStateMap[BB] = State; // Record state
369
373 "Malformed CatchPadInst not caught by win-eh-prepare");
374 const Constant *FilterOrNull = cast<Constant>(
375 cast<CatchPadInst>(It)->getArgOperand(0)->stripPointerCasts());
376 const Function *Filter = dyn_cast<Function>(FilterOrNull);
377 if (!Filter || !Filter->getName().starts_with("__IsLocalUnwind"))
378 State = EHInfo.SEHUnwindMap[State].ToState; // Retrive next State
379 } else if ((isa<CleanupReturnInst>(TI) || isa<CatchReturnInst>(TI)) &&
380 State > 0) {
381 // Retrive the new State.
382 State = EHInfo.SEHUnwindMap[State].ToState; // Retrive next State
383 } else if (isa<InvokeInst>(TI)) {
384 auto *Call = cast<CallBase>(TI);
385 const Function *Fn = Call->getCalledFunction();
386 if (Fn && Fn->isIntrinsic() &&
387 Fn->getIntrinsicID() == Intrinsic::seh_try_begin)
388 // Retrive the new State from seh_try_begin
389 State = EHInfo.InvokeStateMap[cast<InvokeInst>(TI)];
390 else if (Fn && Fn->isIntrinsic() &&
391 Fn->getIntrinsicID() == Intrinsic::seh_try_end)
392 // end of current state, retrive new state from UnwindMap
393 State = EHInfo.SEHUnwindMap[State].ToState;
394 }
395 // Continue push successors into worklist
396 for (auto *SuccBB : successors(BB)) {
397 WI = new WorkItem(SuccBB, State);
398 WorkList.push_back(WI);
399 }
400 }
401}
402
403// Given BB which ends in an unwind edge, return the EHPad that this BB belongs
404// to. If the unwind edge came from an invoke, return null.
406 Value *ParentPad) {
407 const Instruction *TI = BB->getTerminator();
408 if (isa<InvokeInst>(TI))
409 return nullptr;
410 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
411 if (CatchSwitch->getParentPad() != ParentPad)
412 return nullptr;
413 return BB;
414 }
415 assert(!TI->isEHPad() && "unexpected EHPad!");
416 auto *CleanupPad = cast<CleanupReturnInst>(TI)->getCleanupPad();
417 if (CleanupPad->getParentPad() != ParentPad)
418 return nullptr;
419 return CleanupPad->getParent();
420}
421
422// Starting from a EHPad, Backward walk through control-flow graph
423// to produce two primary outputs:
424// FuncInfo.EHPadStateMap[] and FuncInfo.CxxUnwindMap[]
426 const Instruction *FirstNonPHI,
427 int ParentState) {
428 const BasicBlock *BB = FirstNonPHI->getParent();
429 assert(BB->isEHPad() && "not a funclet!");
430
431 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
432 assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&
433 "shouldn't revist catch funclets!");
434
436 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
437 auto *CatchPad = cast<CatchPadInst>(CatchPadBB->getFirstNonPHIIt());
438 Handlers.push_back(CatchPad);
439 }
440 int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
441 FuncInfo.EHPadStateMap[CatchSwitch] = TryLow;
442 for (const BasicBlock *PredBlock : predecessors(BB))
443 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
444 CatchSwitch->getParentPad())))
445 calculateCXXStateNumbers(FuncInfo, &*PredBlock->getFirstNonPHIIt(),
446 TryLow);
447 int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
448
449 // catchpads are separate funclets in C++ EH due to the way rethrow works.
450 int TryHigh = CatchLow - 1;
451
452 // MSVC FrameHandler3/4 on x64&Arm64 expect Catch Handlers in $tryMap$
453 // stored in pre-order (outer first, inner next), not post-order
454 // Add to map here. Fix the CatchHigh after children are processed
455 const Module *Mod = BB->getParent()->getParent();
456 bool IsPreOrder = Mod->getTargetTriple().isArch64Bit();
457 if (IsPreOrder)
458 addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchLow, Handlers);
459 unsigned TBMEIdx = FuncInfo.TryBlockMap.size() - 1;
460
461 for (const auto *CatchPad : Handlers) {
462 FuncInfo.FuncletBaseStateMap[CatchPad] = CatchLow;
463 FuncInfo.EHPadStateMap[CatchPad] = CatchLow;
464 for (const Instruction *UserI : CatchPad->users()) {
465 if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
466 BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
467 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
468 calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
469 }
470 if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
471 BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
472 // If a nested cleanup pad reports a null unwind destination and the
473 // enclosing catch pad doesn't it must be post-dominated by an
474 // unreachable instruction.
475 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
476 calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
477 }
478 }
479 }
480 int CatchHigh = FuncInfo.getLastStateNumber();
481 // Now child Catches are processed, update CatchHigh
482 if (IsPreOrder)
483 FuncInfo.TryBlockMap[TBMEIdx].CatchHigh = CatchHigh;
484 else // PostOrder
485 addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
486
487 LLVM_DEBUG(dbgs() << "TryLow[" << BB->getName() << "]: " << TryLow << '\n');
488 LLVM_DEBUG(dbgs() << "TryHigh[" << BB->getName() << "]: " << TryHigh
489 << '\n');
490 LLVM_DEBUG(dbgs() << "CatchHigh[" << BB->getName() << "]: " << CatchHigh
491 << '\n');
492 } else {
493 auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
494
495 // It's possible for a cleanup to be visited twice: it might have multiple
496 // cleanupret instructions.
497 auto [It, Inserted] = FuncInfo.EHPadStateMap.try_emplace(CleanupPad);
498 if (!Inserted)
499 return;
500
501 int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, BB);
502 It->second = CleanupState;
503 LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
504 << BB->getName() << '\n');
505 for (const BasicBlock *PredBlock : predecessors(BB)) {
506 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
507 CleanupPad->getParentPad()))) {
508 calculateCXXStateNumbers(FuncInfo, &*PredBlock->getFirstNonPHIIt(),
509 CleanupState);
510 }
511 }
512 for (const Instruction *UserI : CleanupPad->users()) {
513 if (UserI->isEHPad())
514 report_fatal_error("Cleanup funclets for the MSVC++ personality cannot "
515 "contain exceptional actions");
516 }
517 }
518}
519
520static int addSEHExcept(WinEHFuncInfo &FuncInfo, int ParentState,
521 const Function *Filter, const BasicBlock *Handler) {
522 SEHUnwindMapEntry Entry;
523 Entry.ToState = ParentState;
524 Entry.IsFinally = false;
525 Entry.Filter = Filter;
526 Entry.Handler = Handler;
527 FuncInfo.SEHUnwindMap.push_back(Entry);
528 return FuncInfo.SEHUnwindMap.size() - 1;
529}
530
531static int addSEHFinally(WinEHFuncInfo &FuncInfo, int ParentState,
532 const BasicBlock *Handler) {
533 SEHUnwindMapEntry Entry;
534 Entry.ToState = ParentState;
535 Entry.IsFinally = true;
536 Entry.Filter = nullptr;
537 Entry.Handler = Handler;
538 FuncInfo.SEHUnwindMap.push_back(Entry);
539 return FuncInfo.SEHUnwindMap.size() - 1;
540}
541
542// Starting from a EHPad, Backward walk through control-flow graph
543// to produce two primary outputs:
544// FuncInfo.EHPadStateMap[] and FuncInfo.SEHUnwindMap[]
546 const Instruction *FirstNonPHI,
547 int ParentState) {
548 const BasicBlock *BB = FirstNonPHI->getParent();
549 assert(BB->isEHPad() && "no a funclet!");
550
551 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
552 assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&
553 "shouldn't revist catch funclets!");
554
555 // Extract the filter function and the __except basic block and create a
556 // state for them.
557 assert(CatchSwitch->getNumHandlers() == 1 &&
558 "SEH doesn't have multiple handlers per __try");
559 const auto *CatchPad =
560 cast<CatchPadInst>((*CatchSwitch->handler_begin())->getFirstNonPHIIt());
561 const BasicBlock *CatchPadBB = CatchPad->getParent();
563 "Malformed CatchPadInst not caught by win-eh-prepare");
564 const Constant *FilterOrNull =
565 cast<Constant>(CatchPad->getArgOperand(0)->stripPointerCasts());
566 const Function *Filter = dyn_cast<Function>(FilterOrNull);
567 assert((Filter || FilterOrNull->isNullValue()) &&
568 "unexpected filter value");
569 int TryState = addSEHExcept(FuncInfo, ParentState, Filter, CatchPadBB);
570
571 // Everything in the __try block uses TryState as its parent state.
572 FuncInfo.EHPadStateMap[CatchSwitch] = TryState;
573 FuncInfo.EHPadStateMap[CatchPad] = TryState;
574 LLVM_DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "
575 << CatchPadBB->getName() << '\n');
576 for (const BasicBlock *PredBlock : predecessors(BB))
577 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
578 CatchSwitch->getParentPad())))
579 calculateSEHStateNumbers(FuncInfo, &*PredBlock->getFirstNonPHIIt(),
580 TryState);
581
582 // Everything in the __except block unwinds to ParentState, just like code
583 // outside the __try.
584 for (const Instruction *UserI : CatchPad->users()) {
585 if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
586 BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
587 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
588 calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
589 }
590 if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
591 BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
592 // If a nested cleanup pad reports a null unwind destination and the
593 // enclosing catch pad doesn't it must be post-dominated by an
594 // unreachable instruction.
595 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
596 calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
597 }
598 }
599 } else {
600 auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
601
602 // It's possible for a cleanup to be visited twice: it might have multiple
603 // cleanupret instructions.
604 auto [It, Inserted] = FuncInfo.EHPadStateMap.try_emplace(CleanupPad);
605 if (!Inserted)
606 return;
607
608 int CleanupState = addSEHFinally(FuncInfo, ParentState, BB);
609 It->second = CleanupState;
610 LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
611 << BB->getName() << '\n');
612 for (const BasicBlock *PredBlock : predecessors(BB))
613 if ((PredBlock =
614 getEHPadFromPredecessor(PredBlock, CleanupPad->getParentPad())))
615 calculateSEHStateNumbers(FuncInfo, &*PredBlock->getFirstNonPHIIt(),
616 CleanupState);
617 for (const Instruction *UserI : CleanupPad->users()) {
618 if (UserI->isEHPad())
619 report_fatal_error("Cleanup funclets for the SEH personality cannot "
620 "contain exceptional actions");
621 }
622 }
623}
624
625static bool isTopLevelPadForMSVC(const Instruction *EHPad) {
626 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(EHPad))
627 return isa<ConstantTokenNone>(CatchSwitch->getParentPad()) &&
628 CatchSwitch->unwindsToCaller();
629 if (auto *CleanupPad = dyn_cast<CleanupPadInst>(EHPad))
630 return isa<ConstantTokenNone>(CleanupPad->getParentPad()) &&
631 getCleanupRetUnwindDest(CleanupPad) == nullptr;
632 if (isa<CatchPadInst>(EHPad))
633 return false;
634 llvm_unreachable("unexpected EHPad!");
635}
636
638 WinEHFuncInfo &FuncInfo) {
639 // Don't compute state numbers twice.
640 if (!FuncInfo.SEHUnwindMap.empty())
641 return;
642
643 for (const BasicBlock &BB : *Fn) {
644 if (!BB.isEHPad())
645 continue;
646 const Instruction *FirstNonPHI = &*BB.getFirstNonPHIIt();
647 if (!isTopLevelPadForMSVC(FirstNonPHI))
648 continue;
649 ::calculateSEHStateNumbers(FuncInfo, FirstNonPHI, -1);
650 }
651
653
654 bool IsEHa = Fn->getParent()->getModuleFlag("eh-asynch");
655 if (IsEHa) {
656 const BasicBlock *EntryBB = &(Fn->getEntryBlock());
657 calculateSEHStateForAsynchEH(EntryBB, -1, FuncInfo);
658 }
659}
660
662 WinEHFuncInfo &FuncInfo) {
663 // Return if it's already been done.
664 if (!FuncInfo.EHPadStateMap.empty())
665 return;
666
667 for (const BasicBlock &BB : *Fn) {
668 if (!BB.isEHPad())
669 continue;
670 const Instruction *FirstNonPHI = &*BB.getFirstNonPHIIt();
671 if (!isTopLevelPadForMSVC(FirstNonPHI))
672 continue;
673 calculateCXXStateNumbers(FuncInfo, FirstNonPHI, -1);
674 }
675
677
678 bool IsEHa = Fn->getParent()->getModuleFlag("eh-asynch");
679 if (IsEHa) {
680 const BasicBlock *EntryBB = &(Fn->getEntryBlock());
681 calculateCXXStateForAsynchEH(EntryBB, -1, FuncInfo);
682 }
683}
684
685static int addClrEHHandler(WinEHFuncInfo &FuncInfo, int HandlerParentState,
686 int TryParentState, ClrHandlerType HandlerType,
687 uint32_t TypeToken, const BasicBlock *Handler) {
689 Entry.HandlerParentState = HandlerParentState;
690 Entry.TryParentState = TryParentState;
691 Entry.Handler = Handler;
692 Entry.HandlerType = HandlerType;
693 Entry.TypeToken = TypeToken;
694 FuncInfo.ClrEHUnwindMap.push_back(Entry);
695 return FuncInfo.ClrEHUnwindMap.size() - 1;
696}
697
699 WinEHFuncInfo &FuncInfo) {
700 // Return if it's already been done.
701 if (!FuncInfo.EHPadStateMap.empty())
702 return;
703
704 // This numbering assigns one state number to each catchpad and cleanuppad.
705 // It also computes two tree-like relations over states:
706 // 1) Each state has a "HandlerParentState", which is the state of the next
707 // outer handler enclosing this state's handler (same as nearest ancestor
708 // per the ParentPad linkage on EH pads, but skipping over catchswitches).
709 // 2) Each state has a "TryParentState", which:
710 // a) for a catchpad that's not the last handler on its catchswitch, is
711 // the state of the next catchpad on that catchswitch
712 // b) for all other pads, is the state of the pad whose try region is the
713 // next outer try region enclosing this state's try region. The "try
714 // regions are not present as such in the IR, but will be inferred
715 // based on the placement of invokes and pads which reach each other
716 // by exceptional exits
717 // Catchswitches do not get their own states, but each gets mapped to the
718 // state of its first catchpad.
719
720 // Step one: walk down from outermost to innermost funclets, assigning each
721 // catchpad and cleanuppad a state number. Add an entry to the
722 // ClrEHUnwindMap for each state, recording its HandlerParentState and
723 // handler attributes. Record the TryParentState as well for each catchpad
724 // that's not the last on its catchswitch, but initialize all other entries'
725 // TryParentStates to a sentinel -1 value that the next pass will update.
726
727 // Seed a worklist with pads that have no parent.
729 for (const BasicBlock &BB : *Fn) {
730 const Instruction *FirstNonPHI = &*BB.getFirstNonPHIIt();
731 const Value *ParentPad;
732 if (const auto *CPI = dyn_cast<CleanupPadInst>(FirstNonPHI))
733 ParentPad = CPI->getParentPad();
734 else if (const auto *CSI = dyn_cast<CatchSwitchInst>(FirstNonPHI))
735 ParentPad = CSI->getParentPad();
736 else
737 continue;
738 if (isa<ConstantTokenNone>(ParentPad))
739 Worklist.emplace_back(FirstNonPHI, -1);
740 }
741
742 // Use the worklist to visit all pads, from outer to inner. Record
743 // HandlerParentState for all pads. Record TryParentState only for catchpads
744 // that aren't the last on their catchswitch (setting all other entries'
745 // TryParentStates to an initial value of -1). This loop is also responsible
746 // for setting the EHPadStateMap entry for all catchpads, cleanuppads, and
747 // catchswitches.
748 while (!Worklist.empty()) {
749 const Instruction *Pad;
750 int HandlerParentState;
751 std::tie(Pad, HandlerParentState) = Worklist.pop_back_val();
752
753 if (const auto *Cleanup = dyn_cast<CleanupPadInst>(Pad)) {
754 // Create the entry for this cleanup with the appropriate handler
755 // properties. Finally and fault handlers are distinguished by arity.
756 ClrHandlerType HandlerType =
757 (Cleanup->arg_size() ? ClrHandlerType::Fault
759 int CleanupState = addClrEHHandler(FuncInfo, HandlerParentState, -1,
760 HandlerType, 0, Pad->getParent());
761 // Queue any child EH pads on the worklist.
762 for (const Instruction *I : Cleanup->users())
763 if (I->isEHPad())
764 Worklist.emplace_back(I, CleanupState);
765 // Remember this pad's state.
766 FuncInfo.EHPadStateMap[Cleanup] = CleanupState;
767 } else {
768 // Walk the handlers of this catchswitch in reverse order since all but
769 // the last need to set the following one as its TryParentState.
770 const auto *CatchSwitch = cast<CatchSwitchInst>(Pad);
771 int CatchState = -1, FollowerState = -1;
772 SmallVector<const BasicBlock *, 4> CatchBlocks(CatchSwitch->handlers());
773 for (const BasicBlock *CatchBlock : llvm::reverse(CatchBlocks)) {
774 // Create the entry for this catch with the appropriate handler
775 // properties.
776 const auto *Catch = cast<CatchPadInst>(CatchBlock->getFirstNonPHIIt());
778 "Malformed CatchPadInst not caught by win-eh-prepare");
779 uint32_t TypeToken = static_cast<uint32_t>(
780 cast<ConstantInt>(Catch->getArgOperand(0))->getZExtValue());
781 CatchState =
782 addClrEHHandler(FuncInfo, HandlerParentState, FollowerState,
783 ClrHandlerType::Catch, TypeToken, CatchBlock);
784 // Queue any child EH pads on the worklist.
785 for (const Instruction *I : Catch->users())
786 if (I->isEHPad())
787 Worklist.emplace_back(I, CatchState);
788 // Remember this catch's state.
789 FuncInfo.EHPadStateMap[Catch] = CatchState;
790 FollowerState = CatchState;
791 }
792 // Associate the catchswitch with the state of its first catch.
793 assert(CatchSwitch->getNumHandlers());
794 FuncInfo.EHPadStateMap[CatchSwitch] = CatchState;
795 }
796 }
797
798 // Step two: record the TryParentState of each state. For cleanuppads that
799 // don't have cleanuprets, we may need to infer this from their child pads,
800 // so visit pads in descendant-most to ancestor-most order.
801 for (ClrEHUnwindMapEntry &Entry : llvm::reverse(FuncInfo.ClrEHUnwindMap)) {
802 const Instruction *Pad =
803 &*cast<const BasicBlock *>(Entry.Handler)->getFirstNonPHIIt();
804 // For most pads, the TryParentState is the state associated with the
805 // unwind dest of exceptional exits from it.
806 const BasicBlock *UnwindDest;
807 if (const auto *Catch = dyn_cast<CatchPadInst>(Pad)) {
808 // If a catch is not the last in its catchswitch, its TryParentState is
809 // the state associated with the next catch in the switch, even though
810 // that's not the unwind dest of exceptions escaping the catch. Those
811 // cases were already assigned a TryParentState in the first pass, so
812 // skip them.
813 if (Entry.TryParentState != -1)
814 continue;
815 // Otherwise, get the unwind dest from the catchswitch.
816 UnwindDest = Catch->getCatchSwitch()->getUnwindDest();
817 } else {
818 const auto *Cleanup = cast<CleanupPadInst>(Pad);
819 UnwindDest = nullptr;
820 for (const User *U : Cleanup->users()) {
821 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
822 // Common and unambiguous case -- cleanupret indicates cleanup's
823 // unwind dest.
824 UnwindDest = CleanupRet->getUnwindDest();
825 break;
826 }
827
828 // Get an unwind dest for the user
829 const BasicBlock *UserUnwindDest = nullptr;
830 if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
831 UserUnwindDest = Invoke->getUnwindDest();
832 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(U)) {
833 UserUnwindDest = CatchSwitch->getUnwindDest();
834 } else if (auto *ChildCleanup = dyn_cast<CleanupPadInst>(U)) {
835 int UserState = FuncInfo.EHPadStateMap[ChildCleanup];
836 int UserUnwindState =
837 FuncInfo.ClrEHUnwindMap[UserState].TryParentState;
838 if (UserUnwindState != -1)
839 UserUnwindDest = cast<const BasicBlock *>(
840 FuncInfo.ClrEHUnwindMap[UserUnwindState].Handler);
841 }
842
843 // Not having an unwind dest for this user might indicate that it
844 // doesn't unwind, so can't be taken as proof that the cleanup itself
845 // may unwind to caller (see e.g. SimplifyUnreachable and
846 // RemoveUnwindEdge).
847 if (!UserUnwindDest)
848 continue;
849
850 // Now we have an unwind dest for the user, but we need to see if it
851 // unwinds all the way out of the cleanup or if it stays within it.
852 const Instruction *UserUnwindPad = &*UserUnwindDest->getFirstNonPHIIt();
853 const Value *UserUnwindParent;
854 if (auto *CSI = dyn_cast<CatchSwitchInst>(UserUnwindPad))
855 UserUnwindParent = CSI->getParentPad();
856 else
857 UserUnwindParent =
858 cast<CleanupPadInst>(UserUnwindPad)->getParentPad();
859
860 // The unwind stays within the cleanup iff it targets a child of the
861 // cleanup.
862 if (UserUnwindParent == Cleanup)
863 continue;
864
865 // This unwind exits the cleanup, so its dest is the cleanup's dest.
866 UnwindDest = UserUnwindDest;
867 break;
868 }
869 }
870
871 // Record the state of the unwind dest as the TryParentState.
872 int UnwindDestState;
873
874 // If UnwindDest is null at this point, either the pad in question can
875 // be exited by unwind to caller, or it cannot be exited by unwind. In
876 // either case, reporting such cases as unwinding to caller is correct.
877 // This can lead to EH tables that "look strange" -- if this pad's is in
878 // a parent funclet which has other children that do unwind to an enclosing
879 // pad, the try region for this pad will be missing the "duplicate" EH
880 // clause entries that you'd expect to see covering the whole parent. That
881 // should be benign, since the unwind never actually happens. If it were
882 // an issue, we could add a subsequent pass that pushes unwind dests down
883 // from parents that have them to children that appear to unwind to caller.
884 if (!UnwindDest) {
885 UnwindDestState = -1;
886 } else {
887 UnwindDestState =
888 FuncInfo.EHPadStateMap[&*UnwindDest->getFirstNonPHIIt()];
889 }
890
891 Entry.TryParentState = UnwindDestState;
892 }
893
894 // Step three: transfer information from pads to invokes.
896}
897
898void WinEHPrepareImpl::colorFunclets(Function &F) {
899 BlockColors = colorEHFunclets(F);
900
901 // Invert the map from BB to colors to color to BBs.
902 for (BasicBlock &BB : F) {
903 ColorVector &Colors = BlockColors[&BB];
904 for (BasicBlock *Color : Colors)
905 FuncletBlocks[Color].push_back(&BB);
906 }
907}
908
909bool WinEHPrepareImpl::demotePHIsOnFunclets(Function &F,
910 bool DemoteCatchSwitchPHIOnly) {
911 bool Changed = false;
912
913 // Strip PHI nodes off of EH pads.
915 for (BasicBlock &BB : make_early_inc_range(F)) {
916 if (!BB.isEHPad())
917 continue;
918
919 for (Instruction &I : make_early_inc_range(BB)) {
920 auto *PN = dyn_cast<PHINode>(&I);
921 // Stop at the first non-PHI.
922 if (!PN)
923 break;
924
925 // If DemoteCatchSwitchPHIOnly is true, we only demote a PHI when
926 // 1. The PHI is within a catchswitch BB
927 // 2. The PHI has a catchswitch BB has one of its incoming blocks
928 if (DemoteCatchSwitchPHIOnly) {
929 bool IsCatchSwitchBB = isa<CatchSwitchInst>(BB.getFirstNonPHIIt());
930 bool HasIncomingCatchSwitchBB = false;
931 for (unsigned I = 0, E = PN->getNumIncomingValues(); I < E; ++I) {
933 PN->getIncomingBlock(I)->getFirstNonPHIIt())) {
934 HasIncomingCatchSwitchBB = true;
935 break;
936 }
937 }
938 if (!IsCatchSwitchBB && !HasIncomingCatchSwitchBB)
939 break;
940 }
941
942 Changed = true;
943
944 AllocaInst *SpillSlot = insertPHILoads(PN, F);
945 if (SpillSlot)
946 insertPHIStores(PN, SpillSlot);
947
948 PHINodes.push_back(PN);
949 }
950 }
951
952 for (auto *PN : PHINodes) {
953 // There may be lingering uses on other EH PHIs being removed
954 PN->replaceAllUsesWith(PoisonValue::get(PN->getType()));
955 PN->eraseFromParent();
956 }
957
958 return Changed;
959}
960
961bool WinEHPrepareImpl::removeMalformedCatchswitch(Value *FuncletToken) {
962 // If a catchpad is malformed, the whole catchswitch is invalidated
963 // therefore, make all of its catchpads unreachable
964 CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(FuncletToken);
965
966 if (!CatchPad)
967 return false;
968
969 if (!isMalformedCatchpad(CatchPad, Personality))
970 return false;
971
973 "catchpad with unexpected arguments", *CatchPad->getParent()->getParent(),
974 CatchPad->getDebugLoc()));
975
976 CatchSwitchInst *CatchSwitch = CatchPad->getCatchSwitch();
977 for (BasicBlock *Handler : CatchSwitch->handlers()) {
978 if (CatchPadInst *CPI =
979 dyn_cast<CatchPadInst>(Handler->getFirstNonPHIIt())) {
980 LLVMContext &CTX = CPI->getContext();
981 IRBuilder<> Builder(CPI);
982
983 // default values for the CatchPad's args
986 Value *constantZero = ConstantInt::get(Type::getInt32Ty(CTX), 0);
987 switch (Personality) {
989 args = {nullPtr, constantZero, nullPtr};
990 break;
995 args = {nullPtr};
996 break;
998 args = {constantZero};
999 break;
1000 default:
1001 llvm_unreachable("Unsupported Personality for WinEH");
1002 };
1003 Value *NewCatchPad =
1004 Builder.CreateCatchPad(CPI->getParentPad(), args, CPI->getName());
1005 CPI->replaceAllUsesWith(NewCatchPad);
1007 }
1008 }
1009
1010 return true;
1011}
1012
1013bool WinEHPrepareImpl::cloneCommonBlocks(Function &F) {
1014 bool Changed = false;
1015
1016 // We need to clone all blocks which belong to multiple funclets. Values are
1017 // remapped throughout the funclet to propagate both the new instructions
1018 // *and* the new basic blocks themselves.
1019 for (auto &Funclets : FuncletBlocks) {
1020 BasicBlock *FuncletPadBB = Funclets.first;
1021 std::vector<BasicBlock *> &BlocksInFunclet = Funclets.second;
1022 Value *FuncletToken;
1023 if (FuncletPadBB == &F.getEntryBlock())
1024 FuncletToken = ConstantTokenNone::get(F.getContext());
1025 else {
1026 FuncletToken = &*FuncletPadBB->getFirstNonPHIIt();
1027 Changed |= removeMalformedCatchswitch(FuncletToken);
1028 }
1029
1030 std::vector<std::pair<BasicBlock *, BasicBlock *>> Orig2Clone;
1031 ValueToValueMapTy VMap;
1032 for (BasicBlock *BB : BlocksInFunclet) {
1033 ColorVector &ColorsForBB = BlockColors[BB];
1034 // We don't need to do anything if the block is monochromatic.
1035 size_t NumColorsForBB = ColorsForBB.size();
1036 if (NumColorsForBB == 1)
1037 continue;
1038
1039 DEBUG_WITH_TYPE("win-eh-prepare-coloring",
1040 dbgs() << " Cloning block \'" << BB->getName()
1041 << "\' for funclet \'" << FuncletPadBB->getName()
1042 << "\'.\n");
1043
1044 // Create a new basic block and copy instructions into it!
1045 BasicBlock *CBB =
1046 CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
1047 // Insert the clone immediately after the original to ensure determinism
1048 // and to keep the same relative ordering of any funclet's blocks.
1049 CBB->insertInto(&F, BB->getNextNode());
1050
1051 // Add basic block mapping.
1052 VMap[BB] = CBB;
1053
1054 // Record delta operations that we need to perform to our color mappings.
1055 Orig2Clone.emplace_back(BB, CBB);
1056 }
1057
1058 // If nothing was cloned, we're done cloning in this funclet.
1059 if (Orig2Clone.empty())
1060 continue;
1061
1062 Changed = true;
1063
1064 // Update our color mappings to reflect that one block has lost a color and
1065 // another has gained a color.
1066 for (auto &BBMapping : Orig2Clone) {
1067 BasicBlock *OldBlock = BBMapping.first;
1068 BasicBlock *NewBlock = BBMapping.second;
1069
1070 BlocksInFunclet.push_back(NewBlock);
1071 ColorVector &NewColors = BlockColors[NewBlock];
1072 assert(NewColors.empty() && "A new block should only have one color!");
1073 NewColors.push_back(FuncletPadBB);
1074
1075 DEBUG_WITH_TYPE("win-eh-prepare-coloring",
1076 dbgs() << " Assigned color \'" << FuncletPadBB->getName()
1077 << "\' to block \'" << NewBlock->getName()
1078 << "\'.\n");
1079
1080 llvm::erase(BlocksInFunclet, OldBlock);
1081 ColorVector &OldColors = BlockColors[OldBlock];
1082 llvm::erase(OldColors, FuncletPadBB);
1083
1084 DEBUG_WITH_TYPE("win-eh-prepare-coloring",
1085 dbgs() << " Removed color \'" << FuncletPadBB->getName()
1086 << "\' from block \'" << OldBlock->getName()
1087 << "\'.\n");
1088 }
1089
1090 // Loop over all of the instructions in this funclet, fixing up operand
1091 // references as we go. This uses VMap to do all the hard work.
1092 for (BasicBlock *BB : BlocksInFunclet)
1093 // Loop over all instructions, fixing each one as we find it...
1094 for (Instruction &I : *BB)
1095 RemapInstruction(&I, VMap,
1097
1098 // Catchrets targeting cloned blocks need to be updated separately from
1099 // the loop above because they are not in the current funclet.
1100 SmallVector<CatchReturnInst *, 2> FixupCatchrets;
1101 for (auto &BBMapping : Orig2Clone) {
1102 BasicBlock *OldBlock = BBMapping.first;
1103 BasicBlock *NewBlock = BBMapping.second;
1104
1105 FixupCatchrets.clear();
1106 for (BasicBlock *Pred : predecessors(OldBlock))
1107 if (auto *CatchRet = dyn_cast<CatchReturnInst>(Pred->getTerminator()))
1108 if (CatchRet->getCatchSwitchParentPad() == FuncletToken)
1109 FixupCatchrets.push_back(CatchRet);
1110
1111 for (CatchReturnInst *CatchRet : FixupCatchrets)
1112 CatchRet->setSuccessor(NewBlock);
1113 }
1114
1115 auto UpdatePHIOnClonedBlock = [&](PHINode *PN, bool IsForOldBlock) {
1117 [&](unsigned Idx) {
1118 BasicBlock *IncomingBlock = PN->getIncomingBlock(Idx);
1119 bool EdgeTargetsFunclet;
1120 if (auto *CRI =
1121 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
1122 EdgeTargetsFunclet =
1123 (CRI->getCatchSwitchParentPad() == FuncletToken);
1124 } else {
1125 ColorVector &IncomingColors = BlockColors[IncomingBlock];
1126 assert(!IncomingColors.empty() && "Block not colored!");
1127 assert(
1128 (IncomingColors.size() == 1 ||
1129 !llvm::is_contained(IncomingColors, FuncletPadBB)) &&
1130 "Cloning should leave this funclet's blocks monochromatic");
1131 EdgeTargetsFunclet = (IncomingColors.front() == FuncletPadBB);
1132 }
1133 return IsForOldBlock == EdgeTargetsFunclet;
1134 },
1135 /*DeletePHIIfEmpty=*/false);
1136 };
1137
1138 for (auto &BBMapping : Orig2Clone) {
1139 BasicBlock *OldBlock = BBMapping.first;
1140 BasicBlock *NewBlock = BBMapping.second;
1141 for (PHINode &OldPN : OldBlock->phis()) {
1142 UpdatePHIOnClonedBlock(&OldPN, /*IsForOldBlock=*/true);
1143 }
1144 for (PHINode &NewPN : NewBlock->phis()) {
1145 UpdatePHIOnClonedBlock(&NewPN, /*IsForOldBlock=*/false);
1146 }
1147 }
1148
1149 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to
1150 // the PHI nodes for NewBB now.
1151 for (auto &BBMapping : Orig2Clone) {
1152 BasicBlock *OldBlock = BBMapping.first;
1153 BasicBlock *NewBlock = BBMapping.second;
1154 for (BasicBlock *SuccBB : successors(NewBlock)) {
1155 for (PHINode &SuccPN : SuccBB->phis()) {
1156 // Ok, we have a PHI node. Figure out what the incoming value was for
1157 // the OldBlock.
1158 int OldBlockIdx = SuccPN.getBasicBlockIndex(OldBlock);
1159 if (OldBlockIdx == -1)
1160 break;
1161 Value *IV = SuccPN.getIncomingValue(OldBlockIdx);
1162
1163 // Remap the value if necessary.
1164 if (auto *Inst = dyn_cast<Instruction>(IV)) {
1165 ValueToValueMapTy::iterator I = VMap.find(Inst);
1166 if (I != VMap.end())
1167 IV = I->second;
1168 }
1169
1170 SuccPN.addIncoming(IV, NewBlock);
1171 }
1172 }
1173 }
1174
1175 for (ValueToValueMapTy::value_type VT : VMap) {
1176 // If there were values defined in BB that are used outside the funclet,
1177 // then we now have to update all uses of the value to use either the
1178 // original value, the cloned value, or some PHI derived value. This can
1179 // require arbitrary PHI insertion, of which we are prepared to do, clean
1180 // these up now.
1181 SmallVector<Use *, 16> UsesToRename;
1182
1183 auto *OldI = dyn_cast<Instruction>(const_cast<Value *>(VT.first));
1184 if (!OldI)
1185 continue;
1186 auto *NewI = cast<Instruction>(VT.second);
1187 // Scan all uses of this instruction to see if it is used outside of its
1188 // funclet, and if so, record them in UsesToRename.
1189 for (Use &U : OldI->uses()) {
1190 Instruction *UserI = cast<Instruction>(U.getUser());
1191 BasicBlock *UserBB = UserI->getParent();
1192 ColorVector &ColorsForUserBB = BlockColors[UserBB];
1193 assert(!ColorsForUserBB.empty());
1194 if (ColorsForUserBB.size() > 1 ||
1195 *ColorsForUserBB.begin() != FuncletPadBB)
1196 UsesToRename.push_back(&U);
1197 }
1198
1199 // If there are no uses outside the block, we're done with this
1200 // instruction.
1201 if (UsesToRename.empty())
1202 continue;
1203
1204 // We found a use of OldI outside of the funclet. Rename all uses of OldI
1205 // that are outside its funclet to be uses of the appropriate PHI node
1206 // etc.
1207 SSAUpdater SSAUpdate;
1208 SSAUpdate.Initialize(OldI->getType(), OldI->getName());
1209 SSAUpdate.AddAvailableValue(OldI->getParent(), OldI);
1210 SSAUpdate.AddAvailableValue(NewI->getParent(), NewI);
1211
1212 while (!UsesToRename.empty())
1213 SSAUpdate.RewriteUseAfterInsertions(*UsesToRename.pop_back_val());
1214 }
1215 }
1216
1217 return Changed;
1218}
1219
1220bool WinEHPrepareImpl::removeImplausibleInstructions(Function &F) {
1221 bool Changed = false;
1222
1223 // Remove implausible terminators and replace them with UnreachableInst.
1224 for (auto &Funclet : FuncletBlocks) {
1225 BasicBlock *FuncletPadBB = Funclet.first;
1226 std::vector<BasicBlock *> &BlocksInFunclet = Funclet.second;
1227 Instruction *FirstNonPHI = &*FuncletPadBB->getFirstNonPHIIt();
1228 auto *FuncletPad = dyn_cast<FuncletPadInst>(FirstNonPHI);
1229 auto *CatchPad = dyn_cast_or_null<CatchPadInst>(FuncletPad);
1230 auto *CleanupPad = dyn_cast_or_null<CleanupPadInst>(FuncletPad);
1231
1232 for (BasicBlock *BB : BlocksInFunclet) {
1233 for (Instruction &I : *BB) {
1234 auto *CB = dyn_cast<CallBase>(&I);
1235 if (!CB)
1236 continue;
1237
1238 Value *FuncletBundleOperand = nullptr;
1239 if (auto BU = CB->getOperandBundle(LLVMContext::OB_funclet))
1240 FuncletBundleOperand = BU->Inputs.front();
1241
1242 if (FuncletBundleOperand == FuncletPad)
1243 continue;
1244
1245 // Skip call sites which are nounwind intrinsics or inline asm.
1246 auto *CalledFn =
1247 dyn_cast<Function>(CB->getCalledOperand()->stripPointerCasts());
1248 if (CB->isInlineAsm() ||
1249 (CalledFn && CalledFn->isIntrinsic() && CB->doesNotThrow()))
1250 continue;
1251
1252 Changed = true;
1253
1254 // This call site was not part of this funclet, remove it.
1255 if (isa<InvokeInst>(CB)) {
1256 // Remove the unwind edge if it was an invoke.
1257 removeUnwindEdge(BB);
1258 // Get a pointer to the new call.
1259 BasicBlock::iterator CallI =
1260 std::prev(BB->getTerminator()->getIterator());
1261 auto *CI = cast<CallInst>(&*CallI);
1263 } else {
1265 }
1266
1267 // There are no more instructions in the block (except for unreachable),
1268 // we are done.
1269 break;
1270 }
1271
1272 Instruction *TI = BB->getTerminator();
1273 // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
1274 bool IsUnreachableRet = isa<ReturnInst>(TI) && FuncletPad;
1275 // The token consumed by a CatchReturnInst must match the funclet token.
1276 bool IsUnreachableCatchret = false;
1277 if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
1278 IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
1279 // The token consumed by a CleanupReturnInst must match the funclet token.
1280 bool IsUnreachableCleanupret = false;
1281 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
1282 IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
1283 if (IsUnreachableRet || IsUnreachableCatchret ||
1284 IsUnreachableCleanupret) {
1285 Changed = true;
1287 } else if (isa<InvokeInst>(TI)) {
1288 if (Personality == EHPersonality::MSVC_CXX && CleanupPad) {
1289 Changed = true;
1290 // Invokes within a cleanuppad for the MSVC++ personality never
1291 // transfer control to their unwind edge: the personality will
1292 // terminate the program.
1293 removeUnwindEdge(BB);
1294 }
1295 }
1296 }
1297 }
1298
1299 return Changed;
1300}
1301
1302bool WinEHPrepareImpl::cleanupPreparedFunclets(Function &F) {
1303 bool Changed = false;
1304
1305 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
1306 // branches, etc.
1309 Changed |= ConstantFoldTerminator(&BB, /*DeleteDeadConditions=*/true);
1311 }
1312
1313 // We might have some unreachable blocks after cleaning up some impossible
1314 // control flow.
1316
1317 return Changed;
1318}
1319
1320#ifndef NDEBUG
1321void WinEHPrepareImpl::verifyPreparedFunclets(Function &F) {
1322 for (BasicBlock &BB : F) {
1323 size_t NumColors = BlockColors[&BB].size();
1324 assert(NumColors == 1 && "Expected monochromatic BB!");
1325 if (NumColors == 0)
1326 report_fatal_error("Uncolored BB!");
1327 if (NumColors > 1)
1328 report_fatal_error("Multicolor BB!");
1329 assert((!Opts.win_eh_prepare_demotion ||
1330 !(BB.isEHPad() && isa<PHINode>(BB.begin()))) &&
1331 "EH Pad still has a PHI!");
1332 }
1333}
1334#endif
1335
1336bool WinEHPrepareImpl::prepareExplicitEH(Function &F) {
1337 // Remove unreachable blocks. It is not valuable to assign them a color and
1338 // their existence can trick us into thinking values are alive when they are
1339 // not.
1341
1342 // Determine which blocks are reachable from which funclet entries.
1343 colorFunclets(F);
1344
1345 Changed |= cloneCommonBlocks(F);
1346
1347 if (Opts.win_eh_prepare_demotion)
1348 Changed |= demotePHIsOnFunclets(F, DemoteCatchSwitchPHIOnly);
1349
1350 if (Opts.win_eh_prepare_cleanups) {
1351 assert(!verifyFunction(F, &dbgs()));
1352 Changed |= removeImplausibleInstructions(F);
1353
1354 assert(!verifyFunction(F, &dbgs()));
1355 Changed |= cleanupPreparedFunclets(F);
1356 }
1357
1358 LLVM_DEBUG(verifyPreparedFunclets(F));
1359 // Recolor the CFG to verify that all is well.
1360 LLVM_DEBUG(colorFunclets(F));
1361 LLVM_DEBUG(verifyPreparedFunclets(F));
1362
1363 return Changed;
1364}
1365
1366// TODO: Share loads when one use dominates another, or when a catchpad exit
1367// dominates uses (needs dominators).
1368AllocaInst *WinEHPrepareImpl::insertPHILoads(PHINode *PN, Function &F) {
1369 BasicBlock *PHIBlock = PN->getParent();
1370 AllocaInst *SpillSlot = nullptr;
1371 Instruction *EHPad = &*PHIBlock->getFirstNonPHIIt();
1372
1373 if (!EHPad->isTerminator()) {
1374 // If the EHPad isn't a terminator, then we can insert a load in this block
1375 // that will dominate all uses.
1376 SpillSlot = new AllocaInst(PN->getType(), DL->getAllocaAddrSpace(), nullptr,
1377 Twine(PN->getName(), ".wineh.spillslot"),
1378 F.getEntryBlock().begin());
1379 Value *V = new LoadInst(PN->getType(), SpillSlot,
1380 Twine(PN->getName(), ".wineh.reload"),
1381 PHIBlock->getFirstInsertionPt());
1382 PN->replaceAllUsesWith(V);
1383 return SpillSlot;
1384 }
1385
1386 // Otherwise, we have a PHI on a terminator EHPad, and we give up and insert
1387 // loads of the slot before every use.
1389 for (Use &U : llvm::make_early_inc_range(PN->uses())) {
1390 auto *UsingInst = cast<Instruction>(U.getUser());
1391 if (isa<PHINode>(UsingInst) && UsingInst->getParent()->isEHPad()) {
1392 // Use is on an EH pad phi. Leave it alone; we'll insert loads and
1393 // stores for it separately.
1394 continue;
1395 }
1396 replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
1397 }
1398 return SpillSlot;
1399}
1400
1401// TODO: improve store placement. Inserting at def is probably good, but need
1402// to be careful not to introduce interfering stores (needs liveness analysis).
1403// TODO: identify related phi nodes that can share spill slots, and share them
1404// (also needs liveness).
1405void WinEHPrepareImpl::insertPHIStores(PHINode *OriginalPHI,
1406 AllocaInst *SpillSlot) {
1407 // Use a worklist of (Block, Value) pairs -- the given Value needs to be
1408 // stored to the spill slot by the end of the given Block.
1410
1411 Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
1412
1413 while (!Worklist.empty()) {
1414 BasicBlock *EHBlock;
1415 Value *InVal;
1416 std::tie(EHBlock, InVal) = Worklist.pop_back_val();
1417
1418 PHINode *PN = dyn_cast<PHINode>(InVal);
1419 if (PN && PN->getParent() == EHBlock) {
1420 // The value is defined by another PHI we need to remove, with no room to
1421 // insert a store after the PHI, so each predecessor needs to store its
1422 // incoming value.
1423 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
1424 Value *PredVal = PN->getIncomingValue(i);
1425
1426 // Undef can safely be skipped.
1427 if (isa<UndefValue>(PredVal))
1428 continue;
1429
1430 insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
1431 }
1432 } else {
1433 // We need to store InVal, which dominates EHBlock, but can't put a store
1434 // in EHBlock, so need to put stores in each predecessor.
1435 for (BasicBlock *PredBlock : predecessors(EHBlock)) {
1436 insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
1437 }
1438 }
1439 }
1440}
1441
1442void WinEHPrepareImpl::insertPHIStore(
1443 BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
1444 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
1445
1446 if (PredBlock->isEHPad() && PredBlock->getFirstNonPHIIt()->isTerminator()) {
1447 // Pred is unsplittable, so we need to queue it on the worklist.
1448 Worklist.push_back({PredBlock, PredVal});
1449 return;
1450 }
1451
1452 // Otherwise, insert the store at the end of the basic block.
1453 new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator()->getIterator());
1454}
1455
1456void WinEHPrepareImpl::replaceUseWithLoad(
1457 Value *V, Use &U, AllocaInst *&SpillSlot,
1459 // Lazilly create the spill slot.
1460 if (!SpillSlot)
1461 SpillSlot = new AllocaInst(V->getType(), DL->getAllocaAddrSpace(), nullptr,
1462 Twine(V->getName(), ".wineh.spillslot"),
1463 F.getEntryBlock().begin());
1464
1465 auto *UsingInst = cast<Instruction>(U.getUser());
1466 if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
1467 // If this is a PHI node, we can't insert a load of the value before
1468 // the use. Instead insert the load in the predecessor block
1469 // corresponding to the incoming value.
1470 //
1471 // Note that if there are multiple edges from a basic block to this
1472 // PHI node that we cannot have multiple loads. The problem is that
1473 // the resulting PHI node will have multiple values (from each load)
1474 // coming in from the same block, which is illegal SSA form.
1475 // For this reason, we keep track of and reuse loads we insert.
1476 BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
1477 if (auto *CatchRet =
1478 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
1479 // Putting a load above a catchret and use on the phi would still leave
1480 // a cross-funclet def/use. We need to split the edge, change the
1481 // catchret to target the new block, and put the load there.
1482 BasicBlock *PHIBlock = UsingInst->getParent();
1483 BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
1484 // SplitEdge gives us:
1485 // IncomingBlock:
1486 // ...
1487 // br label %NewBlock
1488 // NewBlock:
1489 // catchret label %PHIBlock
1490 // But we need:
1491 // IncomingBlock:
1492 // ...
1493 // catchret label %NewBlock
1494 // NewBlock:
1495 // br label %PHIBlock
1496 // So move the terminators to each others' blocks and swap their
1497 // successors.
1498 UncondBrInst *Goto = cast<UncondBrInst>(IncomingBlock->getTerminator());
1499 Goto->removeFromParent();
1500 CatchRet->removeFromParent();
1501 CatchRet->insertInto(IncomingBlock, IncomingBlock->end());
1502 Goto->insertInto(NewBlock, NewBlock->end());
1503 Goto->setSuccessor(PHIBlock);
1504 CatchRet->setSuccessor(NewBlock);
1505 // Update the color mapping for the newly split edge.
1506 // Grab a reference to the ColorVector to be inserted before getting the
1507 // reference to the vector we are copying because inserting the new
1508 // element in BlockColors might cause the map to be reallocated.
1509 ColorVector &ColorsForNewBlock = BlockColors[NewBlock];
1510 ColorVector &ColorsForPHIBlock = BlockColors[PHIBlock];
1511 ColorsForNewBlock = ColorsForPHIBlock;
1512 for (BasicBlock *FuncletPad : ColorsForPHIBlock)
1513 FuncletBlocks[FuncletPad].push_back(NewBlock);
1514 // Treat the new block as incoming for load insertion.
1515 IncomingBlock = NewBlock;
1516 }
1517 Value *&Load = Loads[IncomingBlock];
1518 // Insert the load into the predecessor block
1519 if (!Load)
1520 Load = new LoadInst(
1521 V->getType(), SpillSlot, Twine(V->getName(), ".wineh.reload"),
1522 /*isVolatile=*/false, IncomingBlock->getTerminator()->getIterator());
1523
1524 U.set(Load);
1525 } else {
1526 // Reload right before the old use.
1527 auto *Load = new LoadInst(V->getType(), SpillSlot,
1528 Twine(V->getName(), ".wineh.reload"),
1529 /*isVolatile=*/false, UsingInst->getIterator());
1530 U.set(Load);
1531 }
1532}
1533
1535 MCSymbol *InvokeBegin,
1536 MCSymbol *InvokeEnd) {
1537 assert(InvokeStateMap.count(II) &&
1538 "should get invoke with precomputed state");
1539 LabelToStateMap[InvokeBegin] = std::make_pair(InvokeStateMap[II], InvokeEnd);
1540}
1541
1542void WinEHFuncInfo::addIPToStateRange(int State, MCSymbol* InvokeBegin,
1543 MCSymbol* InvokeEnd) {
1544 LabelToStateMap[InvokeBegin] = std::make_pair(State, InvokeEnd);
1545}
1546
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
ManagedStatic< HTTPClientCleanup > Cleanup
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
nvptx lower args
uint64_t IntrinsicInst * II
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains some templates that are useful if you are working with the STL at all.
#define LLVM_DEBUG(...)
Definition Debug.h:119
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition Debug.h:72
static bool isMalformedCatchpad(const CatchPadInst *CPI, EHPersonality Personality)
static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState, const BasicBlock *BB)
static void calculateStateNumbersForInvokes(const Function *Fn, WinEHFuncInfo &FuncInfo)
static BasicBlock * getCleanupRetUnwindDest(const CleanupPadInst *CleanupPad)
static int addSEHFinally(WinEHFuncInfo &FuncInfo, int ParentState, const BasicBlock *Handler)
static const BasicBlock * getEHPadFromPredecessor(const BasicBlock *BB, Value *ParentPad)
static int addClrEHHandler(WinEHFuncInfo &FuncInfo, int HandlerParentState, int TryParentState, ClrHandlerType HandlerType, uint32_t TypeToken, const BasicBlock *Handler)
static void calculateCXXStateNumbers(WinEHFuncInfo &FuncInfo, const Instruction *FirstNonPHI, int ParentState)
static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow, int TryHigh, int CatchHigh, ArrayRef< const CatchPadInst * > Handlers)
static bool isTopLevelPadForMSVC(const Instruction *EHPad)
static int addSEHExcept(WinEHFuncInfo &FuncInfo, int ParentState, const Function *Filter, const BasicBlock *Handler)
static const uint32_t IV[8]
Definition blake3_impl.h:83
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator end()
Definition BasicBlock.h:452
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:508
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:170
const Instruction & front() const
Definition BasicBlock.h:462
LLVM_ABI void insertInto(Function *Parent, BasicBlock *InsertBefore=nullptr)
Insert unlinked basic block into a function.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition BasicBlock.h:682
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
CatchSwitchInst * getCatchSwitch() const
Convenience accessors.
handler_range handlers()
iteration adapter for range-for loops.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
This is an important base class in LLVM.
Definition Constant.h:44
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
const Constant * stripPointerCasts() const
Definition Constant.h:243
unsigned arg_size() const
arg_size - Return the number of funcletpad arguments.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
const BasicBlock & getEntryBlock() const
Definition Function.h:803
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:356
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:247
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:899
Constant * getPersonalityFn() const
Get the personality function associated with this function.
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:252
Module * getParent()
Get the module that this global value is contained inside of...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
bool isTerminator() const
iterator_range< user_iterator > users()
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
An instruction for reading from memory.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:377
LLVM_ABI void removeIncomingValueIf(function_ref< bool(unsigned)> Predicate, bool DeletePHIIfEmpty=true)
Remove all incoming values for which the predicate returns true.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition SSAUpdater.h:39
LLVM_ABI void RewriteUseAfterInsertions(Use &U)
Rewrite a use like RewriteUse but handling in-block definitions.
LLVM_ABI void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
LLVM_ABI void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
void push_back(EltTy NewVal)
EltTy front() const
unsigned size() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
Unconditional Branch instruction.
void setSuccessor(BasicBlock *NewSucc)
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
std::pair< const Value *, WeakTrackingVH > value_type
Definition ValueMap.h:101
iterator find(const KeyT &Val)
Definition ValueMap.h:160
iterator end()
Definition ValueMap.h:139
ValueMapIteratorImpl< MapT, const Value *, false > iterator
Definition ValueMap.h:135
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI FunctionPass * createWinEHPass()
createWinEHPass - Prepares personality functions used by MSVC on Windows, in addition to the Itanium ...
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition Local.cpp:133
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
Definition Local.cpp:715
LLVM_ABI void calculateWinCXXEHStateNumbers(const Function *ParentFn, WinEHFuncInfo &FuncInfo)
Analyze the IR in ParentFn and it's handlers to build WinEHFuncInfo, which describes the state number...
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool FoldInstsToUnreachable=true)
Remove all blocks that can not be reached from the function's entry.
Definition Local.cpp:2960
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2220
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:97
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:79
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI Instruction * removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Replace 'BB's terminator with one that does not have an unwind successor block.
Definition Local.cpp:2922
LLVM_ABI void calculateSEHStateForAsynchEH(const BasicBlock *BB, int State, WinEHFuncInfo &FuncInfo)
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
Definition Local.cpp:2592
LLVM_ABI void calculateCXXStateForAsynchEH(const BasicBlock *BB, int State, WinEHFuncInfo &FuncInfo)
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
LLVM_ABI void calculateSEHStateNumbers(const Function *ParentFn, WinEHFuncInfo &FuncInfo)
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
TinyPtrVector< BasicBlock * > ColorVector
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
LLVM_ABI void calculateClrEHStateNumbers(const Function *Fn, WinEHFuncInfo &FuncInfo)
const BasicBlock * Block
WorkItem(const BasicBlock *BB, int St)
int HandlerParentState
Outer handler enclosing this entry's handler.
MBBOrBasicBlock Cleanup
Similar to CxxUnwindMapEntry, but supports SEH filters.
int ToState
If unwinding continues through this handler, transition to the handler at this state.
LLVM_ABI void addIPToStateRange(const InvokeInst *II, MCSymbol *InvokeBegin, MCSymbol *InvokeEnd)
SmallVector< SEHUnwindMapEntry, 4 > SEHUnwindMap
SmallVector< ClrEHUnwindMapEntry, 4 > ClrEHUnwindMap
DenseMap< const FuncletPadInst *, int > FuncletBaseStateMap
DenseMap< const BasicBlock *, int > BlockToStateMap
DenseMap< const InvokeInst *, int > InvokeStateMap
SmallVector< WinEHTryBlockMapEntry, 4 > TryBlockMap
DenseMap< const Instruction *, int > EHPadStateMap
LLVM_ABI WinEHFuncInfo()
DenseMap< MCSymbol *, std::pair< int, MCSymbol * > > LabelToStateMap
SmallVector< CxxUnwindMapEntry, 4 > CxxUnwindMap
int getLastStateNumber() const
GlobalVariable * TypeDescriptor
union llvm::WinEHHandlerType::@246205307012256373115155017221207221353102114334 CatchObj
The CatchObj starts out life as an LLVM alloca and is eventually turned frame index.
const AllocaInst * Alloca
MBBOrBasicBlock Handler
SmallVector< WinEHHandlerType, 1 > HandlerArray