blob: 2138cb9514f82484333c7be5c52344698e40cb4b [file] [log] [blame]
Charles Davis91ed7992011-05-27 23:47:32 +00001//===-- 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
Saleem Abdulrasool0fba7b52014-09-01 23:48:34 +000014#include "Win64Exception.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallString.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/ADT/Twine.h"
Charles Davis91ed7992011-05-27 23:47:32 +000018#include "llvm/CodeGen/AsmPrinter.h"
Charles Davis91ed7992011-05-27 23:47:32 +000019#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000023#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Module.h"
Charles Davis91ed7992011-05-27 23:47:32 +000025#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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Support/Dwarf.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/FormattedStream.h"
Charles Davis91ed7992011-05-27 23:47:32 +000034#include "llvm/Target/TargetFrameLowering.h"
35#include "llvm/Target/TargetLoweringObjectFile.h"
Charles Davis91ed7992011-05-27 23:47:32 +000036#include "llvm/Target/TargetOptions.h"
37#include "llvm/Target/TargetRegisterInfo.h"
Charles Davis91ed7992011-05-27 23:47:32 +000038using namespace llvm;
39
40Win64Exception::Win64Exception(AsmPrinter *A)
Saleem Abdulrasool8076cab2014-06-11 01:19:03 +000041 : EHStreamer(A), shouldEmitPersonality(false), shouldEmitLSDA(false),
42 shouldEmitMoves(false) {}
Charles Davis91ed7992011-05-27 23:47:32 +000043
44Win64Exception::~Win64Exception() {}
45
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +000046/// endModule - Emit all exception information that should come after the
Charles Davis91ed7992011-05-27 23:47:32 +000047/// content.
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +000048void Win64Exception::endModule() {
Charles Davis91ed7992011-05-27 23:47:32 +000049}
50
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +000051/// beginFunction - Gather pre-function exception information. Assumes it's
Charles Davis91ed7992011-05-27 23:47:32 +000052/// being emitted immediately after the function entry point.
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +000053void Win64Exception::beginFunction(const MachineFunction *MF) {
Charles Davis5638b9f2011-05-28 04:21:04 +000054 shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
55
56 // If any landing pads survive, we need an EH table.
57 bool hasLandingPads = !MMI->getLandingPads().empty();
58
59 shouldEmitMoves = Asm->needsSEHMoves();
60
61 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
62 unsigned PerEncoding = TLOF.getPersonalityEncoding();
63 const Function *Per = MMI->getPersonalities()[MMI->getPersonalityIndex()];
64
65 shouldEmitPersonality = hasLandingPads &&
66 PerEncoding != dwarf::DW_EH_PE_omit && Per;
67
68 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
69 shouldEmitLSDA = shouldEmitPersonality &&
70 LSDAEncoding != dwarf::DW_EH_PE_omit;
71
72 if (!shouldEmitPersonality && !shouldEmitMoves)
73 return;
74
Saleem Abdulrasool7206a522014-06-29 01:52:01 +000075 Asm->OutStreamer.EmitWinCFIStartProc(Asm->CurrentFnSym);
Charles Davisb0257242011-05-29 04:28:35 +000076
77 if (!shouldEmitPersonality)
78 return;
79
NAKAMURA Takumi1db59952014-06-25 12:41:52 +000080 const MCSymbol *PersHandlerSym =
81 TLOF.getCFIPersonalitySymbol(Per, *Asm->Mang, Asm->TM, MMI);
Saleem Abdulrasool7206a522014-06-29 01:52:01 +000082 Asm->OutStreamer.EmitWinEHHandler(PersHandlerSym, true, true);
Charles Davisa5752262011-05-30 00:13:34 +000083
84 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_begin",
85 Asm->getFunctionNumber()));
Charles Davis91ed7992011-05-27 23:47:32 +000086}
87
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +000088/// endFunction - Gather and emit post-function exception information.
Charles Davis91ed7992011-05-27 23:47:32 +000089///
Timur Iskhodzhanov1cd14442013-12-03 15:10:23 +000090void Win64Exception::endFunction(const MachineFunction *) {
Charles Davis5638b9f2011-05-28 04:21:04 +000091 if (!shouldEmitPersonality && !shouldEmitMoves)
92 return;
93
Charles Davisa5752262011-05-30 00:13:34 +000094 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_end",
95 Asm->getFunctionNumber()));
96
97 // Map all labels and get rid of any dead landing pads.
98 MMI->TidyLandingPads();
99
100 if (shouldEmitPersonality) {
Charles Davisa5752262011-05-30 00:13:34 +0000101 Asm->OutStreamer.PushSection();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000102
103 // Emit an UNWIND_INFO struct describing the prologue.
Saleem Abdulrasool7206a522014-06-29 01:52:01 +0000104 Asm->OutStreamer.EmitWinEHHandlerData();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000105
106 // Emit either MSVC-compatible tables or the usual Itanium-style LSDA after
107 // the UNWIND_INFO struct.
108 if (Asm->MAI->getExceptionHandlingType() == ExceptionHandling::MSVC) {
109 const Function *Per = MMI->getPersonalities()[MMI->getPersonalityIndex()];
110 if (Per->getName() == "__C_specific_handler")
111 emitCSpecificHandlerTable();
112 else
113 report_fatal_error(Twine("unexpected personality function: ") +
114 Per->getName());
115 } else {
116 emitExceptionTable();
117 }
118
Charles Davisa5752262011-05-30 00:13:34 +0000119 Asm->OutStreamer.PopSection();
120 }
Saleem Abdulrasool7206a522014-06-29 01:52:01 +0000121 Asm->OutStreamer.EmitWinCFIEndProc();
Charles Davis91ed7992011-05-27 23:47:32 +0000122}
Reid Kleckner0a57f652015-01-14 01:05:27 +0000123
124const MCSymbolRefExpr *Win64Exception::createImageRel32(const MCSymbol *Value) {
125 return MCSymbolRefExpr::Create(Value, MCSymbolRefExpr::VK_COFF_IMGREL32,
126 Asm->OutContext);
127}
128
129/// Emit the language-specific data that __C_specific_handler expects. This
130/// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
131/// up after faults with __try, __except, and __finally. The typeinfo values
132/// are not really RTTI data, but pointers to filter functions that return an
133/// integer (1, 0, or -1) indicating how to handle the exception. For __finally
134/// blocks and other cleanups, the landing pad label is zero, and the filter
135/// function is actually a cleanup handler with the same prototype. A catch-all
136/// entry is modeled with a null filter function field and a non-zero landing
137/// pad label.
138///
139/// Possible filter function return values:
140/// EXCEPTION_EXECUTE_HANDLER (1):
141/// Jump to the landing pad label after cleanups.
142/// EXCEPTION_CONTINUE_SEARCH (0):
143/// Continue searching this table or continue unwinding.
144/// EXCEPTION_CONTINUE_EXECUTION (-1):
145/// Resume execution at the trapping PC.
146///
147/// Inferred table structure:
148/// struct Table {
149/// int NumEntries;
150/// struct Entry {
151/// imagerel32 LabelStart;
152/// imagerel32 LabelEnd;
153/// imagerel32 FilterOrFinally; // Zero means catch-all.
154/// imagerel32 LabelLPad; // Zero means __finally.
155/// } Entries[NumEntries];
156/// };
157void Win64Exception::emitCSpecificHandlerTable() {
158 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
159
160 // Simplifying assumptions for first implementation:
161 // - Cleanups are not implemented.
162 // - Filters are not implemented.
163
164 // The Itanium LSDA table sorts similar landing pads together to simplify the
165 // actions table, but we don't need that.
166 SmallVector<const LandingPadInfo *, 64> LandingPads;
167 LandingPads.reserve(PadInfos.size());
168 for (const auto &LP : PadInfos)
169 LandingPads.push_back(&LP);
170
171 // Compute label ranges for call sites as we would for the Itanium LSDA, but
172 // use an all zero action table because we aren't using these actions.
173 SmallVector<unsigned, 64> FirstActions;
174 FirstActions.resize(LandingPads.size());
175 SmallVector<CallSiteEntry, 64> CallSites;
176 computeCallSiteTable(CallSites, LandingPads, FirstActions);
177
178 MCSymbol *EHFuncBeginSym =
179 Asm->GetTempSymbol("eh_func_begin", Asm->getFunctionNumber());
180 MCSymbol *EHFuncEndSym =
181 Asm->GetTempSymbol("eh_func_end", Asm->getFunctionNumber());
182
183 // Emit the number of table entries.
184 unsigned NumEntries = 0;
185 for (const CallSiteEntry &CSE : CallSites) {
186 if (!CSE.LPad)
187 continue; // Ignore gaps.
188 for (int Selector : CSE.LPad->TypeIds) {
189 // Ignore C++ filter clauses in SEH.
190 // FIXME: Implement cleanup clauses.
191 if (isCatchEHSelector(Selector))
192 ++NumEntries;
193 }
194 }
195 Asm->OutStreamer.EmitIntValue(NumEntries, 4);
196
197 // Emit the four-label records for each call site entry. The table has to be
198 // sorted in layout order, and the call sites should already be sorted.
199 for (const CallSiteEntry &CSE : CallSites) {
200 // Ignore gaps. Unlike the Itanium model, unwinding through a frame without
201 // an EH table entry will propagate the exception rather than terminating
202 // the program.
203 if (!CSE.LPad)
204 continue;
205 const LandingPadInfo *LPad = CSE.LPad;
206
207 // Compute the label range. We may reuse the function begin and end labels
208 // rather than forming new ones.
209 const MCExpr *Begin =
210 createImageRel32(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
211 const MCExpr *End;
212 if (CSE.EndLabel) {
213 // The interval is half-open, so we have to add one to include the return
214 // address of the last invoke in the range.
215 End = MCBinaryExpr::CreateAdd(createImageRel32(CSE.EndLabel),
216 MCConstantExpr::Create(1, Asm->OutContext),
217 Asm->OutContext);
218 } else {
219 End = createImageRel32(EHFuncEndSym);
220 }
221
222 // These aren't really type info globals, they are actually pointers to
223 // filter functions ordered by selector. The zero selector is used for
224 // cleanups, so slot zero corresponds to selector 1.
225 const std::vector<const GlobalValue *> &SelectorToFilter = MMI->getTypeInfos();
226
227 // Do a parallel iteration across typeids and clause labels, skipping filter
228 // clauses.
229 assert(LPad->TypeIds.size() == LPad->ClauseLabels.size());
230 for (size_t I = 0, E = LPad->TypeIds.size(); I < E; ++I) {
231 // AddLandingPadInfo stores the clauses in reverse, but there is a FIXME
232 // to change that.
233 int Selector = LPad->TypeIds[E - I - 1];
234 MCSymbol *ClauseLabel = LPad->ClauseLabels[I];
235
236 // Ignore C++ filter clauses in SEH.
237 // FIXME: Implement cleanup clauses.
238 if (!isCatchEHSelector(Selector))
239 continue;
240
241 Asm->OutStreamer.EmitValue(Begin, 4);
242 Asm->OutStreamer.EmitValue(End, 4);
243 if (isCatchEHSelector(Selector)) {
244 assert(unsigned(Selector - 1) < SelectorToFilter.size());
245 const GlobalValue *TI = SelectorToFilter[Selector - 1];
246 if (TI) // Emit the filter function pointer.
247 Asm->OutStreamer.EmitValue(createImageRel32(Asm->getSymbol(TI)), 4);
248 else // Otherwise, this is a "catch i8* null", or catch all.
249 Asm->OutStreamer.EmitIntValue(0, 4);
250 }
251 Asm->OutStreamer.EmitValue(createImageRel32(ClauseLabel), 4);
252 }
253 }
254}