[WinEH] Emit __C_specific_handler tables for the new IR
[oota-llvm.git] / lib / CodeGen / AsmPrinter / WinException.cpp
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 using namespace llvm;
42
43 WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
44   // MSVC's EH tables are always composed of 32-bit words.  All known 64-bit
45   // platforms use an imagerel32 relocation to refer to symbols.
46   useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
47 }
48
49 WinException::~WinException() {}
50
51 /// endModule - Emit all exception information that should come after the
52 /// content.
53 void WinException::endModule() {
54   auto &OS = *Asm->OutStreamer;
55   const Module *M = MMI->getModule();
56   for (const Function &F : *M)
57     if (F.hasFnAttribute("safeseh"))
58       OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
59 }
60
61 void WinException::beginFunction(const MachineFunction *MF) {
62   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
63
64   // If any landing pads survive, we need an EH table.
65   bool hasLandingPads = !MMI->getLandingPads().empty();
66   bool hasEHFunclets = MMI->hasEHFunclets();
67
68   const Function *F = MF->getFunction();
69   const Function *ParentF = MMI->getWinEHParent(F);
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   // FIXME: If WinEHPrepare outlined something, we should emit the LSDA. Remove
94   // this once WinEHPrepare stops doing that.
95   if (!Asm->MAI->usesWindowsCFI()) {
96     shouldEmitLSDA =
97         hasEHFunclets || (F->hasFnAttribute("wineh-parent") && F == ParentF);
98     shouldEmitPersonality = false;
99     return;
100   }
101
102   beginFunclet(MF->front(), Asm->CurrentFnSym);
103 }
104
105 /// endFunction - Gather and emit post-function exception information.
106 ///
107 void WinException::endFunction(const MachineFunction *MF) {
108   if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
109     return;
110
111   const Function *F = MF->getFunction();
112   EHPersonality Per = EHPersonality::Unknown;
113   if (F->hasPersonalityFn())
114     Per = classifyEHPersonality(F->getPersonalityFn());
115
116   // Get rid of any dead landing pads if we're not using a Windows EH scheme. In
117   // Windows EH schemes, the landing pad is not actually reachable. It only
118   // exists so that we can emit the right table data.
119   if (!isMSVCEHPersonality(Per))
120     MMI->TidyLandingPads();
121
122   endFunclet();
123
124   // endFunclet will emit the necessary .xdata tables for x64 SEH.
125   if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets())
126     return;
127
128   if (shouldEmitPersonality || shouldEmitLSDA) {
129     Asm->OutStreamer->PushSection();
130
131     // Just switch sections to the right xdata section. This use of CurrentFnSym
132     // assumes that we only emit the LSDA when ending the parent function.
133     MCSection *XData = WinEH::UnwindEmitter::getXDataSection(Asm->CurrentFnSym,
134                                                              Asm->OutContext);
135     Asm->OutStreamer->SwitchSection(XData);
136
137     // Emit the tables appropriate to the personality function in use. If we
138     // don't recognize the personality, assume it uses an Itanium-style LSDA.
139     if (Per == EHPersonality::MSVC_Win64SEH)
140       emitCSpecificHandlerTable(MF);
141     else if (Per == EHPersonality::MSVC_X86SEH)
142       emitExceptHandlerTable(MF);
143     else if (Per == EHPersonality::MSVC_CXX)
144       emitCXXFrameHandler3Table(MF);
145     else
146       emitExceptionTable();
147
148     Asm->OutStreamer->PopSection();
149   }
150 }
151
152 /// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock. GlobalValues
153 /// are used in the old WinEH scheme, and they will be removed eventually.
154 static MCSymbol *getMCSymbolForMBBOrGV(AsmPrinter *Asm, ValueOrMBB Handler) {
155   if (!Handler)
156     return nullptr;
157   if (Handler.is<const MachineBasicBlock *>()) {
158     auto *MBB = Handler.get<const MachineBasicBlock *>();
159     assert(MBB->isEHFuncletEntry());
160
161     // Give catches and cleanups a name based off of their parent function and
162     // their funclet entry block's number.
163     const MachineFunction *MF = MBB->getParent();
164     const Function *F = MF->getFunction();
165     StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
166     MCContext &Ctx = MF->getContext();
167     StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
168     return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
169                                  Twine(MBB->getNumber()) + "@?0?" +
170                                  FuncLinkageName + "@4HA");
171   }
172   return Asm->getSymbol(cast<GlobalValue>(Handler.get<const Value *>()));
173 }
174
175 void WinException::beginFunclet(const MachineBasicBlock &MBB,
176                                 MCSymbol *Sym) {
177   CurrentFuncletEntry = &MBB;
178
179   const Function *F = Asm->MF->getFunction();
180   // If a symbol was not provided for the funclet, invent one.
181   if (!Sym) {
182     Sym = getMCSymbolForMBBOrGV(Asm, &MBB);
183
184     // Describe our funclet symbol as a function with internal linkage.
185     Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
186     Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
187     Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
188                                          << COFF::SCT_COMPLEX_TYPE_SHIFT);
189     Asm->OutStreamer->EndCOFFSymbolDef();
190
191     // We want our funclet's entry point to be aligned such that no nops will be
192     // present after the label.
193     Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
194                        F);
195
196     // Now that we've emitted the alignment directive, point at our funclet.
197     Asm->OutStreamer->EmitLabel(Sym);
198   }
199
200   // Mark 'Sym' as starting our funclet.
201   if (shouldEmitMoves || shouldEmitPersonality)
202     Asm->OutStreamer->EmitWinCFIStartProc(Sym);
203
204   if (shouldEmitPersonality) {
205     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
206     const Function *PerFn = nullptr;
207
208     // Determine which personality routine we are using for this funclet.
209     if (F->hasPersonalityFn())
210       PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
211     const MCSymbol *PersHandlerSym =
212         TLOF.getCFIPersonalitySymbol(PerFn, *Asm->Mang, Asm->TM, MMI);
213
214     // Classify the personality routine so that we may reason about it.
215     EHPersonality Per = EHPersonality::Unknown;
216     if (F->hasPersonalityFn())
217       Per = classifyEHPersonality(F->getPersonalityFn());
218
219     // Do not emit a .seh_handler directive if it is a C++ cleanup funclet.
220     if (Per != EHPersonality::MSVC_CXX ||
221         !CurrentFuncletEntry->isCleanupFuncletEntry())
222       Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
223   }
224 }
225
226 void WinException::endFunclet() {
227   // No funclet to process?  Great, we have nothing to do.
228   if (!CurrentFuncletEntry)
229     return;
230
231   if (shouldEmitMoves || shouldEmitPersonality) {
232     const Function *F = Asm->MF->getFunction();
233     EHPersonality Per = EHPersonality::Unknown;
234     if (F->hasPersonalityFn())
235       Per = classifyEHPersonality(F->getPersonalityFn());
236
237     // The .seh_handlerdata directive implicitly switches section, push the
238     // current section so that we may return to it.
239     Asm->OutStreamer->PushSection();
240
241     // Emit an UNWIND_INFO struct describing the prologue.
242     Asm->OutStreamer->EmitWinEHHandlerData();
243
244     if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
245         !CurrentFuncletEntry->isCleanupFuncletEntry()) {
246       // If this is a C++ catch funclet (or the parent function),
247       // emit a reference to the LSDA for the parent function.
248       StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
249       MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
250           Twine("$cppxdata$", FuncLinkageName));
251       Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
252     } else if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets() &&
253                !CurrentFuncletEntry->isEHFuncletEntry()) {
254       // If this is the parent function in Win64 SEH, emit the LSDA immediately
255       // following .seh_handlerdata.
256       emitCSpecificHandlerTable(Asm->MF);
257     }
258
259     // Switch back to the previous section now that we are done writing to
260     // .xdata.
261     Asm->OutStreamer->PopSection();
262
263     // Emit a .seh_endproc directive to mark the end of the function.
264     Asm->OutStreamer->EmitWinCFIEndProc();
265   }
266
267   // Let's make sure we don't try to end the same funclet twice.
268   CurrentFuncletEntry = nullptr;
269 }
270
271 const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
272   if (!Value)
273     return MCConstantExpr::create(0, Asm->OutContext);
274   return MCSymbolRefExpr::create(Value, useImageRel32
275                                             ? MCSymbolRefExpr::VK_COFF_IMGREL32
276                                             : MCSymbolRefExpr::VK_None,
277                                  Asm->OutContext);
278 }
279
280 const MCExpr *WinException::create32bitRef(const Value *V) {
281   if (!V)
282     return MCConstantExpr::create(0, Asm->OutContext);
283   // FIXME: Delete the GlobalValue case once the new IR is fully functional.
284   if (const auto *GV = dyn_cast<GlobalValue>(V))
285     return create32bitRef(Asm->getSymbol(GV));
286   return create32bitRef(MMI->getAddrLabelSymbol(cast<BasicBlock>(V)));
287 }
288
289 const MCExpr *WinException::getLabelPlusOne(MCSymbol *Label) {
290   return MCBinaryExpr::createAdd(create32bitRef(Label),
291                                  MCConstantExpr::create(1, Asm->OutContext),
292                                  Asm->OutContext);
293 }
294
295 /// Information describing an invoke range.
296 struct InvokeRange {
297   MCSymbol *BeginLabel = nullptr;
298   MCSymbol *EndLabel = nullptr;
299   int State = -1;
300
301   /// If we saw a potentially throwing call between this range and the last
302   /// range.
303   bool SawPotentiallyThrowing = false;
304 };
305
306 /// Iterator over the begin/end label pairs of invokes within a basic block.
307 class InvokeLabelIterator {
308 public:
309   InvokeLabelIterator(WinEHFuncInfo &EHInfo,
310                       MachineBasicBlock::const_iterator MBBI,
311                       MachineBasicBlock::const_iterator MBBIEnd)
312       : EHInfo(EHInfo), MBBI(MBBI), MBBIEnd(MBBIEnd) {
313     scan();
314   }
315
316   // Iterator methods.
317   bool operator==(const InvokeLabelIterator &o) const { return MBBI == o.MBBI; }
318   bool operator!=(const InvokeLabelIterator &o) const { return MBBI != o.MBBI; }
319   InvokeRange &operator*() { return CurRange; }
320   InvokeRange *operator->() { return &CurRange; }
321   InvokeLabelIterator &operator++() { return scan(); }
322
323 private:
324   // Scan forward to find the next invoke range, or hit the end iterator.
325   InvokeLabelIterator &scan();
326
327   WinEHFuncInfo &EHInfo;
328   MachineBasicBlock::const_iterator MBBI;
329   MachineBasicBlock::const_iterator MBBIEnd;
330   InvokeRange CurRange;
331 };
332
333 /// Invoke label range iteration logic. Increment MBBI until we find the next
334 /// EH_LABEL pair, and then update MBBI to point after the end label.
335 InvokeLabelIterator &InvokeLabelIterator::scan() {
336   // Reset our state.
337   CurRange = InvokeRange{};
338
339   for (const MachineInstr &MI : make_range(MBBI, MBBIEnd)) {
340     // Remember if we had to cross a potentially throwing call instruction that
341     // must unwind to caller.
342     if (MI.isCall()) {
343       CurRange.SawPotentiallyThrowing |=
344           !EHStreamer::callToNoUnwindFunction(&MI);
345       continue;
346     }
347     // Find the next EH_LABEL instruction.
348     if (!MI.isEHLabel())
349       continue;
350
351     // If this is a begin label, break out with the state and end label.
352     // Otherwise this is probably a CFI EH_LABEL that we should continue past.
353     MCSymbol *Label = MI.getOperand(0).getMCSymbol();
354     auto StateAndEnd = EHInfo.InvokeToStateMap.find(Label);
355     if (StateAndEnd == EHInfo.InvokeToStateMap.end())
356       continue;
357     MBBI = MachineBasicBlock::const_iterator(&MI);
358     CurRange.BeginLabel = Label;
359     CurRange.EndLabel = StateAndEnd->second.second;
360     CurRange.State = StateAndEnd->second.first;
361     break;
362   }
363
364   // If we didn't find a begin label, we are done, return the end iterator.
365   if (!CurRange.BeginLabel) {
366     MBBI = MBBIEnd;
367     return *this;
368   }
369
370   // If this is a begin label, update MBBI to point past the end label.
371   for (; MBBI != MBBIEnd; ++MBBI)
372     if (MBBI->isEHLabel() &&
373         MBBI->getOperand(0).getMCSymbol() == CurRange.EndLabel)
374       break;
375   return *this;
376 }
377
378 /// Utility for making a range for all the invoke ranges.
379 static iterator_range<InvokeLabelIterator>
380 invoke_ranges(WinEHFuncInfo &EHInfo, const MachineBasicBlock &MBB) {
381   return make_range(InvokeLabelIterator(EHInfo, MBB.begin(), MBB.end()),
382                     InvokeLabelIterator(EHInfo, MBB.end(), MBB.end()));
383 }
384
385 /// Emit the language-specific data that __C_specific_handler expects.  This
386 /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
387 /// up after faults with __try, __except, and __finally.  The typeinfo values
388 /// are not really RTTI data, but pointers to filter functions that return an
389 /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
390 /// blocks and other cleanups, the landing pad label is zero, and the filter
391 /// function is actually a cleanup handler with the same prototype.  A catch-all
392 /// entry is modeled with a null filter function field and a non-zero landing
393 /// pad label.
394 ///
395 /// Possible filter function return values:
396 ///   EXCEPTION_EXECUTE_HANDLER (1):
397 ///     Jump to the landing pad label after cleanups.
398 ///   EXCEPTION_CONTINUE_SEARCH (0):
399 ///     Continue searching this table or continue unwinding.
400 ///   EXCEPTION_CONTINUE_EXECUTION (-1):
401 ///     Resume execution at the trapping PC.
402 ///
403 /// Inferred table structure:
404 ///   struct Table {
405 ///     int NumEntries;
406 ///     struct Entry {
407 ///       imagerel32 LabelStart;
408 ///       imagerel32 LabelEnd;
409 ///       imagerel32 FilterOrFinally;  // One means catch-all.
410 ///       imagerel32 LabelLPad;        // Zero means __finally.
411 ///     } Entries[NumEntries];
412 ///   };
413 void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
414   auto &OS = *Asm->OutStreamer;
415   MCContext &Ctx = Asm->OutContext;
416
417   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(MF->getFunction());
418   if (!FuncInfo.SEHUnwindMap.empty()) {
419     // Remember what state we were in the last time we found a begin try label.
420     // This allows us to coalesce many nearby invokes with the same state into
421     // one entry.
422     int LastEHState = -1;
423     MCSymbol *LastBeginLabel = nullptr;
424     MCSymbol *LastEndLabel = nullptr;
425
426     // Use the assembler to compute the number of table entries through label
427     // difference and division.
428     MCSymbol *TableBegin = Ctx.createTempSymbol("lsda_begin");
429     MCSymbol *TableEnd = Ctx.createTempSymbol("lsda_end");
430     const MCExpr *LabelDiff =
431         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TableEnd, Ctx),
432                                 MCSymbolRefExpr::create(TableBegin, Ctx), Ctx);
433     const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
434     const MCExpr *EntryCount =
435         MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
436     OS.EmitValue(EntryCount, 4);
437
438     OS.EmitLabel(TableBegin);
439
440     // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
441     // models exceptions from invokes. LLVM also allows arbitrary reordering of
442     // the code, so our tables end up looking a bit different. Rather than
443     // trying to match MSVC's tables exactly, we emit a denormalized table.  For
444     // each range of invokes in the same state, we emit table entries for all
445     // the actions that would be taken in that state. This means our tables are
446     // slightly bigger, which is OK.
447     for (const auto &MBB : *MF) {
448       for (InvokeRange &I : invoke_ranges(FuncInfo, MBB)) {
449         // If this invoke is in the same state as the last invoke and there were
450         // no non-throwing calls between it, extend the range to include both
451         // and continue.
452         if (!I.SawPotentiallyThrowing && I.State == LastEHState) {
453           LastEndLabel = I.EndLabel;
454           continue;
455         }
456
457         // If this invoke ends a previous one, emit all the actions for this
458         // state.
459         if (LastEHState != -1) {
460           assert(LastBeginLabel && LastEndLabel);
461           for (int State = LastEHState; State != -1;) {
462             SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
463             const MCExpr *FilterOrFinally;
464             const MCExpr *ExceptOrNull;
465             auto *Handler = UME.Handler.get<MachineBasicBlock *>();
466             if (UME.IsFinally) {
467               FilterOrFinally = create32bitRef(Handler->getSymbol());
468               ExceptOrNull = MCConstantExpr::create(0, Ctx);
469             } else {
470               // For an except, the filter can be 1 (catch-all) or a function
471               // label.
472               FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
473                                            : MCConstantExpr::create(1, Ctx);
474               ExceptOrNull = create32bitRef(Handler->getSymbol());
475             }
476
477             OS.EmitValue(getLabelPlusOne(LastBeginLabel), 4);
478             OS.EmitValue(getLabelPlusOne(LastEndLabel), 4);
479             OS.EmitValue(FilterOrFinally, 4);
480             OS.EmitValue(ExceptOrNull, 4);
481
482             State = UME.ToState;
483           }
484         }
485
486         LastBeginLabel = I.BeginLabel;
487         LastEndLabel = I.EndLabel;
488         LastEHState = I.State;
489       }
490     }
491     OS.EmitLabel(TableEnd);
492     return;
493   }
494
495   // Simplifying assumptions for first implementation:
496   // - Cleanups are not implemented.
497   // - Filters are not implemented.
498
499   // The Itanium LSDA table sorts similar landing pads together to simplify the
500   // actions table, but we don't need that.
501   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
502   SmallVector<const LandingPadInfo *, 64> LandingPads;
503   LandingPads.reserve(PadInfos.size());
504   for (const auto &LP : PadInfos)
505     LandingPads.push_back(&LP);
506
507   // Compute label ranges for call sites as we would for the Itanium LSDA, but
508   // use an all zero action table because we aren't using these actions.
509   SmallVector<unsigned, 64> FirstActions;
510   FirstActions.resize(LandingPads.size());
511   SmallVector<CallSiteEntry, 64> CallSites;
512   computeCallSiteTable(CallSites, LandingPads, FirstActions);
513
514   MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
515   MCSymbol *EHFuncEndSym = Asm->getFunctionEnd();
516
517   // Emit the number of table entries.
518   unsigned NumEntries = 0;
519   for (const CallSiteEntry &CSE : CallSites) {
520     if (!CSE.LPad)
521       continue; // Ignore gaps.
522     NumEntries += CSE.LPad->SEHHandlers.size();
523   }
524   OS.EmitIntValue(NumEntries, 4);
525
526   // If there are no actions, we don't need to iterate again.
527   if (NumEntries == 0)
528     return;
529
530   // Emit the four-label records for each call site entry. The table has to be
531   // sorted in layout order, and the call sites should already be sorted.
532   for (const CallSiteEntry &CSE : CallSites) {
533     // Ignore gaps. Unlike the Itanium model, unwinding through a frame without
534     // an EH table entry will propagate the exception rather than terminating
535     // the program.
536     if (!CSE.LPad)
537       continue;
538     const LandingPadInfo *LPad = CSE.LPad;
539
540     // Compute the label range. We may reuse the function begin and end labels
541     // rather than forming new ones.
542     const MCExpr *Begin =
543         create32bitRef(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
544     const MCExpr *End;
545     if (CSE.EndLabel) {
546       // The interval is half-open, so we have to add one to include the return
547       // address of the last invoke in the range.
548       End = getLabelPlusOne(CSE.EndLabel);
549     } else {
550       End = create32bitRef(EHFuncEndSym);
551     }
552
553     // Emit an entry for each action.
554     for (SEHHandler Handler : LPad->SEHHandlers) {
555       OS.EmitValue(Begin, 4);
556       OS.EmitValue(End, 4);
557
558       // Emit the filter or finally function pointer, if present. Otherwise,
559       // emit '1' to indicate a catch-all.
560       const Function *F = Handler.FilterOrFinally;
561       if (F)
562         OS.EmitValue(create32bitRef(Asm->getSymbol(F)), 4);
563       else
564         OS.EmitIntValue(1, 4);
565
566       // Emit the recovery address, if present. Otherwise, this must be a
567       // finally.
568       const BlockAddress *BA = Handler.RecoverBA;
569       if (BA)
570         OS.EmitValue(
571             create32bitRef(Asm->GetBlockAddressSymbol(BA)), 4);
572       else
573         OS.EmitIntValue(0, 4);
574     }
575   }
576 }
577
578 void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
579   const Function *F = MF->getFunction();
580   auto &OS = *Asm->OutStreamer;
581   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
582
583   StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
584
585   SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
586   MCSymbol *FuncInfoXData = nullptr;
587   if (shouldEmitPersonality) {
588     // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
589     // IPs to state numbers.
590     FuncInfoXData =
591         Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
592     computeIP2StateTable(MF, FuncInfo, IPToStateTable);
593   } else {
594     FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
595     emitEHRegistrationOffsetLabel(FuncInfo, FuncLinkageName);
596   }
597
598   MCSymbol *UnwindMapXData = nullptr;
599   MCSymbol *TryBlockMapXData = nullptr;
600   MCSymbol *IPToStateXData = nullptr;
601   if (!FuncInfo.UnwindMap.empty())
602     UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
603         Twine("$stateUnwindMap$", FuncLinkageName));
604   if (!FuncInfo.TryBlockMap.empty())
605     TryBlockMapXData =
606         Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
607   if (!IPToStateTable.empty())
608     IPToStateXData =
609         Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
610
611   // FuncInfo {
612   //   uint32_t           MagicNumber
613   //   int32_t            MaxState;
614   //   UnwindMapEntry    *UnwindMap;
615   //   uint32_t           NumTryBlocks;
616   //   TryBlockMapEntry  *TryBlockMap;
617   //   uint32_t           IPMapEntries; // always 0 for x86
618   //   IPToStateMapEntry *IPToStateMap; // always 0 for x86
619   //   uint32_t           UnwindHelp;   // non-x86 only
620   //   ESTypeList        *ESTypeList;
621   //   int32_t            EHFlags;
622   // }
623   // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
624   // EHFlags & 2 -> ???
625   // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
626   OS.EmitValueToAlignment(4);
627   OS.EmitLabel(FuncInfoXData);
628   OS.EmitIntValue(0x19930522, 4);                      // MagicNumber
629   OS.EmitIntValue(FuncInfo.UnwindMap.size(), 4);       // MaxState
630   OS.EmitValue(create32bitRef(UnwindMapXData), 4);     // UnwindMap
631   OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);     // NumTryBlocks
632   OS.EmitValue(create32bitRef(TryBlockMapXData), 4);   // TryBlockMap
633   OS.EmitIntValue(IPToStateTable.size(), 4);           // IPMapEntries
634   OS.EmitValue(create32bitRef(IPToStateXData), 4);     // IPToStateMap
635   if (Asm->MAI->usesWindowsCFI())
636     OS.EmitIntValue(FuncInfo.UnwindHelpFrameOffset, 4); // UnwindHelp
637   OS.EmitIntValue(0, 4);                               // ESTypeList
638   OS.EmitIntValue(1, 4);                               // EHFlags
639
640   // UnwindMapEntry {
641   //   int32_t ToState;
642   //   void  (*Action)();
643   // };
644   if (UnwindMapXData) {
645     OS.EmitLabel(UnwindMapXData);
646     for (const WinEHUnwindMapEntry &UME : FuncInfo.UnwindMap) {
647       MCSymbol *CleanupSym = getMCSymbolForMBBOrGV(Asm, UME.Cleanup);
648       OS.EmitIntValue(UME.ToState, 4);             // ToState
649       OS.EmitValue(create32bitRef(CleanupSym), 4); // Action
650     }
651   }
652
653   // TryBlockMap {
654   //   int32_t      TryLow;
655   //   int32_t      TryHigh;
656   //   int32_t      CatchHigh;
657   //   int32_t      NumCatches;
658   //   HandlerType *HandlerArray;
659   // };
660   if (TryBlockMapXData) {
661     OS.EmitLabel(TryBlockMapXData);
662     SmallVector<MCSymbol *, 1> HandlerMaps;
663     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
664       WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
665
666       MCSymbol *HandlerMapXData = nullptr;
667       if (!TBME.HandlerArray.empty())
668         HandlerMapXData =
669             Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
670                                                   .concat(Twine(I))
671                                                   .concat("$")
672                                                   .concat(FuncLinkageName));
673       HandlerMaps.push_back(HandlerMapXData);
674
675       // TBMEs should form intervals.
676       assert(0 <= TBME.TryLow && "bad trymap interval");
677       assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
678       assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
679       assert(TBME.CatchHigh < int(FuncInfo.UnwindMap.size()) &&
680              "bad trymap interval");
681
682       OS.EmitIntValue(TBME.TryLow, 4);                    // TryLow
683       OS.EmitIntValue(TBME.TryHigh, 4);                   // TryHigh
684       OS.EmitIntValue(TBME.CatchHigh, 4);                 // CatchHigh
685       OS.EmitIntValue(TBME.HandlerArray.size(), 4);       // NumCatches
686       OS.EmitValue(create32bitRef(HandlerMapXData), 4);   // HandlerArray
687     }
688
689     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
690       WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
691       MCSymbol *HandlerMapXData = HandlerMaps[I];
692       if (!HandlerMapXData)
693         continue;
694       // HandlerType {
695       //   int32_t         Adjectives;
696       //   TypeDescriptor *Type;
697       //   int32_t         CatchObjOffset;
698       //   void          (*Handler)();
699       //   int32_t         ParentFrameOffset; // x64 only
700       // };
701       OS.EmitLabel(HandlerMapXData);
702       for (const WinEHHandlerType &HT : TBME.HandlerArray) {
703         // Get the frame escape label with the offset of the catch object. If
704         // the index is -1, then there is no catch object, and we should emit an
705         // offset of zero, indicating that no copy will occur.
706         const MCExpr *FrameAllocOffsetRef = nullptr;
707         if (HT.CatchObjRecoverIdx >= 0) {
708           MCSymbol *FrameAllocOffset =
709               Asm->OutContext.getOrCreateFrameAllocSymbol(
710                   FuncLinkageName, HT.CatchObjRecoverIdx);
711           FrameAllocOffsetRef = MCSymbolRefExpr::create(
712               FrameAllocOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
713         } else if (HT.CatchObj.FrameOffset != INT_MAX) {
714           int Offset = HT.CatchObj.FrameOffset;
715           // For 32-bit, the catch object offset is relative to the end of the
716           // EH registration node. For 64-bit, it's relative to SP at the end of
717           // the prologue.
718           if (!shouldEmitPersonality) {
719             assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
720             Offset += FuncInfo.EHRegNodeEndOffset;
721           }
722           FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
723         } else {
724           FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
725         }
726
727         MCSymbol *HandlerSym = getMCSymbolForMBBOrGV(Asm, HT.Handler);
728
729         OS.EmitIntValue(HT.Adjectives, 4);                  // Adjectives
730         OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4); // Type
731         OS.EmitValue(FrameAllocOffsetRef, 4);               // CatchObjOffset
732         OS.EmitValue(create32bitRef(HandlerSym), 4);        // Handler
733
734         if (shouldEmitPersonality) {
735           // With the new IR, this is always 16 + 8 + getMaxCallFrameSize().
736           // Keep this in sync with X86FrameLowering::emitPrologue.
737           int ParentFrameOffset =
738               16 + 8 + MF->getFrameInfo()->getMaxCallFrameSize();
739           OS.EmitIntValue(ParentFrameOffset, 4); // ParentFrameOffset
740         }
741       }
742     }
743   }
744
745   // IPToStateMapEntry {
746   //   void   *IP;
747   //   int32_t State;
748   // };
749   if (IPToStateXData) {
750     OS.EmitLabel(IPToStateXData);
751     for (auto &IPStatePair : IPToStateTable) {
752       OS.EmitValue(IPStatePair.first, 4);     // IP
753       OS.EmitIntValue(IPStatePair.second, 4); // State
754     }
755   }
756 }
757
758 void WinException::computeIP2StateTable(
759     const MachineFunction *MF, WinEHFuncInfo &FuncInfo,
760     SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
761   // Remember what state we were in the last time we found a begin try label.
762   // This allows us to coalesce many nearby invokes with the same state into one
763   // entry.
764   int LastEHState = -1;
765   MCSymbol *LastEndLabel = Asm->getFunctionBegin();
766   assert(LastEndLabel && "need local function start label");
767
768   // Indicate that all calls from the prologue to the first invoke unwind to
769   // caller. We handle this as a special case since other ranges starting at end
770   // labels need to use LtmpN+1.
771   IPToStateTable.push_back(std::make_pair(create32bitRef(LastEndLabel), -1));
772
773   for (const auto &MBB : *MF) {
774     // FIXME: Do we need to emit entries for funclet base states?
775
776     for (InvokeRange &I : invoke_ranges(FuncInfo, MBB)) {
777       assert(I.BeginLabel && I.EndLabel);
778       // If there was a potentially throwing call between this begin label and
779       // the last end label, we need an extra base state entry to indicate that
780       // those calls unwind directly to the caller.
781       if (I.SawPotentiallyThrowing && LastEHState != -1) {
782         IPToStateTable.push_back(
783             std::make_pair(getLabelPlusOne(LastEndLabel), -1));
784         LastEHState = -1;
785       }
786
787       // Emit an entry indicating that PCs after 'Label' have this EH state.
788       if (I.State != LastEHState)
789         IPToStateTable.push_back(
790             std::make_pair(create32bitRef(I.BeginLabel), I.State));
791       LastEHState = I.State;
792       LastEndLabel = I.EndLabel;
793     }
794   }
795
796   if (LastEndLabel != Asm->getFunctionBegin()) {
797     // Indicate that all calls from the last invoke until the epilogue unwind to
798     // caller. This also ensures that we have at least one ip2state entry, if
799     // somehow all invokes were deleted during CodeGen.
800     IPToStateTable.push_back(std::make_pair(getLabelPlusOne(LastEndLabel), -1));
801   }
802 }
803
804 void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
805                                                  StringRef FLinkageName) {
806   // Outlined helpers called by the EH runtime need to know the offset of the EH
807   // registration in order to recover the parent frame pointer. Now that we know
808   // we've code generated the parent, we can emit the label assignment that
809   // those helpers use to get the offset of the registration node.
810   assert(FuncInfo.EHRegNodeEscapeIndex != INT_MAX &&
811          "no EH reg node localescape index");
812   MCSymbol *ParentFrameOffset =
813       Asm->OutContext.getOrCreateParentFrameOffsetSymbol(FLinkageName);
814   MCSymbol *RegistrationOffsetSym = Asm->OutContext.getOrCreateFrameAllocSymbol(
815       FLinkageName, FuncInfo.EHRegNodeEscapeIndex);
816   const MCExpr *RegistrationOffsetSymRef =
817       MCSymbolRefExpr::create(RegistrationOffsetSym, Asm->OutContext);
818   Asm->OutStreamer->EmitAssignment(ParentFrameOffset, RegistrationOffsetSymRef);
819 }
820
821 /// Emit the language-specific data that _except_handler3 and 4 expect. This is
822 /// functionally equivalent to the __C_specific_handler table, except it is
823 /// indexed by state number instead of IP.
824 void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
825   MCStreamer &OS = *Asm->OutStreamer;
826   const Function *F = MF->getFunction();
827   StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
828
829   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
830   emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
831
832   // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
833   MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
834   OS.EmitValueToAlignment(4);
835   OS.EmitLabel(LSDALabel);
836
837   const Function *Per =
838       dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
839   StringRef PerName = Per->getName();
840   int BaseState = -1;
841   if (PerName == "_except_handler4") {
842     // The LSDA for _except_handler4 starts with this struct, followed by the
843     // scope table:
844     //
845     // struct EH4ScopeTable {
846     //   int32_t GSCookieOffset;
847     //   int32_t GSCookieXOROffset;
848     //   int32_t EHCookieOffset;
849     //   int32_t EHCookieXOROffset;
850     //   ScopeTableEntry ScopeRecord[];
851     // };
852     //
853     // Only the EHCookieOffset field appears to vary, and it appears to be the
854     // offset from the final saved SP value to the retaddr.
855     OS.EmitIntValue(-2, 4);
856     OS.EmitIntValue(0, 4);
857     // FIXME: Calculate.
858     OS.EmitIntValue(9999, 4);
859     OS.EmitIntValue(0, 4);
860     BaseState = -2;
861   }
862
863   if (!FuncInfo.SEHUnwindMap.empty()) {
864     for (SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
865       MCSymbol *ExceptOrFinally =
866           UME.Handler.get<MachineBasicBlock *>()->getSymbol();
867       OS.EmitIntValue(UME.ToState, 4);                  // ToState
868       OS.EmitValue(create32bitRef(UME.Filter), 4);      // Filter
869       OS.EmitValue(create32bitRef(ExceptOrFinally), 4); // Except/Finally
870     }
871     return;
872   }
873   // FIXME: The following code is for the old landingpad-based SEH
874   // implementation. Remove it when possible.
875
876   // Build a list of pointers to LandingPadInfos and then sort by WinEHState.
877   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
878   SmallVector<const LandingPadInfo *, 4> LPads;
879   LPads.reserve((PadInfos.size()));
880   for (const LandingPadInfo &LPInfo : PadInfos)
881     LPads.push_back(&LPInfo);
882   std::sort(LPads.begin(), LPads.end(),
883             [](const LandingPadInfo *L, const LandingPadInfo *R) {
884               return L->WinEHState < R->WinEHState;
885             });
886
887   // For each action in each lpad, emit one of these:
888   // struct ScopeTableEntry {
889   //   int32_t EnclosingLevel;
890   //   int32_t (__cdecl *Filter)();
891   //   void *HandlerOrFinally;
892   // };
893   //
894   // The "outermost" action will use BaseState as its enclosing level. Each
895   // other action will refer to the previous state as its enclosing level.
896   int CurState = 0;
897   for (const LandingPadInfo *LPInfo : LPads) {
898     int EnclosingLevel = BaseState;
899     assert(CurState + int(LPInfo->SEHHandlers.size()) - 1 ==
900                LPInfo->WinEHState &&
901            "gaps in the SEH scope table");
902     for (auto I = LPInfo->SEHHandlers.rbegin(), E = LPInfo->SEHHandlers.rend();
903          I != E; ++I) {
904       const SEHHandler &Handler = *I;
905       const BlockAddress *BA = Handler.RecoverBA;
906       const Function *F = Handler.FilterOrFinally;
907       assert(F && "cannot catch all in 32-bit SEH without filter function");
908       const MCExpr *FilterOrNull =
909           create32bitRef(BA ? Asm->getSymbol(F) : nullptr);
910       const MCExpr *ExceptOrFinally = create32bitRef(
911           BA ? Asm->GetBlockAddressSymbol(BA) : Asm->getSymbol(F));
912
913       OS.EmitIntValue(EnclosingLevel, 4);
914       OS.EmitValue(FilterOrNull, 4);
915       OS.EmitValue(ExceptOrFinally, 4);
916
917       // The next state unwinds to this state.
918       EnclosingLevel = CurState;
919       CurState++;
920     }
921   }
922 }