xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/WinException.cpp (revision 5e3190f700637fcfc1a52daeaa4a031fdd2557c7)
1 //===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
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 file contains support for writing Win64 exception info into asm files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "WinException.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/BinaryFormat/COFF.h"
16 #include "llvm/BinaryFormat/Dwarf.h"
17 #include "llvm/CodeGen/AsmPrinter.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/CodeGen/TargetFrameLowering.h"
22 #include "llvm/CodeGen/TargetLowering.h"
23 #include "llvm/CodeGen/TargetSubtargetInfo.h"
24 #include "llvm/CodeGen/WinEHFuncInfo.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "llvm/Target/TargetMachine.h"
33 using namespace llvm;
34 
35 WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
36   // MSVC's EH tables are always composed of 32-bit words.  All known 64-bit
37   // platforms use an imagerel32 relocation to refer to symbols.
38   useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
39   isAArch64 = Asm->TM.getTargetTriple().isAArch64();
40   isThumb = Asm->TM.getTargetTriple().isThumb();
41 }
42 
43 WinException::~WinException() = default;
44 
45 /// endModule - Emit all exception information that should come after the
46 /// content.
47 void WinException::endModule() {
48   auto &OS = *Asm->OutStreamer;
49   const Module *M = MMI->getModule();
50   for (const Function &F : *M)
51     if (F.hasFnAttribute("safeseh"))
52       OS.emitCOFFSafeSEH(Asm->getSymbol(&F));
53 
54   if (M->getModuleFlag("ehcontguard") && !EHContTargets.empty()) {
55     // Emit the symbol index of each ehcont target.
56     OS.switchSection(Asm->OutContext.getObjectFileInfo()->getGEHContSection());
57     for (const MCSymbol *S : EHContTargets) {
58       OS.emitCOFFSymbolIndex(S);
59     }
60   }
61 }
62 
63 void WinException::beginFunction(const MachineFunction *MF) {
64   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
65 
66   // If any landing pads survive, we need an EH table.
67   bool hasLandingPads = !MF->getLandingPads().empty();
68   bool hasEHFunclets = MF->hasEHFunclets();
69 
70   const Function &F = MF->getFunction();
71 
72   shouldEmitMoves = Asm->needsSEHMoves() && MF->hasWinCFI();
73 
74   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
75   unsigned PerEncoding = TLOF.getPersonalityEncoding();
76 
77   EHPersonality Per = EHPersonality::Unknown;
78   const Function *PerFn = nullptr;
79   if (F.hasPersonalityFn()) {
80     PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
81     Per = classifyEHPersonality(PerFn);
82   }
83 
84   bool forceEmitPersonality = F.hasPersonalityFn() &&
85                               !isNoOpWithoutInvoke(Per) &&
86                               F.needsUnwindTableEntry();
87 
88   shouldEmitPersonality =
89       forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
90                                PerEncoding != dwarf::DW_EH_PE_omit && PerFn);
91 
92   unsigned LSDAEncoding = TLOF.getLSDAEncoding();
93   shouldEmitLSDA = shouldEmitPersonality &&
94     LSDAEncoding != dwarf::DW_EH_PE_omit;
95 
96   // If we're not using CFI, we don't want the CFI or the personality, but we
97   // might want EH tables if we had EH pads.
98   if (!Asm->MAI->usesWindowsCFI()) {
99     if (Per == EHPersonality::MSVC_X86SEH && !hasEHFunclets) {
100       // If this is 32-bit SEH and we don't have any funclets (really invokes),
101       // make sure we emit the parent offset label. Some unreferenced filter
102       // functions may still refer to it.
103       const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
104       StringRef FLinkageName =
105           GlobalValue::dropLLVMManglingEscape(MF->getFunction().getName());
106       emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
107     }
108     shouldEmitLSDA = hasEHFunclets;
109     shouldEmitPersonality = false;
110     return;
111   }
112 
113   beginFunclet(MF->front(), Asm->CurrentFnSym);
114 }
115 
116 void WinException::markFunctionEnd() {
117   if (isAArch64 && CurrentFuncletEntry &&
118       (shouldEmitMoves || shouldEmitPersonality))
119     Asm->OutStreamer->emitWinCFIFuncletOrFuncEnd();
120 }
121 
122 /// endFunction - Gather and emit post-function exception information.
123 ///
124 void WinException::endFunction(const MachineFunction *MF) {
125   if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
126     return;
127 
128   const Function &F = MF->getFunction();
129   EHPersonality Per = EHPersonality::Unknown;
130   if (F.hasPersonalityFn())
131     Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
132 
133   endFuncletImpl();
134 
135   // endFunclet will emit the necessary .xdata tables for table-based SEH.
136   if (Per == EHPersonality::MSVC_TableSEH && MF->hasEHFunclets())
137     return;
138 
139   if (shouldEmitPersonality || shouldEmitLSDA) {
140     Asm->OutStreamer->pushSection();
141 
142     // Just switch sections to the right xdata section.
143     MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
144         Asm->OutStreamer->getCurrentSectionOnly());
145     Asm->OutStreamer->switchSection(XData);
146 
147     // Emit the tables appropriate to the personality function in use. If we
148     // don't recognize the personality, assume it uses an Itanium-style LSDA.
149     if (Per == EHPersonality::MSVC_TableSEH)
150       emitCSpecificHandlerTable(MF);
151     else if (Per == EHPersonality::MSVC_X86SEH)
152       emitExceptHandlerTable(MF);
153     else if (Per == EHPersonality::MSVC_CXX)
154       emitCXXFrameHandler3Table(MF);
155     else if (Per == EHPersonality::CoreCLR)
156       emitCLRExceptionTable(MF);
157     else
158       emitExceptionTable();
159 
160     Asm->OutStreamer->popSection();
161   }
162 
163   if (!MF->getCatchretTargets().empty()) {
164     // Copy the function's catchret targets to a module-level list.
165     EHContTargets.insert(EHContTargets.end(), MF->getCatchretTargets().begin(),
166                          MF->getCatchretTargets().end());
167   }
168 }
169 
170 /// Retrieve the MCSymbol for a GlobalValue or MachineBasicBlock.
171 static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
172                                    const MachineBasicBlock *MBB) {
173   if (!MBB)
174     return nullptr;
175 
176   assert(MBB->isEHFuncletEntry());
177 
178   // Give catches and cleanups a name based off of their parent function and
179   // their funclet entry block's number.
180   const MachineFunction *MF = MBB->getParent();
181   const Function &F = MF->getFunction();
182   StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
183   MCContext &Ctx = MF->getContext();
184   StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
185   return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
186                                Twine(MBB->getNumber()) + "@?0?" +
187                                FuncLinkageName + "@4HA");
188 }
189 
190 void WinException::beginFunclet(const MachineBasicBlock &MBB,
191                                 MCSymbol *Sym) {
192   CurrentFuncletEntry = &MBB;
193 
194   const Function &F = Asm->MF->getFunction();
195   // If a symbol was not provided for the funclet, invent one.
196   if (!Sym) {
197     Sym = getMCSymbolForMBB(Asm, &MBB);
198 
199     // Describe our funclet symbol as a function with internal linkage.
200     Asm->OutStreamer->beginCOFFSymbolDef(Sym);
201     Asm->OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
202     Asm->OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
203                                          << COFF::SCT_COMPLEX_TYPE_SHIFT);
204     Asm->OutStreamer->endCOFFSymbolDef();
205 
206     // We want our funclet's entry point to be aligned such that no nops will be
207     // present after the label.
208     Asm->emitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
209                        &F);
210 
211     // Now that we've emitted the alignment directive, point at our funclet.
212     Asm->OutStreamer->emitLabel(Sym);
213   }
214 
215   // Mark 'Sym' as starting our funclet.
216   if (shouldEmitMoves || shouldEmitPersonality) {
217     CurrentFuncletTextSection = Asm->OutStreamer->getCurrentSectionOnly();
218     Asm->OutStreamer->emitWinCFIStartProc(Sym);
219   }
220 
221   if (shouldEmitPersonality) {
222     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
223     const Function *PerFn = nullptr;
224 
225     // Determine which personality routine we are using for this funclet.
226     if (F.hasPersonalityFn())
227       PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
228     const MCSymbol *PersHandlerSym =
229         TLOF.getCFIPersonalitySymbol(PerFn, Asm->TM, MMI);
230 
231     // Do not emit a .seh_handler directives for cleanup funclets.
232     // FIXME: This means cleanup funclets cannot handle exceptions. Given that
233     // Clang doesn't produce EH constructs inside cleanup funclets and LLVM's
234     // inliner doesn't allow inlining them, this isn't a major problem in
235     // practice.
236     if (!CurrentFuncletEntry->isCleanupFuncletEntry())
237       Asm->OutStreamer->emitWinEHHandler(PersHandlerSym, true, true);
238   }
239 }
240 
241 void WinException::endFunclet() {
242   if (isAArch64 && CurrentFuncletEntry &&
243       (shouldEmitMoves || shouldEmitPersonality)) {
244     Asm->OutStreamer->switchSection(CurrentFuncletTextSection);
245     Asm->OutStreamer->emitWinCFIFuncletOrFuncEnd();
246   }
247   endFuncletImpl();
248 }
249 
250 void WinException::endFuncletImpl() {
251   // No funclet to process?  Great, we have nothing to do.
252   if (!CurrentFuncletEntry)
253     return;
254 
255   const MachineFunction *MF = Asm->MF;
256   if (shouldEmitMoves || shouldEmitPersonality) {
257     const Function &F = MF->getFunction();
258     EHPersonality Per = EHPersonality::Unknown;
259     if (F.hasPersonalityFn())
260       Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
261 
262     if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
263         !CurrentFuncletEntry->isCleanupFuncletEntry()) {
264       // Emit an UNWIND_INFO struct describing the prologue.
265       Asm->OutStreamer->emitWinEHHandlerData();
266 
267       // If this is a C++ catch funclet (or the parent function),
268       // emit a reference to the LSDA for the parent function.
269       StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
270       MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
271           Twine("$cppxdata$", FuncLinkageName));
272       Asm->OutStreamer->emitValue(create32bitRef(FuncInfoXData), 4);
273     } else if (Per == EHPersonality::MSVC_TableSEH && MF->hasEHFunclets() &&
274                !CurrentFuncletEntry->isEHFuncletEntry()) {
275       // Emit an UNWIND_INFO struct describing the prologue.
276       Asm->OutStreamer->emitWinEHHandlerData();
277 
278       // If this is the parent function in Win64 SEH, emit the LSDA immediately
279       // following .seh_handlerdata.
280       emitCSpecificHandlerTable(MF);
281     } else if (shouldEmitPersonality || shouldEmitLSDA) {
282       // Emit an UNWIND_INFO struct describing the prologue.
283       Asm->OutStreamer->emitWinEHHandlerData();
284       // In these cases, no further info is written to the .xdata section
285       // right here, but is written by e.g. emitExceptionTable in endFunction()
286       // above.
287     } else {
288       // No need to emit the EH handler data right here if nothing needs
289       // writing to the .xdata section; it will be emitted for all
290       // functions that need it in the end anyway.
291     }
292 
293     // Switch back to the funclet start .text section now that we are done
294     // writing to .xdata, and emit an .seh_endproc directive to mark the end of
295     // the function.
296     Asm->OutStreamer->switchSection(CurrentFuncletTextSection);
297     Asm->OutStreamer->emitWinCFIEndProc();
298   }
299 
300   // Let's make sure we don't try to end the same funclet twice.
301   CurrentFuncletEntry = nullptr;
302 }
303 
304 const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
305   if (!Value)
306     return MCConstantExpr::create(0, Asm->OutContext);
307   return MCSymbolRefExpr::create(Value, useImageRel32
308                                             ? MCSymbolRefExpr::VK_COFF_IMGREL32
309                                             : MCSymbolRefExpr::VK_None,
310                                  Asm->OutContext);
311 }
312 
313 const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
314   if (!GV)
315     return MCConstantExpr::create(0, Asm->OutContext);
316   return create32bitRef(Asm->getSymbol(GV));
317 }
318 
319 const MCExpr *WinException::getLabel(const MCSymbol *Label) {
320   return MCSymbolRefExpr::create(Label, MCSymbolRefExpr::VK_COFF_IMGREL32,
321                                  Asm->OutContext);
322 }
323 
324 const MCExpr *WinException::getLabelPlusOne(const MCSymbol *Label) {
325   return MCBinaryExpr::createAdd(getLabel(Label),
326                                  MCConstantExpr::create(1, Asm->OutContext),
327                                  Asm->OutContext);
328 }
329 
330 const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
331                                       const MCSymbol *OffsetFrom) {
332   return MCBinaryExpr::createSub(
333       MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
334       MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
335 }
336 
337 const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
338                                              const MCSymbol *OffsetFrom) {
339   return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
340                                  MCConstantExpr::create(1, Asm->OutContext),
341                                  Asm->OutContext);
342 }
343 
344 int WinException::getFrameIndexOffset(int FrameIndex,
345                                       const WinEHFuncInfo &FuncInfo) {
346   const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
347   Register UnusedReg;
348   if (Asm->MAI->usesWindowsCFI()) {
349     StackOffset Offset =
350         TFI.getFrameIndexReferencePreferSP(*Asm->MF, FrameIndex, UnusedReg,
351                                            /*IgnoreSPUpdates*/ true);
352     assert(UnusedReg ==
353            Asm->MF->getSubtarget()
354                .getTargetLowering()
355                ->getStackPointerRegisterToSaveRestore());
356     return Offset.getFixed();
357   }
358 
359   // For 32-bit, offsets should be relative to the end of the EH registration
360   // node. For 64-bit, it's relative to SP at the end of the prologue.
361   assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
362   StackOffset Offset = TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
363   Offset += StackOffset::getFixed(FuncInfo.EHRegNodeEndOffset);
364   assert(!Offset.getScalable() &&
365          "Frame offsets with a scalable component are not supported");
366   return Offset.getFixed();
367 }
368 
369 namespace {
370 
371 /// Top-level state used to represent unwind to caller
372 const int NullState = -1;
373 
374 struct InvokeStateChange {
375   /// EH Label immediately after the last invoke in the previous state, or
376   /// nullptr if the previous state was the null state.
377   const MCSymbol *PreviousEndLabel;
378 
379   /// EH label immediately before the first invoke in the new state, or nullptr
380   /// if the new state is the null state.
381   const MCSymbol *NewStartLabel;
382 
383   /// State of the invoke following NewStartLabel, or NullState to indicate
384   /// the presence of calls which may unwind to caller.
385   int NewState;
386 };
387 
388 /// Iterator that reports all the invoke state changes in a range of machine
389 /// basic blocks.  Changes to the null state are reported whenever a call that
390 /// may unwind to caller is encountered.  The MBB range is expected to be an
391 /// entire function or funclet, and the start and end of the range are treated
392 /// as being in the NullState even if there's not an unwind-to-caller call
393 /// before the first invoke or after the last one (i.e., the first state change
394 /// reported is the first change to something other than NullState, and a
395 /// change back to NullState is always reported at the end of iteration).
396 class InvokeStateChangeIterator {
397   InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
398                             MachineFunction::const_iterator MFI,
399                             MachineFunction::const_iterator MFE,
400                             MachineBasicBlock::const_iterator MBBI,
401                             int BaseState)
402       : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
403     LastStateChange.PreviousEndLabel = nullptr;
404     LastStateChange.NewStartLabel = nullptr;
405     LastStateChange.NewState = BaseState;
406     scan();
407   }
408 
409 public:
410   static iterator_range<InvokeStateChangeIterator>
411   range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
412         MachineFunction::const_iterator End, int BaseState = NullState) {
413     // Reject empty ranges to simplify bookkeeping by ensuring that we can get
414     // the end of the last block.
415     assert(Begin != End);
416     auto BlockBegin = Begin->begin();
417     auto BlockEnd = std::prev(End)->end();
418     return make_range(
419         InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
420         InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
421   }
422 
423   // Iterator methods.
424   bool operator==(const InvokeStateChangeIterator &O) const {
425     assert(BaseState == O.BaseState);
426     // Must be visiting same block.
427     if (MFI != O.MFI)
428       return false;
429     // Must be visiting same isntr.
430     if (MBBI != O.MBBI)
431       return false;
432     // At end of block/instr iteration, we can still have two distinct states:
433     // one to report the final EndLabel, and another indicating the end of the
434     // state change iteration.  Check for CurrentEndLabel equality to
435     // distinguish these.
436     return CurrentEndLabel == O.CurrentEndLabel;
437   }
438 
439   bool operator!=(const InvokeStateChangeIterator &O) const {
440     return !operator==(O);
441   }
442   InvokeStateChange &operator*() { return LastStateChange; }
443   InvokeStateChange *operator->() { return &LastStateChange; }
444   InvokeStateChangeIterator &operator++() { return scan(); }
445 
446 private:
447   InvokeStateChangeIterator &scan();
448 
449   const WinEHFuncInfo &EHInfo;
450   const MCSymbol *CurrentEndLabel = nullptr;
451   MachineFunction::const_iterator MFI;
452   MachineFunction::const_iterator MFE;
453   MachineBasicBlock::const_iterator MBBI;
454   InvokeStateChange LastStateChange;
455   bool VisitingInvoke = false;
456   int BaseState;
457 };
458 
459 } // end anonymous namespace
460 
461 InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
462   bool IsNewBlock = false;
463   for (; MFI != MFE; ++MFI, IsNewBlock = true) {
464     if (IsNewBlock)
465       MBBI = MFI->begin();
466     for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
467       const MachineInstr &MI = *MBBI;
468       if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
469           MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
470         // Indicate a change of state to the null state.  We don't have
471         // start/end EH labels handy but the caller won't expect them for
472         // null state regions.
473         LastStateChange.PreviousEndLabel = CurrentEndLabel;
474         LastStateChange.NewStartLabel = nullptr;
475         LastStateChange.NewState = BaseState;
476         CurrentEndLabel = nullptr;
477         // Don't re-visit this instr on the next scan
478         ++MBBI;
479         return *this;
480       }
481 
482       // All other state changes are at EH labels before/after invokes.
483       if (!MI.isEHLabel())
484         continue;
485       MCSymbol *Label = MI.getOperand(0).getMCSymbol();
486       if (Label == CurrentEndLabel) {
487         VisitingInvoke = false;
488         continue;
489       }
490       auto InvokeMapIter = EHInfo.LabelToStateMap.find(Label);
491       // Ignore EH labels that aren't the ones inserted before an invoke
492       if (InvokeMapIter == EHInfo.LabelToStateMap.end())
493         continue;
494       auto &StateAndEnd = InvokeMapIter->second;
495       int NewState = StateAndEnd.first;
496       // Keep track of the fact that we're between EH start/end labels so
497       // we know not to treat the inoke we'll see as unwinding to caller.
498       VisitingInvoke = true;
499       if (NewState == LastStateChange.NewState) {
500         // The state isn't actually changing here.  Record the new end and
501         // keep going.
502         CurrentEndLabel = StateAndEnd.second;
503         continue;
504       }
505       // Found a state change to report
506       LastStateChange.PreviousEndLabel = CurrentEndLabel;
507       LastStateChange.NewStartLabel = Label;
508       LastStateChange.NewState = NewState;
509       // Start keeping track of the new current end
510       CurrentEndLabel = StateAndEnd.second;
511       // Don't re-visit this instr on the next scan
512       ++MBBI;
513       return *this;
514     }
515   }
516   // Iteration hit the end of the block range.
517   if (LastStateChange.NewState != BaseState) {
518     // Report the end of the last new state
519     LastStateChange.PreviousEndLabel = CurrentEndLabel;
520     LastStateChange.NewStartLabel = nullptr;
521     LastStateChange.NewState = BaseState;
522     // Leave CurrentEndLabel non-null to distinguish this state from end.
523     assert(CurrentEndLabel != nullptr);
524     return *this;
525   }
526   // We've reported all state changes and hit the end state.
527   CurrentEndLabel = nullptr;
528   return *this;
529 }
530 
531 /// Emit the language-specific data that __C_specific_handler expects.  This
532 /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
533 /// up after faults with __try, __except, and __finally.  The typeinfo values
534 /// are not really RTTI data, but pointers to filter functions that return an
535 /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
536 /// blocks and other cleanups, the landing pad label is zero, and the filter
537 /// function is actually a cleanup handler with the same prototype.  A catch-all
538 /// entry is modeled with a null filter function field and a non-zero landing
539 /// pad label.
540 ///
541 /// Possible filter function return values:
542 ///   EXCEPTION_EXECUTE_HANDLER (1):
543 ///     Jump to the landing pad label after cleanups.
544 ///   EXCEPTION_CONTINUE_SEARCH (0):
545 ///     Continue searching this table or continue unwinding.
546 ///   EXCEPTION_CONTINUE_EXECUTION (-1):
547 ///     Resume execution at the trapping PC.
548 ///
549 /// Inferred table structure:
550 ///   struct Table {
551 ///     int NumEntries;
552 ///     struct Entry {
553 ///       imagerel32 LabelStart;       // Inclusive
554 ///       imagerel32 LabelEnd;         // Exclusive
555 ///       imagerel32 FilterOrFinally;  // One means catch-all.
556 ///       imagerel32 LabelLPad;        // Zero means __finally.
557 ///     } Entries[NumEntries];
558 ///   };
559 void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
560   auto &OS = *Asm->OutStreamer;
561   MCContext &Ctx = Asm->OutContext;
562   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
563 
564   bool VerboseAsm = OS.isVerboseAsm();
565   auto AddComment = [&](const Twine &Comment) {
566     if (VerboseAsm)
567       OS.AddComment(Comment);
568   };
569 
570   if (!isAArch64) {
571     // Emit a label assignment with the SEH frame offset so we can use it for
572     // llvm.eh.recoverfp.
573     StringRef FLinkageName =
574         GlobalValue::dropLLVMManglingEscape(MF->getFunction().getName());
575     MCSymbol *ParentFrameOffset =
576         Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
577     const MCExpr *MCOffset =
578         MCConstantExpr::create(FuncInfo.SEHSetFrameOffset, Ctx);
579     Asm->OutStreamer->emitAssignment(ParentFrameOffset, MCOffset);
580   }
581 
582   // Use the assembler to compute the number of table entries through label
583   // difference and division.
584   MCSymbol *TableBegin =
585       Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
586   MCSymbol *TableEnd =
587       Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
588   const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
589   const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
590   const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
591   AddComment("Number of call sites");
592   OS.emitValue(EntryCount, 4);
593 
594   OS.emitLabel(TableBegin);
595 
596   // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
597   // models exceptions from invokes. LLVM also allows arbitrary reordering of
598   // the code, so our tables end up looking a bit different. Rather than
599   // trying to match MSVC's tables exactly, we emit a denormalized table.  For
600   // each range of invokes in the same state, we emit table entries for all
601   // the actions that would be taken in that state. This means our tables are
602   // slightly bigger, which is OK.
603   const MCSymbol *LastStartLabel = nullptr;
604   int LastEHState = -1;
605   // Break out before we enter into a finally funclet.
606   // FIXME: We need to emit separate EH tables for cleanups.
607   MachineFunction::const_iterator End = MF->end();
608   MachineFunction::const_iterator Stop = std::next(MF->begin());
609   while (Stop != End && !Stop->isEHFuncletEntry())
610     ++Stop;
611   for (const auto &StateChange :
612        InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
613     // Emit all the actions for the state we just transitioned out of
614     // if it was not the null state
615     if (LastEHState != -1)
616       emitSEHActionsForRange(FuncInfo, LastStartLabel,
617                              StateChange.PreviousEndLabel, LastEHState);
618     LastStartLabel = StateChange.NewStartLabel;
619     LastEHState = StateChange.NewState;
620   }
621 
622   OS.emitLabel(TableEnd);
623 }
624 
625 void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
626                                           const MCSymbol *BeginLabel,
627                                           const MCSymbol *EndLabel, int State) {
628   auto &OS = *Asm->OutStreamer;
629   MCContext &Ctx = Asm->OutContext;
630   bool VerboseAsm = OS.isVerboseAsm();
631   auto AddComment = [&](const Twine &Comment) {
632     if (VerboseAsm)
633       OS.AddComment(Comment);
634   };
635 
636   assert(BeginLabel && EndLabel);
637   while (State != -1) {
638     const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
639     const MCExpr *FilterOrFinally;
640     const MCExpr *ExceptOrNull;
641     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
642     if (UME.IsFinally) {
643       FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
644       ExceptOrNull = MCConstantExpr::create(0, Ctx);
645     } else {
646       // For an except, the filter can be 1 (catch-all) or a function
647       // label.
648       FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
649                                    : MCConstantExpr::create(1, Ctx);
650       ExceptOrNull = create32bitRef(Handler->getSymbol());
651     }
652 
653     AddComment("LabelStart");
654     OS.emitValue(getLabel(BeginLabel), 4);
655     AddComment("LabelEnd");
656     OS.emitValue(getLabelPlusOne(EndLabel), 4);
657     AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
658                                                              : "CatchAll");
659     OS.emitValue(FilterOrFinally, 4);
660     AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
661     OS.emitValue(ExceptOrNull, 4);
662 
663     assert(UME.ToState < State && "states should decrease");
664     State = UME.ToState;
665   }
666 }
667 
668 void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
669   const Function &F = MF->getFunction();
670   auto &OS = *Asm->OutStreamer;
671   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
672 
673   StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
674 
675   SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
676   MCSymbol *FuncInfoXData = nullptr;
677   if (shouldEmitPersonality) {
678     // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
679     // IPs to state numbers.
680     FuncInfoXData =
681         Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
682     computeIP2StateTable(MF, FuncInfo, IPToStateTable);
683   } else {
684     FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
685   }
686 
687   int UnwindHelpOffset = 0;
688   // TODO: The check for UnwindHelpFrameIdx against max() below (and the
689   // second check further below) can be removed if MS C++ unwinding is
690   // implemented for ARM, when test/CodeGen/ARM/Windows/wineh-basic.ll
691   // passes without the check.
692   if (Asm->MAI->usesWindowsCFI() &&
693       FuncInfo.UnwindHelpFrameIdx != std::numeric_limits<int>::max())
694     UnwindHelpOffset =
695         getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx, FuncInfo);
696 
697   MCSymbol *UnwindMapXData = nullptr;
698   MCSymbol *TryBlockMapXData = nullptr;
699   MCSymbol *IPToStateXData = nullptr;
700   if (!FuncInfo.CxxUnwindMap.empty())
701     UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
702         Twine("$stateUnwindMap$", FuncLinkageName));
703   if (!FuncInfo.TryBlockMap.empty())
704     TryBlockMapXData =
705         Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
706   if (!IPToStateTable.empty())
707     IPToStateXData =
708         Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
709 
710   bool VerboseAsm = OS.isVerboseAsm();
711   auto AddComment = [&](const Twine &Comment) {
712     if (VerboseAsm)
713       OS.AddComment(Comment);
714   };
715 
716   // FuncInfo {
717   //   uint32_t           MagicNumber
718   //   int32_t            MaxState;
719   //   UnwindMapEntry    *UnwindMap;
720   //   uint32_t           NumTryBlocks;
721   //   TryBlockMapEntry  *TryBlockMap;
722   //   uint32_t           IPMapEntries; // always 0 for x86
723   //   IPToStateMapEntry *IPToStateMap; // always 0 for x86
724   //   uint32_t           UnwindHelp;   // non-x86 only
725   //   ESTypeList        *ESTypeList;
726   //   int32_t            EHFlags;
727   // }
728   // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
729   // EHFlags & 2 -> ???
730   // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
731   OS.emitValueToAlignment(Align(4));
732   OS.emitLabel(FuncInfoXData);
733 
734   AddComment("MagicNumber");
735   OS.emitInt32(0x19930522);
736 
737   AddComment("MaxState");
738   OS.emitInt32(FuncInfo.CxxUnwindMap.size());
739 
740   AddComment("UnwindMap");
741   OS.emitValue(create32bitRef(UnwindMapXData), 4);
742 
743   AddComment("NumTryBlocks");
744   OS.emitInt32(FuncInfo.TryBlockMap.size());
745 
746   AddComment("TryBlockMap");
747   OS.emitValue(create32bitRef(TryBlockMapXData), 4);
748 
749   AddComment("IPMapEntries");
750   OS.emitInt32(IPToStateTable.size());
751 
752   AddComment("IPToStateXData");
753   OS.emitValue(create32bitRef(IPToStateXData), 4);
754 
755   if (Asm->MAI->usesWindowsCFI() &&
756       FuncInfo.UnwindHelpFrameIdx != std::numeric_limits<int>::max()) {
757     AddComment("UnwindHelp");
758     OS.emitInt32(UnwindHelpOffset);
759   }
760 
761   AddComment("ESTypeList");
762   OS.emitInt32(0);
763 
764   AddComment("EHFlags");
765   OS.emitInt32(1);
766 
767   // UnwindMapEntry {
768   //   int32_t ToState;
769   //   void  (*Action)();
770   // };
771   if (UnwindMapXData) {
772     OS.emitLabel(UnwindMapXData);
773     for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
774       MCSymbol *CleanupSym =
775           getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
776       AddComment("ToState");
777       OS.emitInt32(UME.ToState);
778 
779       AddComment("Action");
780       OS.emitValue(create32bitRef(CleanupSym), 4);
781     }
782   }
783 
784   // TryBlockMap {
785   //   int32_t      TryLow;
786   //   int32_t      TryHigh;
787   //   int32_t      CatchHigh;
788   //   int32_t      NumCatches;
789   //   HandlerType *HandlerArray;
790   // };
791   if (TryBlockMapXData) {
792     OS.emitLabel(TryBlockMapXData);
793     SmallVector<MCSymbol *, 1> HandlerMaps;
794     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
795       const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
796 
797       MCSymbol *HandlerMapXData = nullptr;
798       if (!TBME.HandlerArray.empty())
799         HandlerMapXData =
800             Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
801                                                   .concat(Twine(I))
802                                                   .concat("$")
803                                                   .concat(FuncLinkageName));
804       HandlerMaps.push_back(HandlerMapXData);
805 
806       // TBMEs should form intervals.
807       assert(0 <= TBME.TryLow && "bad trymap interval");
808       assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
809       assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
810       assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
811              "bad trymap interval");
812 
813       AddComment("TryLow");
814       OS.emitInt32(TBME.TryLow);
815 
816       AddComment("TryHigh");
817       OS.emitInt32(TBME.TryHigh);
818 
819       AddComment("CatchHigh");
820       OS.emitInt32(TBME.CatchHigh);
821 
822       AddComment("NumCatches");
823       OS.emitInt32(TBME.HandlerArray.size());
824 
825       AddComment("HandlerArray");
826       OS.emitValue(create32bitRef(HandlerMapXData), 4);
827     }
828 
829     // All funclets use the same parent frame offset currently.
830     unsigned ParentFrameOffset = 0;
831     if (shouldEmitPersonality) {
832       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
833       ParentFrameOffset = TFI->getWinEHParentFrameOffset(*MF);
834     }
835 
836     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
837       const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
838       MCSymbol *HandlerMapXData = HandlerMaps[I];
839       if (!HandlerMapXData)
840         continue;
841       // HandlerType {
842       //   int32_t         Adjectives;
843       //   TypeDescriptor *Type;
844       //   int32_t         CatchObjOffset;
845       //   void          (*Handler)();
846       //   int32_t         ParentFrameOffset; // x64 and AArch64 only
847       // };
848       OS.emitLabel(HandlerMapXData);
849       for (const WinEHHandlerType &HT : TBME.HandlerArray) {
850         // Get the frame escape label with the offset of the catch object. If
851         // the index is INT_MAX, then there is no catch object, and we should
852         // emit an offset of zero, indicating that no copy will occur.
853         const MCExpr *FrameAllocOffsetRef = nullptr;
854         if (HT.CatchObj.FrameIndex != INT_MAX) {
855           int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex, FuncInfo);
856           assert(Offset != 0 && "Illegal offset for catch object!");
857           FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
858         } else {
859           FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
860         }
861 
862         MCSymbol *HandlerSym =
863             getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
864 
865         AddComment("Adjectives");
866         OS.emitInt32(HT.Adjectives);
867 
868         AddComment("Type");
869         OS.emitValue(create32bitRef(HT.TypeDescriptor), 4);
870 
871         AddComment("CatchObjOffset");
872         OS.emitValue(FrameAllocOffsetRef, 4);
873 
874         AddComment("Handler");
875         OS.emitValue(create32bitRef(HandlerSym), 4);
876 
877         if (shouldEmitPersonality) {
878           AddComment("ParentFrameOffset");
879           OS.emitInt32(ParentFrameOffset);
880         }
881       }
882     }
883   }
884 
885   // IPToStateMapEntry {
886   //   void   *IP;
887   //   int32_t State;
888   // };
889   if (IPToStateXData) {
890     OS.emitLabel(IPToStateXData);
891     for (auto &IPStatePair : IPToStateTable) {
892       AddComment("IP");
893       OS.emitValue(IPStatePair.first, 4);
894       AddComment("ToState");
895       OS.emitInt32(IPStatePair.second);
896     }
897   }
898 }
899 
900 void WinException::computeIP2StateTable(
901     const MachineFunction *MF, const WinEHFuncInfo &FuncInfo,
902     SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
903 
904   for (MachineFunction::const_iterator FuncletStart = MF->begin(),
905                                        FuncletEnd = MF->begin(),
906                                        End = MF->end();
907        FuncletStart != End; FuncletStart = FuncletEnd) {
908     // Find the end of the funclet
909     while (++FuncletEnd != End) {
910       if (FuncletEnd->isEHFuncletEntry()) {
911         break;
912       }
913     }
914 
915     // Don't emit ip2state entries for cleanup funclets. Any interesting
916     // exceptional actions in cleanups must be handled in a separate IR
917     // function.
918     if (FuncletStart->isCleanupFuncletEntry())
919       continue;
920 
921     MCSymbol *StartLabel;
922     int BaseState;
923     if (FuncletStart == MF->begin()) {
924       BaseState = NullState;
925       StartLabel = Asm->getFunctionBegin();
926     } else {
927       auto *FuncletPad =
928           cast<FuncletPadInst>(FuncletStart->getBasicBlock()->getFirstNonPHI());
929       assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
930       BaseState = FuncInfo.FuncletBaseStateMap.find(FuncletPad)->second;
931       StartLabel = getMCSymbolForMBB(Asm, &*FuncletStart);
932     }
933     assert(StartLabel && "need local function start label");
934     IPToStateTable.push_back(
935         std::make_pair(create32bitRef(StartLabel), BaseState));
936 
937     for (const auto &StateChange : InvokeStateChangeIterator::range(
938              FuncInfo, FuncletStart, FuncletEnd, BaseState)) {
939       // Compute the label to report as the start of this entry; use the EH
940       // start label for the invoke if we have one, otherwise (this is a call
941       // which may unwind to our caller and does not have an EH start label, so)
942       // use the previous end label.
943       const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
944       if (!ChangeLabel)
945         ChangeLabel = StateChange.PreviousEndLabel;
946       // Emit an entry indicating that PCs after 'Label' have this EH state.
947       // NOTE: On ARM architectures, the StateFromIp automatically takes into
948       // account that the return address is after the call instruction (whose EH
949       // state we should be using), but on other platforms we need to +1 to the
950       // label so that we are using the correct EH state.
951       const MCExpr *LabelExpression = (isAArch64 || isThumb)
952                                           ? getLabel(ChangeLabel)
953                                           : getLabelPlusOne(ChangeLabel);
954       IPToStateTable.push_back(
955           std::make_pair(LabelExpression, StateChange.NewState));
956       // FIXME: assert that NewState is between CatchLow and CatchHigh.
957     }
958   }
959 }
960 
961 void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
962                                                  StringRef FLinkageName) {
963   // Outlined helpers called by the EH runtime need to know the offset of the EH
964   // registration in order to recover the parent frame pointer. Now that we know
965   // we've code generated the parent, we can emit the label assignment that
966   // those helpers use to get the offset of the registration node.
967 
968   // Compute the parent frame offset. The EHRegNodeFrameIndex will be invalid if
969   // after optimization all the invokes were eliminated. We still need to emit
970   // the parent frame offset label, but it should be garbage and should never be
971   // used.
972   int64_t Offset = 0;
973   int FI = FuncInfo.EHRegNodeFrameIndex;
974   if (FI != INT_MAX) {
975     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
976     Offset = TFI->getNonLocalFrameIndexReference(*Asm->MF, FI).getFixed();
977   }
978 
979   MCContext &Ctx = Asm->OutContext;
980   MCSymbol *ParentFrameOffset =
981       Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
982   Asm->OutStreamer->emitAssignment(ParentFrameOffset,
983                                    MCConstantExpr::create(Offset, Ctx));
984 }
985 
986 /// Emit the language-specific data that _except_handler3 and 4 expect. This is
987 /// functionally equivalent to the __C_specific_handler table, except it is
988 /// indexed by state number instead of IP.
989 void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
990   MCStreamer &OS = *Asm->OutStreamer;
991   const Function &F = MF->getFunction();
992   StringRef FLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
993 
994   bool VerboseAsm = OS.isVerboseAsm();
995   auto AddComment = [&](const Twine &Comment) {
996     if (VerboseAsm)
997       OS.AddComment(Comment);
998   };
999 
1000   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
1001   emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
1002 
1003   // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
1004   MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
1005   OS.emitValueToAlignment(Align(4));
1006   OS.emitLabel(LSDALabel);
1007 
1008   const auto *Per = cast<Function>(F.getPersonalityFn()->stripPointerCasts());
1009   StringRef PerName = Per->getName();
1010   int BaseState = -1;
1011   if (PerName == "_except_handler4") {
1012     // The LSDA for _except_handler4 starts with this struct, followed by the
1013     // scope table:
1014     //
1015     // struct EH4ScopeTable {
1016     //   int32_t GSCookieOffset;
1017     //   int32_t GSCookieXOROffset;
1018     //   int32_t EHCookieOffset;
1019     //   int32_t EHCookieXOROffset;
1020     //   ScopeTableEntry ScopeRecord[];
1021     // };
1022     //
1023     // Offsets are %ebp relative.
1024     //
1025     // The GS cookie is present only if the function needs stack protection.
1026     // GSCookieOffset = -2 means that GS cookie is not used.
1027     //
1028     // The EH cookie is always present.
1029     //
1030     // Check is done the following way:
1031     //    (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie
1032 
1033     // Retrieve the Guard Stack slot.
1034     int GSCookieOffset = -2;
1035     const MachineFrameInfo &MFI = MF->getFrameInfo();
1036     if (MFI.hasStackProtectorIndex()) {
1037       Register UnusedReg;
1038       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
1039       int SSPIdx = MFI.getStackProtectorIndex();
1040       GSCookieOffset =
1041           TFI->getFrameIndexReference(*MF, SSPIdx, UnusedReg).getFixed();
1042     }
1043 
1044     // Retrieve the EH Guard slot.
1045     // TODO(etienneb): Get rid of this value and change it for and assertion.
1046     int EHCookieOffset = 9999;
1047     if (FuncInfo.EHGuardFrameIndex != INT_MAX) {
1048       Register UnusedReg;
1049       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
1050       int EHGuardIdx = FuncInfo.EHGuardFrameIndex;
1051       EHCookieOffset =
1052           TFI->getFrameIndexReference(*MF, EHGuardIdx, UnusedReg).getFixed();
1053     }
1054 
1055     AddComment("GSCookieOffset");
1056     OS.emitInt32(GSCookieOffset);
1057     AddComment("GSCookieXOROffset");
1058     OS.emitInt32(0);
1059     AddComment("EHCookieOffset");
1060     OS.emitInt32(EHCookieOffset);
1061     AddComment("EHCookieXOROffset");
1062     OS.emitInt32(0);
1063     BaseState = -2;
1064   }
1065 
1066   assert(!FuncInfo.SEHUnwindMap.empty());
1067   for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
1068     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
1069     const MCSymbol *ExceptOrFinally =
1070         UME.IsFinally ? getMCSymbolForMBB(Asm, Handler) : Handler->getSymbol();
1071     // -1 is usually the base state for "unwind to caller", but for
1072     // _except_handler4 it's -2. Do that replacement here if necessary.
1073     int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
1074     AddComment("ToState");
1075     OS.emitInt32(ToState);
1076     AddComment(UME.IsFinally ? "Null" : "FilterFunction");
1077     OS.emitValue(create32bitRef(UME.Filter), 4);
1078     AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
1079     OS.emitValue(create32bitRef(ExceptOrFinally), 4);
1080   }
1081 }
1082 
1083 static int getTryRank(const WinEHFuncInfo &FuncInfo, int State) {
1084   int Rank = 0;
1085   while (State != -1) {
1086     ++Rank;
1087     State = FuncInfo.ClrEHUnwindMap[State].TryParentState;
1088   }
1089   return Rank;
1090 }
1091 
1092 static int getTryAncestor(const WinEHFuncInfo &FuncInfo, int Left, int Right) {
1093   int LeftRank = getTryRank(FuncInfo, Left);
1094   int RightRank = getTryRank(FuncInfo, Right);
1095 
1096   while (LeftRank < RightRank) {
1097     Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
1098     --RightRank;
1099   }
1100 
1101   while (RightRank < LeftRank) {
1102     Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
1103     --LeftRank;
1104   }
1105 
1106   while (Left != Right) {
1107     Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
1108     Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
1109   }
1110 
1111   return Left;
1112 }
1113 
1114 void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
1115   // CLR EH "states" are really just IDs that identify handlers/funclets;
1116   // states, handlers, and funclets all have 1:1 mappings between them, and a
1117   // handler/funclet's "state" is its index in the ClrEHUnwindMap.
1118   MCStreamer &OS = *Asm->OutStreamer;
1119   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
1120   MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
1121   MCSymbol *FuncEndSym = Asm->getFunctionEnd();
1122 
1123   // A ClrClause describes a protected region.
1124   struct ClrClause {
1125     const MCSymbol *StartLabel; // Start of protected region
1126     const MCSymbol *EndLabel;   // End of protected region
1127     int State;          // Index of handler protecting the protected region
1128     int EnclosingState; // Index of funclet enclosing the protected region
1129   };
1130   SmallVector<ClrClause, 8> Clauses;
1131 
1132   // Build a map from handler MBBs to their corresponding states (i.e. their
1133   // indices in the ClrEHUnwindMap).
1134   int NumStates = FuncInfo.ClrEHUnwindMap.size();
1135   assert(NumStates > 0 && "Don't need exception table!");
1136   DenseMap<const MachineBasicBlock *, int> HandlerStates;
1137   for (int State = 0; State < NumStates; ++State) {
1138     MachineBasicBlock *HandlerBlock =
1139         FuncInfo.ClrEHUnwindMap[State].Handler.get<MachineBasicBlock *>();
1140     HandlerStates[HandlerBlock] = State;
1141     // Use this loop through all handlers to verify our assumption (used in
1142     // the MinEnclosingState computation) that enclosing funclets have lower
1143     // state numbers than their enclosed funclets.
1144     assert(FuncInfo.ClrEHUnwindMap[State].HandlerParentState < State &&
1145            "ill-formed state numbering");
1146   }
1147   // Map the main function to the NullState.
1148   HandlerStates[&MF->front()] = NullState;
1149 
1150   // Write out a sentinel indicating the end of the standard (Windows) xdata
1151   // and the start of the additional (CLR) info.
1152   OS.emitInt32(0xffffffff);
1153   // Write out the number of funclets
1154   OS.emitInt32(NumStates);
1155 
1156   // Walk the machine blocks/instrs, computing and emitting a few things:
1157   // 1. Emit a list of the offsets to each handler entry, in lexical order.
1158   // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
1159   // 3. Compute the list of ClrClauses, in the required order (inner before
1160   //    outer, earlier before later; the order by which a forward scan with
1161   //    early termination will find the innermost enclosing clause covering
1162   //    a given address).
1163   // 4. A map (MinClauseMap) from each handler index to the index of the
1164   //    outermost funclet/function which contains a try clause targeting the
1165   //    key handler.  This will be used to determine IsDuplicate-ness when
1166   //    emitting ClrClauses.  The NullState value is used to indicate that the
1167   //    top-level function contains a try clause targeting the key handler.
1168   // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
1169   // try regions we entered before entering the PendingState try but which
1170   // we haven't yet exited.
1171   SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
1172   // EndSymbolMap and MinClauseMap are maps described above.
1173   std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
1174   SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
1175 
1176   // Visit the root function and each funclet.
1177   for (MachineFunction::const_iterator FuncletStart = MF->begin(),
1178                                        FuncletEnd = MF->begin(),
1179                                        End = MF->end();
1180        FuncletStart != End; FuncletStart = FuncletEnd) {
1181     int FuncletState = HandlerStates[&*FuncletStart];
1182     // Find the end of the funclet
1183     MCSymbol *EndSymbol = FuncEndSym;
1184     while (++FuncletEnd != End) {
1185       if (FuncletEnd->isEHFuncletEntry()) {
1186         EndSymbol = getMCSymbolForMBB(Asm, &*FuncletEnd);
1187         break;
1188       }
1189     }
1190     // Emit the function/funclet end and, if this is a funclet (and not the
1191     // root function), record it in the EndSymbolMap.
1192     OS.emitValue(getOffset(EndSymbol, FuncBeginSym), 4);
1193     if (FuncletState != NullState) {
1194       // Record the end of the handler.
1195       EndSymbolMap[FuncletState] = EndSymbol;
1196     }
1197 
1198     // Walk the state changes in this function/funclet and compute its clauses.
1199     // Funclets always start in the null state.
1200     const MCSymbol *CurrentStartLabel = nullptr;
1201     int CurrentState = NullState;
1202     assert(HandlerStack.empty());
1203     for (const auto &StateChange :
1204          InvokeStateChangeIterator::range(FuncInfo, FuncletStart, FuncletEnd)) {
1205       // Close any try regions we're not still under
1206       int StillPendingState =
1207           getTryAncestor(FuncInfo, CurrentState, StateChange.NewState);
1208       while (CurrentState != StillPendingState) {
1209         assert(CurrentState != NullState &&
1210                "Failed to find still-pending state!");
1211         // Close the pending clause
1212         Clauses.push_back({CurrentStartLabel, StateChange.PreviousEndLabel,
1213                            CurrentState, FuncletState});
1214         // Now the next-outer try region is current
1215         CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].TryParentState;
1216         // Pop the new start label from the handler stack if we've exited all
1217         // inner try regions of the corresponding try region.
1218         if (HandlerStack.back().second == CurrentState)
1219           CurrentStartLabel = HandlerStack.pop_back_val().first;
1220       }
1221 
1222       if (StateChange.NewState != CurrentState) {
1223         // For each clause we're starting, update the MinClauseMap so we can
1224         // know which is the topmost funclet containing a clause targeting
1225         // it.
1226         for (int EnteredState = StateChange.NewState;
1227              EnteredState != CurrentState;
1228              EnteredState =
1229                  FuncInfo.ClrEHUnwindMap[EnteredState].TryParentState) {
1230           int &MinEnclosingState = MinClauseMap[EnteredState];
1231           if (FuncletState < MinEnclosingState)
1232             MinEnclosingState = FuncletState;
1233         }
1234         // Save the previous current start/label on the stack and update to
1235         // the newly-current start/state.
1236         HandlerStack.emplace_back(CurrentStartLabel, CurrentState);
1237         CurrentStartLabel = StateChange.NewStartLabel;
1238         CurrentState = StateChange.NewState;
1239       }
1240     }
1241     assert(HandlerStack.empty());
1242   }
1243 
1244   // Now emit the clause info, starting with the number of clauses.
1245   OS.emitInt32(Clauses.size());
1246   for (ClrClause &Clause : Clauses) {
1247     // Emit a CORINFO_EH_CLAUSE :
1248     /*
1249       struct CORINFO_EH_CLAUSE
1250       {
1251           CORINFO_EH_CLAUSE_FLAGS Flags;         // actually a CorExceptionFlag
1252           DWORD                   TryOffset;
1253           DWORD                   TryLength;     // actually TryEndOffset
1254           DWORD                   HandlerOffset;
1255           DWORD                   HandlerLength; // actually HandlerEndOffset
1256           union
1257           {
1258               DWORD               ClassToken;   // use for catch clauses
1259               DWORD               FilterOffset; // use for filter clauses
1260           };
1261       };
1262 
1263       enum CORINFO_EH_CLAUSE_FLAGS
1264       {
1265           CORINFO_EH_CLAUSE_NONE    = 0,
1266           CORINFO_EH_CLAUSE_FILTER  = 0x0001, // This clause is for a filter
1267           CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
1268           CORINFO_EH_CLAUSE_FAULT   = 0x0004, // This clause is a fault clause
1269       };
1270       typedef enum CorExceptionFlag
1271       {
1272           COR_ILEXCEPTION_CLAUSE_NONE,
1273           COR_ILEXCEPTION_CLAUSE_FILTER  = 0x0001, // This is a filter clause
1274           COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
1275           COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004,   // This is a fault clause
1276           COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
1277                                                       // clause was duplicated
1278                                                       // to a funclet which was
1279                                                       // pulled out of line
1280       } CorExceptionFlag;
1281     */
1282     // Add 1 to the start/end of the EH clause; the IP associated with a
1283     // call when the runtime does its scan is the IP of the next instruction
1284     // (the one to which control will return after the call), so we need
1285     // to add 1 to the end of the clause to cover that offset.  We also add
1286     // 1 to the start of the clause to make sure that the ranges reported
1287     // for all clauses are disjoint.  Note that we'll need some additional
1288     // logic when machine traps are supported, since in that case the IP
1289     // that the runtime uses is the offset of the faulting instruction
1290     // itself; if such an instruction immediately follows a call but the
1291     // two belong to different clauses, we'll need to insert a nop between
1292     // them so the runtime can distinguish the point to which the call will
1293     // return from the point at which the fault occurs.
1294 
1295     const MCExpr *ClauseBegin =
1296         getOffsetPlusOne(Clause.StartLabel, FuncBeginSym);
1297     const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
1298 
1299     const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
1300     MachineBasicBlock *HandlerBlock = Entry.Handler.get<MachineBasicBlock *>();
1301     MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
1302     const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
1303     MCSymbol *EndSym = EndSymbolMap[Clause.State];
1304     const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
1305 
1306     uint32_t Flags = 0;
1307     switch (Entry.HandlerType) {
1308     case ClrHandlerType::Catch:
1309       // Leaving bits 0-2 clear indicates catch.
1310       break;
1311     case ClrHandlerType::Filter:
1312       Flags |= 1;
1313       break;
1314     case ClrHandlerType::Finally:
1315       Flags |= 2;
1316       break;
1317     case ClrHandlerType::Fault:
1318       Flags |= 4;
1319       break;
1320     }
1321     if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
1322       // This is a "duplicate" clause; the handler needs to be entered from a
1323       // frame above the one holding the invoke.
1324       assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
1325       Flags |= 8;
1326     }
1327     OS.emitInt32(Flags);
1328 
1329     // Write the clause start/end
1330     OS.emitValue(ClauseBegin, 4);
1331     OS.emitValue(ClauseEnd, 4);
1332 
1333     // Write out the handler start/end
1334     OS.emitValue(HandlerBegin, 4);
1335     OS.emitValue(HandlerEnd, 4);
1336 
1337     // Write out the type token or filter offset
1338     assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
1339     OS.emitInt32(Entry.TypeToken);
1340   }
1341 }
1342