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