Move the EH symbol to the asm printer and use it for the SJLJ case too.
[oota-llvm.git] / lib / CodeGen / AsmPrinter / Win64Exception.cpp
1 //===-- CodeGen/AsmPrinter/Win64Exception.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 "Win64Exception.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/IR/DataLayout.h"
23 #include "llvm/IR/Mangler.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/Support/Dwarf.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Target/TargetFrameLowering.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 using namespace llvm;
39
40 Win64Exception::Win64Exception(AsmPrinter *A)
41   : EHStreamer(A), shouldEmitPersonality(false), shouldEmitLSDA(false),
42     shouldEmitMoves(false) {}
43
44 Win64Exception::~Win64Exception() {}
45
46 /// endModule - Emit all exception information that should come after the
47 /// content.
48 void Win64Exception::endModule() {
49 }
50
51 void Win64Exception::beginFunction(const MachineFunction *MF) {
52   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
53
54   // If any landing pads survive, we need an EH table.
55   bool hasLandingPads = !MMI->getLandingPads().empty();
56
57   shouldEmitMoves = Asm->needsSEHMoves();
58
59   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
60   unsigned PerEncoding = TLOF.getPersonalityEncoding();
61   const Function *Per = MF->getMMI().getPersonality();
62
63   shouldEmitPersonality = hasLandingPads &&
64     PerEncoding != dwarf::DW_EH_PE_omit && Per;
65
66   unsigned LSDAEncoding = TLOF.getLSDAEncoding();
67   shouldEmitLSDA = shouldEmitPersonality &&
68     LSDAEncoding != dwarf::DW_EH_PE_omit;
69
70   if (!shouldEmitPersonality && !shouldEmitMoves)
71     return;
72
73   Asm->OutStreamer.EmitWinCFIStartProc(Asm->CurrentFnSym);
74
75   if (!shouldEmitPersonality)
76     return;
77
78   const MCSymbol *PersHandlerSym =
79       TLOF.getCFIPersonalitySymbol(Per, *Asm->Mang, Asm->TM, MMI);
80   Asm->OutStreamer.EmitWinEHHandler(PersHandlerSym, true, true);
81 }
82
83 /// endFunction - Gather and emit post-function exception information.
84 ///
85 void Win64Exception::endFunction(const MachineFunction *) {
86   if (!shouldEmitPersonality && !shouldEmitMoves)
87     return;
88
89   // Map all labels and get rid of any dead landing pads.
90   MMI->TidyLandingPads();
91
92   if (shouldEmitPersonality) {
93     Asm->OutStreamer.PushSection();
94
95     // Emit an UNWIND_INFO struct describing the prologue.
96     Asm->OutStreamer.EmitWinEHHandlerData();
97
98     // Emit the tables appropriate to the personality function in use. If we
99     // don't recognize the personality, assume it uses an Itanium-style LSDA.
100     EHPersonality Per = MMI->getPersonalityType();
101     if (Per == EHPersonality::MSVC_Win64SEH)
102       emitCSpecificHandlerTable();
103     else
104       emitExceptionTable();
105
106     Asm->OutStreamer.PopSection();
107   }
108   Asm->OutStreamer.EmitWinCFIEndProc();
109 }
110
111 const MCSymbolRefExpr *Win64Exception::createImageRel32(const MCSymbol *Value) {
112   return MCSymbolRefExpr::Create(Value, MCSymbolRefExpr::VK_COFF_IMGREL32,
113                                  Asm->OutContext);
114 }
115
116 /// Emit the language-specific data that __C_specific_handler expects.  This
117 /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
118 /// up after faults with __try, __except, and __finally.  The typeinfo values
119 /// are not really RTTI data, but pointers to filter functions that return an
120 /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
121 /// blocks and other cleanups, the landing pad label is zero, and the filter
122 /// function is actually a cleanup handler with the same prototype.  A catch-all
123 /// entry is modeled with a null filter function field and a non-zero landing
124 /// pad label.
125 ///
126 /// Possible filter function return values:
127 ///   EXCEPTION_EXECUTE_HANDLER (1):
128 ///     Jump to the landing pad label after cleanups.
129 ///   EXCEPTION_CONTINUE_SEARCH (0):
130 ///     Continue searching this table or continue unwinding.
131 ///   EXCEPTION_CONTINUE_EXECUTION (-1):
132 ///     Resume execution at the trapping PC.
133 ///
134 /// Inferred table structure:
135 ///   struct Table {
136 ///     int NumEntries;
137 ///     struct Entry {
138 ///       imagerel32 LabelStart;
139 ///       imagerel32 LabelEnd;
140 ///       imagerel32 FilterOrFinally;  // One means catch-all.
141 ///       imagerel32 LabelLPad;        // Zero means __finally.
142 ///     } Entries[NumEntries];
143 ///   };
144 void Win64Exception::emitCSpecificHandlerTable() {
145   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
146
147   // Simplifying assumptions for first implementation:
148   // - Cleanups are not implemented.
149   // - Filters are not implemented.
150
151   // The Itanium LSDA table sorts similar landing pads together to simplify the
152   // actions table, but we don't need that.
153   SmallVector<const LandingPadInfo *, 64> LandingPads;
154   LandingPads.reserve(PadInfos.size());
155   for (const auto &LP : PadInfos)
156     LandingPads.push_back(&LP);
157
158   // Compute label ranges for call sites as we would for the Itanium LSDA, but
159   // use an all zero action table because we aren't using these actions.
160   SmallVector<unsigned, 64> FirstActions;
161   FirstActions.resize(LandingPads.size());
162   SmallVector<CallSiteEntry, 64> CallSites;
163   computeCallSiteTable(CallSites, LandingPads, FirstActions);
164
165   MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
166   MCSymbol *EHFuncEndSym = Asm->getFunctionEnd();
167
168   // Emit the number of table entries.
169   unsigned NumEntries = 0;
170   for (const CallSiteEntry &CSE : CallSites) {
171     if (!CSE.LPad)
172       continue; // Ignore gaps.
173     for (int Selector : CSE.LPad->TypeIds) {
174       // Ignore C++ filter clauses in SEH.
175       // FIXME: Implement cleanup clauses.
176       if (isCatchEHSelector(Selector))
177         ++NumEntries;
178     }
179   }
180   Asm->OutStreamer.EmitIntValue(NumEntries, 4);
181
182   // Emit the four-label records for each call site entry. The table has to be
183   // sorted in layout order, and the call sites should already be sorted.
184   for (const CallSiteEntry &CSE : CallSites) {
185     // Ignore gaps. Unlike the Itanium model, unwinding through a frame without
186     // an EH table entry will propagate the exception rather than terminating
187     // the program.
188     if (!CSE.LPad)
189       continue;
190     const LandingPadInfo *LPad = CSE.LPad;
191
192     // Compute the label range. We may reuse the function begin and end labels
193     // rather than forming new ones.
194     const MCExpr *Begin =
195         createImageRel32(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
196     const MCExpr *End;
197     if (CSE.EndLabel) {
198       // The interval is half-open, so we have to add one to include the return
199       // address of the last invoke in the range.
200       End = MCBinaryExpr::CreateAdd(createImageRel32(CSE.EndLabel),
201                                     MCConstantExpr::Create(1, Asm->OutContext),
202                                     Asm->OutContext);
203     } else {
204       End = createImageRel32(EHFuncEndSym);
205     }
206
207     // These aren't really type info globals, they are actually pointers to
208     // filter functions ordered by selector. The zero selector is used for
209     // cleanups, so slot zero corresponds to selector 1.
210     const std::vector<const GlobalValue *> &SelectorToFilter = MMI->getTypeInfos();
211
212     // Do a parallel iteration across typeids and clause labels, skipping filter
213     // clauses.
214     size_t NextClauseLabel = 0;
215     for (size_t I = 0, E = LPad->TypeIds.size(); I < E; ++I) {
216       // AddLandingPadInfo stores the clauses in reverse, but there is a FIXME
217       // to change that.
218       int Selector = LPad->TypeIds[E - I - 1];
219
220       // Ignore C++ filter clauses in SEH.
221       // FIXME: Implement cleanup clauses.
222       if (!isCatchEHSelector(Selector))
223         continue;
224
225       Asm->OutStreamer.EmitValue(Begin, 4);
226       Asm->OutStreamer.EmitValue(End, 4);
227       if (isCatchEHSelector(Selector)) {
228         assert(unsigned(Selector - 1) < SelectorToFilter.size());
229         const GlobalValue *TI = SelectorToFilter[Selector - 1];
230         if (TI) // Emit the filter function pointer.
231           Asm->OutStreamer.EmitValue(createImageRel32(Asm->getSymbol(TI)), 4);
232         else  // Otherwise, this is a "catch i8* null", or catch all.
233           Asm->OutStreamer.EmitIntValue(1, 4);
234       }
235       MCSymbol *ClauseLabel = LPad->ClauseLabels[NextClauseLabel++];
236       Asm->OutStreamer.EmitValue(createImageRel32(ClauseLabel), 4);
237     }
238   }
239 }