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