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