[WinEH] Remove CatchObjRecoverIdx
[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 #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
143       emitExceptionTable();
144
145     Asm->OutStreamer->PopSection();
146   }
147 }
148
149 /// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock.
150 static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
151                                    const MachineBasicBlock *MBB) {
152   if (!MBB)
153     return nullptr;
154
155   assert(MBB->isEHFuncletEntry());
156
157   // Give catches and cleanups a name based off of their parent function and
158   // their funclet entry block's number.
159   const MachineFunction *MF = MBB->getParent();
160   const Function *F = MF->getFunction();
161   StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
162   MCContext &Ctx = MF->getContext();
163   StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
164   return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
165                                Twine(MBB->getNumber()) + "@?0?" +
166                                FuncLinkageName + "@4HA");
167 }
168
169 void WinException::beginFunclet(const MachineBasicBlock &MBB,
170                                 MCSymbol *Sym) {
171   CurrentFuncletEntry = &MBB;
172
173   const Function *F = Asm->MF->getFunction();
174   // If a symbol was not provided for the funclet, invent one.
175   if (!Sym) {
176     Sym = getMCSymbolForMBB(Asm, &MBB);
177
178     // Describe our funclet symbol as a function with internal linkage.
179     Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
180     Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
181     Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
182                                          << COFF::SCT_COMPLEX_TYPE_SHIFT);
183     Asm->OutStreamer->EndCOFFSymbolDef();
184
185     // We want our funclet's entry point to be aligned such that no nops will be
186     // present after the label.
187     Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
188                        F);
189
190     // Now that we've emitted the alignment directive, point at our funclet.
191     Asm->OutStreamer->EmitLabel(Sym);
192   }
193
194   // Mark 'Sym' as starting our funclet.
195   if (shouldEmitMoves || shouldEmitPersonality)
196     Asm->OutStreamer->EmitWinCFIStartProc(Sym);
197
198   if (shouldEmitPersonality) {
199     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
200     const Function *PerFn = nullptr;
201
202     // Determine which personality routine we are using for this funclet.
203     if (F->hasPersonalityFn())
204       PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
205     const MCSymbol *PersHandlerSym =
206         TLOF.getCFIPersonalitySymbol(PerFn, *Asm->Mang, Asm->TM, MMI);
207
208     // Classify the personality routine so that we may reason about it.
209     EHPersonality Per = EHPersonality::Unknown;
210     if (F->hasPersonalityFn())
211       Per = classifyEHPersonality(F->getPersonalityFn());
212
213     // Do not emit a .seh_handler directive if it is a C++ cleanup funclet.
214     if (Per != EHPersonality::MSVC_CXX ||
215         !CurrentFuncletEntry->isCleanupFuncletEntry())
216       Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
217   }
218 }
219
220 void WinException::endFunclet() {
221   // No funclet to process?  Great, we have nothing to do.
222   if (!CurrentFuncletEntry)
223     return;
224
225   if (shouldEmitMoves || shouldEmitPersonality) {
226     const Function *F = Asm->MF->getFunction();
227     EHPersonality Per = EHPersonality::Unknown;
228     if (F->hasPersonalityFn())
229       Per = classifyEHPersonality(F->getPersonalityFn());
230
231     // The .seh_handlerdata directive implicitly switches section, push the
232     // current section so that we may return to it.
233     Asm->OutStreamer->PushSection();
234
235     // Emit an UNWIND_INFO struct describing the prologue.
236     Asm->OutStreamer->EmitWinEHHandlerData();
237
238     if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
239         !CurrentFuncletEntry->isCleanupFuncletEntry()) {
240       // If this is a C++ catch funclet (or the parent function),
241       // emit a reference to the LSDA for the parent function.
242       StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
243       MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
244           Twine("$cppxdata$", FuncLinkageName));
245       Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
246     } else if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets() &&
247                !CurrentFuncletEntry->isEHFuncletEntry()) {
248       // If this is the parent function in Win64 SEH, emit the LSDA immediately
249       // following .seh_handlerdata.
250       emitCSpecificHandlerTable(Asm->MF);
251     }
252
253     // Switch back to the previous section now that we are done writing to
254     // .xdata.
255     Asm->OutStreamer->PopSection();
256
257     // Emit a .seh_endproc directive to mark the end of the function.
258     Asm->OutStreamer->EmitWinCFIEndProc();
259   }
260
261   // Let's make sure we don't try to end the same funclet twice.
262   CurrentFuncletEntry = nullptr;
263 }
264
265 const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
266   if (!Value)
267     return MCConstantExpr::create(0, Asm->OutContext);
268   return MCSymbolRefExpr::create(Value, useImageRel32
269                                             ? MCSymbolRefExpr::VK_COFF_IMGREL32
270                                             : MCSymbolRefExpr::VK_None,
271                                  Asm->OutContext);
272 }
273
274 const MCExpr *WinException::create32bitRef(const Value *V) {
275   if (!V)
276     return MCConstantExpr::create(0, Asm->OutContext);
277   if (const auto *GV = dyn_cast<GlobalValue>(V))
278     return create32bitRef(Asm->getSymbol(GV));
279   return create32bitRef(MMI->getAddrLabelSymbol(cast<BasicBlock>(V)));
280 }
281
282 const MCExpr *WinException::getLabelPlusOne(MCSymbol *Label) {
283   return MCBinaryExpr::createAdd(create32bitRef(Label),
284                                  MCConstantExpr::create(1, Asm->OutContext),
285                                  Asm->OutContext);
286 }
287
288 int WinException::getFrameIndexOffset(int FrameIndex) {
289   const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
290   unsigned UnusedReg;
291   if (Asm->MAI->usesWindowsCFI())
292     return TFI.getFrameIndexReferenceFromSP(*Asm->MF, FrameIndex, UnusedReg);
293   return TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
294 }
295
296 namespace {
297 /// Information describing an invoke range.
298 struct InvokeRange {
299   MCSymbol *BeginLabel = nullptr;
300   MCSymbol *EndLabel = nullptr;
301   int State = -1;
302
303   /// If we saw a potentially throwing call between this range and the last
304   /// range.
305   bool SawPotentiallyThrowing = false;
306 };
307
308 /// Iterator over the begin/end label pairs of invokes within a basic block.
309 class InvokeLabelIterator {
310 public:
311   InvokeLabelIterator(WinEHFuncInfo &EHInfo,
312                       MachineBasicBlock::const_iterator MBBI,
313                       MachineBasicBlock::const_iterator MBBIEnd)
314       : EHInfo(EHInfo), MBBI(MBBI), MBBIEnd(MBBIEnd) {
315     scan();
316   }
317
318   // Iterator methods.
319   bool operator==(const InvokeLabelIterator &o) const { return MBBI == o.MBBI; }
320   bool operator!=(const InvokeLabelIterator &o) const { return MBBI != o.MBBI; }
321   InvokeRange &operator*() { return CurRange; }
322   InvokeRange *operator->() { return &CurRange; }
323   InvokeLabelIterator &operator++() { return scan(); }
324
325 private:
326   // Scan forward to find the next invoke range, or hit the end iterator.
327   InvokeLabelIterator &scan();
328
329   WinEHFuncInfo &EHInfo;
330   MachineBasicBlock::const_iterator MBBI;
331   MachineBasicBlock::const_iterator MBBIEnd;
332   InvokeRange CurRange;
333 };
334 } // end anonymous namespace
335
336 /// Invoke label range iteration logic. Increment MBBI until we find the next
337 /// EH_LABEL pair, and then update MBBI to point after the end label.
338 InvokeLabelIterator &InvokeLabelIterator::scan() {
339   // Reset our state.
340   CurRange = InvokeRange{};
341
342   for (const MachineInstr &MI : make_range(MBBI, MBBIEnd)) {
343     // Remember if we had to cross a potentially throwing call instruction that
344     // must unwind to caller.
345     if (MI.isCall()) {
346       CurRange.SawPotentiallyThrowing |=
347           !EHStreamer::callToNoUnwindFunction(&MI);
348       continue;
349     }
350     // Find the next EH_LABEL instruction.
351     if (!MI.isEHLabel())
352       continue;
353
354     // If this is a begin label, break out with the state and end label.
355     // Otherwise this is probably a CFI EH_LABEL that we should continue past.
356     MCSymbol *Label = MI.getOperand(0).getMCSymbol();
357     auto StateAndEnd = EHInfo.InvokeToStateMap.find(Label);
358     if (StateAndEnd == EHInfo.InvokeToStateMap.end())
359       continue;
360     MBBI = MachineBasicBlock::const_iterator(&MI);
361     CurRange.BeginLabel = Label;
362     CurRange.EndLabel = StateAndEnd->second.second;
363     CurRange.State = StateAndEnd->second.first;
364     break;
365   }
366
367   // If we didn't find a begin label, we are done, return the end iterator.
368   if (!CurRange.BeginLabel) {
369     MBBI = MBBIEnd;
370     return *this;
371   }
372
373   // If this is a begin label, update MBBI to point past the end label.
374   for (; MBBI != MBBIEnd; ++MBBI)
375     if (MBBI->isEHLabel() &&
376         MBBI->getOperand(0).getMCSymbol() == CurRange.EndLabel)
377       break;
378   return *this;
379 }
380
381 /// Utility for making a range for all the invoke ranges.
382 static iterator_range<InvokeLabelIterator>
383 invoke_ranges(WinEHFuncInfo &EHInfo, const MachineBasicBlock &MBB) {
384   return make_range(InvokeLabelIterator(EHInfo, MBB.begin(), MBB.end()),
385                     InvokeLabelIterator(EHInfo, MBB.end(), MBB.end()));
386 }
387
388 /// Emit the language-specific data that __C_specific_handler expects.  This
389 /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
390 /// up after faults with __try, __except, and __finally.  The typeinfo values
391 /// are not really RTTI data, but pointers to filter functions that return an
392 /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
393 /// blocks and other cleanups, the landing pad label is zero, and the filter
394 /// function is actually a cleanup handler with the same prototype.  A catch-all
395 /// entry is modeled with a null filter function field and a non-zero landing
396 /// pad label.
397 ///
398 /// Possible filter function return values:
399 ///   EXCEPTION_EXECUTE_HANDLER (1):
400 ///     Jump to the landing pad label after cleanups.
401 ///   EXCEPTION_CONTINUE_SEARCH (0):
402 ///     Continue searching this table or continue unwinding.
403 ///   EXCEPTION_CONTINUE_EXECUTION (-1):
404 ///     Resume execution at the trapping PC.
405 ///
406 /// Inferred table structure:
407 ///   struct Table {
408 ///     int NumEntries;
409 ///     struct Entry {
410 ///       imagerel32 LabelStart;
411 ///       imagerel32 LabelEnd;
412 ///       imagerel32 FilterOrFinally;  // One means catch-all.
413 ///       imagerel32 LabelLPad;        // Zero means __finally.
414 ///     } Entries[NumEntries];
415 ///   };
416 void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
417   auto &OS = *Asm->OutStreamer;
418   MCContext &Ctx = Asm->OutContext;
419
420   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(MF->getFunction());
421
422   // Remember what state we were in the last time we found a begin try label.
423   // This allows us to coalesce many nearby invokes with the same state into
424   // one entry.
425   int LastEHState = -1;
426   MCSymbol *LastBeginLabel = nullptr;
427   MCSymbol *LastEndLabel = nullptr;
428
429   // Use the assembler to compute the number of table entries through label
430   // difference and division.
431   MCSymbol *TableBegin =
432       Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
433   MCSymbol *TableEnd =
434       Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
435   const MCExpr *LabelDiff =
436       MCBinaryExpr::createSub(MCSymbolRefExpr::create(TableEnd, Ctx),
437                               MCSymbolRefExpr::create(TableBegin, Ctx), Ctx);
438   const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
439   const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
440   OS.EmitValue(EntryCount, 4);
441
442   OS.EmitLabel(TableBegin);
443
444   // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
445   // models exceptions from invokes. LLVM also allows arbitrary reordering of
446   // the code, so our tables end up looking a bit different. Rather than
447   // trying to match MSVC's tables exactly, we emit a denormalized table.  For
448   // each range of invokes in the same state, we emit table entries for all
449   // the actions that would be taken in that state. This means our tables are
450   // slightly bigger, which is OK.
451   for (const auto &MBB : *MF) {
452     // Break out before we enter into a finally funclet.
453     // FIXME: We need to emit separate EH tables for cleanups.
454     if (MBB.isEHFuncletEntry() && &MBB != MF->begin())
455       break;
456
457     for (InvokeRange &I : invoke_ranges(FuncInfo, MBB)) {
458       // If this invoke is in the same state as the last invoke and there were
459       // no non-throwing calls between it, extend the range to include both
460       // and continue.
461       if (!I.SawPotentiallyThrowing && I.State == LastEHState) {
462         LastEndLabel = I.EndLabel;
463         continue;
464       }
465
466       // If this invoke ends a previous one, emit all the actions for this
467       // state.
468       if (LastEHState != -1)
469         emitSEHActionsForRange(FuncInfo, LastBeginLabel, LastEndLabel,
470                                LastEHState);
471
472       LastBeginLabel = I.BeginLabel;
473       LastEndLabel = I.EndLabel;
474       LastEHState = I.State;
475     }
476   }
477
478   // Hitting the end of the function causes us to emit the range for the
479   // previous invoke.
480   if (LastEndLabel)
481     emitSEHActionsForRange(FuncInfo, LastBeginLabel, LastEndLabel, LastEHState);
482
483   OS.EmitLabel(TableEnd);
484 }
485
486 void WinException::emitSEHActionsForRange(WinEHFuncInfo &FuncInfo,
487                                           MCSymbol *BeginLabel,
488                                           MCSymbol *EndLabel, int State) {
489   auto &OS = *Asm->OutStreamer;
490   MCContext &Ctx = Asm->OutContext;
491
492   assert(BeginLabel && EndLabel);
493   while (State != -1) {
494     SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
495     const MCExpr *FilterOrFinally;
496     const MCExpr *ExceptOrNull;
497     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
498     if (UME.IsFinally) {
499       FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
500       ExceptOrNull = MCConstantExpr::create(0, Ctx);
501     } else {
502       // For an except, the filter can be 1 (catch-all) or a function
503       // label.
504       FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
505                                    : MCConstantExpr::create(1, Ctx);
506       ExceptOrNull = create32bitRef(Handler->getSymbol());
507     }
508
509     OS.EmitValue(getLabelPlusOne(BeginLabel), 4);
510     OS.EmitValue(getLabelPlusOne(EndLabel), 4);
511     OS.EmitValue(FilterOrFinally, 4);
512     OS.EmitValue(ExceptOrNull, 4);
513
514     assert(UME.ToState < State && "states should decrease");
515     State = UME.ToState;
516   }
517 }
518
519 void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
520   const Function *F = MF->getFunction();
521   auto &OS = *Asm->OutStreamer;
522   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
523
524   StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
525
526   SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
527   MCSymbol *FuncInfoXData = nullptr;
528   if (shouldEmitPersonality) {
529     // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
530     // IPs to state numbers.
531     FuncInfoXData =
532         Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
533     computeIP2StateTable(MF, FuncInfo, IPToStateTable);
534   } else {
535     FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
536     emitEHRegistrationOffsetLabel(FuncInfo, FuncLinkageName);
537   }
538
539   int UnwindHelpOffset = 0;
540   if (Asm->MAI->usesWindowsCFI())
541     UnwindHelpOffset = getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx);
542
543   MCSymbol *UnwindMapXData = nullptr;
544   MCSymbol *TryBlockMapXData = nullptr;
545   MCSymbol *IPToStateXData = nullptr;
546   if (!FuncInfo.CxxUnwindMap.empty())
547     UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
548         Twine("$stateUnwindMap$", FuncLinkageName));
549   if (!FuncInfo.TryBlockMap.empty())
550     TryBlockMapXData =
551         Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
552   if (!IPToStateTable.empty())
553     IPToStateXData =
554         Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
555
556   // FuncInfo {
557   //   uint32_t           MagicNumber
558   //   int32_t            MaxState;
559   //   UnwindMapEntry    *UnwindMap;
560   //   uint32_t           NumTryBlocks;
561   //   TryBlockMapEntry  *TryBlockMap;
562   //   uint32_t           IPMapEntries; // always 0 for x86
563   //   IPToStateMapEntry *IPToStateMap; // always 0 for x86
564   //   uint32_t           UnwindHelp;   // non-x86 only
565   //   ESTypeList        *ESTypeList;
566   //   int32_t            EHFlags;
567   // }
568   // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
569   // EHFlags & 2 -> ???
570   // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
571   OS.EmitValueToAlignment(4);
572   OS.EmitLabel(FuncInfoXData);
573   OS.EmitIntValue(0x19930522, 4);                      // MagicNumber
574   OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4);       // MaxState
575   OS.EmitValue(create32bitRef(UnwindMapXData), 4);     // UnwindMap
576   OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);     // NumTryBlocks
577   OS.EmitValue(create32bitRef(TryBlockMapXData), 4);   // TryBlockMap
578   OS.EmitIntValue(IPToStateTable.size(), 4);           // IPMapEntries
579   OS.EmitValue(create32bitRef(IPToStateXData), 4);     // IPToStateMap
580   if (Asm->MAI->usesWindowsCFI())
581     OS.EmitIntValue(UnwindHelpOffset, 4);              // UnwindHelp
582   OS.EmitIntValue(0, 4);                               // ESTypeList
583   OS.EmitIntValue(1, 4);                               // EHFlags
584
585   // UnwindMapEntry {
586   //   int32_t ToState;
587   //   void  (*Action)();
588   // };
589   if (UnwindMapXData) {
590     OS.EmitLabel(UnwindMapXData);
591     for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
592       MCSymbol *CleanupSym =
593           getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
594       OS.EmitIntValue(UME.ToState, 4);             // ToState
595       OS.EmitValue(create32bitRef(CleanupSym), 4); // Action
596     }
597   }
598
599   // TryBlockMap {
600   //   int32_t      TryLow;
601   //   int32_t      TryHigh;
602   //   int32_t      CatchHigh;
603   //   int32_t      NumCatches;
604   //   HandlerType *HandlerArray;
605   // };
606   if (TryBlockMapXData) {
607     OS.EmitLabel(TryBlockMapXData);
608     SmallVector<MCSymbol *, 1> HandlerMaps;
609     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
610       WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
611
612       MCSymbol *HandlerMapXData = nullptr;
613       if (!TBME.HandlerArray.empty())
614         HandlerMapXData =
615             Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
616                                                   .concat(Twine(I))
617                                                   .concat("$")
618                                                   .concat(FuncLinkageName));
619       HandlerMaps.push_back(HandlerMapXData);
620
621       // TBMEs should form intervals.
622       assert(0 <= TBME.TryLow && "bad trymap interval");
623       assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
624       assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
625       assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
626              "bad trymap interval");
627
628       OS.EmitIntValue(TBME.TryLow, 4);                    // TryLow
629       OS.EmitIntValue(TBME.TryHigh, 4);                   // TryHigh
630       OS.EmitIntValue(TBME.CatchHigh, 4);                 // CatchHigh
631       OS.EmitIntValue(TBME.HandlerArray.size(), 4);       // NumCatches
632       OS.EmitValue(create32bitRef(HandlerMapXData), 4);   // HandlerArray
633     }
634
635     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
636       WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
637       MCSymbol *HandlerMapXData = HandlerMaps[I];
638       if (!HandlerMapXData)
639         continue;
640       // HandlerType {
641       //   int32_t         Adjectives;
642       //   TypeDescriptor *Type;
643       //   int32_t         CatchObjOffset;
644       //   void          (*Handler)();
645       //   int32_t         ParentFrameOffset; // x64 only
646       // };
647       OS.EmitLabel(HandlerMapXData);
648       for (const WinEHHandlerType &HT : TBME.HandlerArray) {
649         // Get the frame escape label with the offset of the catch object. If
650         // the index is INT_MAX, then there is no catch object, and we should
651         // emit an offset of zero, indicating that no copy will occur.
652         const MCExpr *FrameAllocOffsetRef = nullptr;
653         if (HT.CatchObj.FrameIndex != INT_MAX) {
654           int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex);
655           // For 32-bit, the catch object offset is relative to the end of the
656           // EH registration node. For 64-bit, it's relative to SP at the end of
657           // the prologue.
658           if (!shouldEmitPersonality) {
659             assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
660             Offset += FuncInfo.EHRegNodeEndOffset;
661           }
662           FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
663         } else {
664           FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
665         }
666
667         MCSymbol *HandlerSym =
668             getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
669
670         OS.EmitIntValue(HT.Adjectives, 4);                  // Adjectives
671         OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4); // Type
672         OS.EmitValue(FrameAllocOffsetRef, 4);               // CatchObjOffset
673         OS.EmitValue(create32bitRef(HandlerSym), 4);        // Handler
674
675         if (shouldEmitPersonality) {
676           // Keep this in sync with X86FrameLowering::emitPrologue.
677           int ParentFrameOffset =
678               16 + 8 + MF->getFrameInfo()->getMaxCallFrameSize();
679           OS.EmitIntValue(ParentFrameOffset, 4); // ParentFrameOffset
680         }
681       }
682     }
683   }
684
685   // IPToStateMapEntry {
686   //   void   *IP;
687   //   int32_t State;
688   // };
689   if (IPToStateXData) {
690     OS.EmitLabel(IPToStateXData);
691     for (auto &IPStatePair : IPToStateTable) {
692       OS.EmitValue(IPStatePair.first, 4);     // IP
693       OS.EmitIntValue(IPStatePair.second, 4); // State
694     }
695   }
696 }
697
698 void WinException::computeIP2StateTable(
699     const MachineFunction *MF, WinEHFuncInfo &FuncInfo,
700     SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
701   // Remember what state we were in the last time we found a begin try label.
702   // This allows us to coalesce many nearby invokes with the same state into one
703   // entry.
704   int LastEHState = -1;
705   MCSymbol *LastEndLabel = Asm->getFunctionBegin();
706   assert(LastEndLabel && "need local function start label");
707
708   // Indicate that all calls from the prologue to the first invoke unwind to
709   // caller. We handle this as a special case since other ranges starting at end
710   // labels need to use LtmpN+1.
711   IPToStateTable.push_back(std::make_pair(create32bitRef(LastEndLabel), -1));
712
713   for (const auto &MBB : *MF) {
714     // FIXME: Do we need to emit entries for funclet base states?
715
716     for (InvokeRange &I : invoke_ranges(FuncInfo, MBB)) {
717       assert(I.BeginLabel && I.EndLabel);
718       // If there was a potentially throwing call between this begin label and
719       // the last end label, we need an extra base state entry to indicate that
720       // those calls unwind directly to the caller.
721       if (I.SawPotentiallyThrowing && LastEHState != -1) {
722         IPToStateTable.push_back(
723             std::make_pair(getLabelPlusOne(LastEndLabel), -1));
724         LastEHState = -1;
725       }
726
727       // Emit an entry indicating that PCs after 'Label' have this EH state.
728       if (I.State != LastEHState)
729         IPToStateTable.push_back(
730             std::make_pair(getLabelPlusOne(I.BeginLabel), I.State));
731       LastEHState = I.State;
732       LastEndLabel = I.EndLabel;
733     }
734   }
735
736   if (LastEndLabel != Asm->getFunctionBegin()) {
737     // Indicate that all calls from the last invoke until the epilogue unwind to
738     // caller. This also ensures that we have at least one ip2state entry, if
739     // somehow all invokes were deleted during CodeGen.
740     IPToStateTable.push_back(std::make_pair(getLabelPlusOne(LastEndLabel), -1));
741   }
742 }
743
744 void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
745                                                  StringRef FLinkageName) {
746   // Outlined helpers called by the EH runtime need to know the offset of the EH
747   // registration in order to recover the parent frame pointer. Now that we know
748   // we've code generated the parent, we can emit the label assignment that
749   // those helpers use to get the offset of the registration node.
750   assert(FuncInfo.EHRegNodeEscapeIndex != INT_MAX &&
751          "no EH reg node localescape index");
752   MCSymbol *ParentFrameOffset =
753       Asm->OutContext.getOrCreateParentFrameOffsetSymbol(FLinkageName);
754   MCSymbol *RegistrationOffsetSym = Asm->OutContext.getOrCreateFrameAllocSymbol(
755       FLinkageName, FuncInfo.EHRegNodeEscapeIndex);
756   const MCExpr *RegistrationOffsetSymRef =
757       MCSymbolRefExpr::create(RegistrationOffsetSym, Asm->OutContext);
758   Asm->OutStreamer->EmitAssignment(ParentFrameOffset, RegistrationOffsetSymRef);
759 }
760
761 /// Emit the language-specific data that _except_handler3 and 4 expect. This is
762 /// functionally equivalent to the __C_specific_handler table, except it is
763 /// indexed by state number instead of IP.
764 void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
765   MCStreamer &OS = *Asm->OutStreamer;
766   const Function *F = MF->getFunction();
767   StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
768
769   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
770   emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
771
772   // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
773   MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
774   OS.EmitValueToAlignment(4);
775   OS.EmitLabel(LSDALabel);
776
777   const Function *Per =
778       dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
779   StringRef PerName = Per->getName();
780   int BaseState = -1;
781   if (PerName == "_except_handler4") {
782     // The LSDA for _except_handler4 starts with this struct, followed by the
783     // scope table:
784     //
785     // struct EH4ScopeTable {
786     //   int32_t GSCookieOffset;
787     //   int32_t GSCookieXOROffset;
788     //   int32_t EHCookieOffset;
789     //   int32_t EHCookieXOROffset;
790     //   ScopeTableEntry ScopeRecord[];
791     // };
792     //
793     // Only the EHCookieOffset field appears to vary, and it appears to be the
794     // offset from the final saved SP value to the retaddr.
795     OS.EmitIntValue(-2, 4);
796     OS.EmitIntValue(0, 4);
797     // FIXME: Calculate.
798     OS.EmitIntValue(9999, 4);
799     OS.EmitIntValue(0, 4);
800     BaseState = -2;
801   }
802
803   assert(!FuncInfo.SEHUnwindMap.empty());
804   for (SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
805     MCSymbol *ExceptOrFinally =
806         UME.Handler.get<MachineBasicBlock *>()->getSymbol();
807     // -1 is usually the base state for "unwind to caller", but for
808     // _except_handler4 it's -2. Do that replacement here if necessary.
809     int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
810     OS.EmitIntValue(ToState, 4);                      // ToState
811     OS.EmitValue(create32bitRef(UME.Filter), 4);      // Filter
812     OS.EmitValue(create32bitRef(ExceptOrFinally), 4); // Except/Finally
813   }
814 }