blob: b0c6b7d11e4dfffb515b29c47afc534d1b03576c [file] [log] [blame]
Reid Kleckner60b640b2015-05-28 22:47:01 +00001//===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
Charles Davis91ed7992011-05-27 23:47:32 +00002//
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
Reid Kleckner60b640b2015-05-28 22:47:01 +000014#include "WinException.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"
David Majnemercde33032015-03-30 22:58:10 +000022#include "llvm/CodeGen/WinEHFuncInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000024#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Module.h"
Charles Davis91ed7992011-05-27 23:47:32 +000026#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"
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000032#include "llvm/MC/MCWin64EH.h"
David Majnemera80c1512015-09-29 20:12:33 +000033#include "llvm/Support/COFF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/Dwarf.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/FormattedStream.h"
Charles Davis91ed7992011-05-27 23:47:32 +000037#include "llvm/Target/TargetFrameLowering.h"
38#include "llvm/Target/TargetLoweringObjectFile.h"
Charles Davis91ed7992011-05-27 23:47:32 +000039#include "llvm/Target/TargetOptions.h"
40#include "llvm/Target/TargetRegisterInfo.h"
Charles Davis91ed7992011-05-27 23:47:32 +000041using namespace llvm;
42
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000043WinException::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}
Charles Davis91ed7992011-05-27 23:47:32 +000048
Reid Kleckner60b640b2015-05-28 22:47:01 +000049WinException::~WinException() {}
Charles Davis91ed7992011-05-27 23:47:32 +000050
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +000051/// endModule - Emit all exception information that should come after the
Charles Davis91ed7992011-05-27 23:47:32 +000052/// content.
Reid Kleckner60b640b2015-05-28 22:47:01 +000053void WinException::endModule() {
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000054 auto &OS = *Asm->OutStreamer;
55 const Module *M = MMI->getModule();
Reid Klecknerca6ef662015-06-10 01:13:44 +000056 for (const Function &F : *M)
57 if (F.hasFnAttribute("safeseh"))
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000058 OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
Charles Davis91ed7992011-05-27 23:47:32 +000059}
60
Reid Kleckner60b640b2015-05-28 22:47:01 +000061void WinException::beginFunction(const MachineFunction *MF) {
Charles Davis5638b9f2011-05-28 04:21:04 +000062 shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
63
64 // If any landing pads survive, we need an EH table.
65 bool hasLandingPads = !MMI->getLandingPads().empty();
Reid Kleckner0e288232015-08-27 23:27:47 +000066 bool hasEHFunclets = MMI->hasEHFunclets();
Charles Davis5638b9f2011-05-28 04:21:04 +000067
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000068 const Function *F = MF->getFunction();
69 const Function *ParentF = MMI->getWinEHParent(F);
70
Charles Davis5638b9f2011-05-28 04:21:04 +000071 shouldEmitMoves = Asm->needsSEHMoves();
72
73 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
74 unsigned PerEncoding = TLOF.getPersonalityEncoding();
Reid Kleckner9a1a9192015-07-13 20:41:46 +000075 const Function *Per = nullptr;
76 if (F->hasPersonalityFn())
77 Per = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Charles Davis5638b9f2011-05-28 04:21:04 +000078
Keno Fischeraff703a2015-07-14 19:22:51 +000079 bool forceEmitPersonality =
80 F->hasPersonalityFn() && !isNoOpWithoutInvoke(classifyEHPersonality(Per)) &&
81 F->needsUnwindTableEntry();
82
Reid Kleckner0e288232015-08-27 23:27:47 +000083 shouldEmitPersonality =
84 forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
85 PerEncoding != dwarf::DW_EH_PE_omit && Per);
Charles Davis5638b9f2011-05-28 04:21:04 +000086
87 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
88 shouldEmitLSDA = shouldEmitPersonality &&
89 LSDAEncoding != dwarf::DW_EH_PE_omit;
90
Reid Kleckner0e288232015-08-27 23:27:47 +000091 // 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.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000095 if (!Asm->MAI->usesWindowsCFI()) {
Reid Kleckner0e288232015-08-27 23:27:47 +000096 shouldEmitLSDA =
97 hasEHFunclets || (F->hasFnAttribute("wineh-parent") && F == ParentF);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000098 shouldEmitPersonality = false;
99 return;
100 }
David Majnemera225a192015-03-31 22:35:44 +0000101
David Majnemera80c1512015-09-29 20:12:33 +0000102 beginFunclet(MF->front(), Asm->CurrentFnSym);
Charles Davis91ed7992011-05-27 23:47:32 +0000103}
104
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +0000105/// endFunction - Gather and emit post-function exception information.
Charles Davis91ed7992011-05-27 23:47:32 +0000106///
Reid Kleckner60b640b2015-05-28 22:47:01 +0000107void WinException::endFunction(const MachineFunction *MF) {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000108 if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
Charles Davis5638b9f2011-05-28 04:21:04 +0000109 return;
110
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000111 const Function *F = MF->getFunction();
112 EHPersonality Per = EHPersonality::Unknown;
113 if (F->hasPersonalityFn())
114 Per = classifyEHPersonality(F->getPersonalityFn());
Reid Kleckner3e9fadf2015-04-15 18:48:15 +0000115
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();
Charles Davisa5752262011-05-30 00:13:34 +0000121
David Majnemera80c1512015-09-29 20:12:33 +0000122 endFunclet();
123
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000124 // endFunclet will emit the necessary .xdata tables for x64 SEH.
125 if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets())
126 return;
127
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000128 if (shouldEmitPersonality || shouldEmitLSDA) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000129 Asm->OutStreamer->PushSection();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000130
David Majnemera80c1512015-09-29 20:12:33 +0000131 // 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);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000136
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000137 // 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.
Reid Kleckner2d5fb682015-02-14 00:21:02 +0000139 if (Per == EHPersonality::MSVC_Win64SEH)
Reid Kleckner94b704c2015-09-09 21:10:03 +0000140 emitCSpecificHandlerTable(MF);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000141 else if (Per == EHPersonality::MSVC_X86SEH)
Reid Klecknerf12c0302015-06-09 21:42:19 +0000142 emitExceptHandlerTable(MF);
David Majnemercde33032015-03-30 22:58:10 +0000143 else if (Per == EHPersonality::MSVC_CXX)
144 emitCXXFrameHandler3Table(MF);
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000145 else
Reid Kleckner0a57f652015-01-14 01:05:27 +0000146 emitExceptionTable();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000147
Lang Hames9ff69c82015-04-24 19:11:51 +0000148 Asm->OutStreamer->PopSection();
Charles Davisa5752262011-05-30 00:13:34 +0000149 }
David Majnemera80c1512015-09-29 20:12:33 +0000150}
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000151
David Majnemera80c1512015-09-29 20:12:33 +0000152/// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock. GlobalValues
153/// are used in the old WinEH scheme, and they will be removed eventually.
154static 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
175void 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.
David Majnemer0e705982015-09-11 17:34:34 +0000201 if (shouldEmitMoves || shouldEmitPersonality)
David Majnemera80c1512015-09-29 20:12:33 +0000202 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
226void 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
David Majnemera80c1512015-09-29 20:12:33 +0000244 if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
245 !CurrentFuncletEntry->isCleanupFuncletEntry()) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000246 // If this is a C++ catch funclet (or the parent function),
247 // emit a reference to the LSDA for the parent function.
David Majnemera80c1512015-09-29 20:12:33 +0000248 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
249 MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
250 Twine("$cppxdata$", FuncLinkageName));
251 Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000252 } 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);
David Majnemera80c1512015-09-29 20:12:33 +0000257 }
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.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000264 Asm->OutStreamer->EmitWinCFIEndProc();
David Majnemera80c1512015-09-29 20:12:33 +0000265 }
266
267 // Let's make sure we don't try to end the same funclet twice.
268 CurrentFuncletEntry = nullptr;
Charles Davis91ed7992011-05-27 23:47:32 +0000269}
Reid Kleckner0a57f652015-01-14 01:05:27 +0000270
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000271const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
David Majnemercde33032015-03-30 22:58:10 +0000272 if (!Value)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000273 return MCConstantExpr::create(0, Asm->OutContext);
274 return MCSymbolRefExpr::create(Value, useImageRel32
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000275 ? MCSymbolRefExpr::VK_COFF_IMGREL32
276 : MCSymbolRefExpr::VK_None,
Reid Kleckner0a57f652015-01-14 01:05:27 +0000277 Asm->OutContext);
278}
279
David Majnemer0ad363e2015-08-18 19:07:12 +0000280const MCExpr *WinException::create32bitRef(const Value *V) {
281 if (!V)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000282 return MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner0e288232015-08-27 23:27:47 +0000283 // 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)));
David Majnemercde33032015-03-30 22:58:10 +0000287}
288
Reid Klecknerc71d6272015-09-28 23:56:30 +0000289const MCExpr *WinException::getLabelPlusOne(MCSymbol *Label) {
290 return MCBinaryExpr::createAdd(create32bitRef(Label),
291 MCConstantExpr::create(1, Asm->OutContext),
292 Asm->OutContext);
293}
294
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000295/// Information describing an invoke range.
296struct 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.
307class InvokeLabelIterator {
308public:
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
323private:
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.
335InvokeLabelIterator &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.
379static iterator_range<InvokeLabelIterator>
380invoke_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
Reid Kleckner0a57f652015-01-14 01:05:27 +0000385/// 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;
Reid Klecknerf690f502015-01-22 02:27:44 +0000409/// imagerel32 FilterOrFinally; // One means catch-all.
Reid Kleckner0a57f652015-01-14 01:05:27 +0000410/// imagerel32 LabelLPad; // Zero means __finally.
411/// } Entries[NumEntries];
412/// };
Reid Kleckner94b704c2015-09-09 21:10:03 +0000413void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000414 auto &OS = *Asm->OutStreamer;
415 MCContext &Ctx = Asm->OutContext;
Reid Kleckner0a57f652015-01-14 01:05:27 +0000416
Reid Kleckner94b704c2015-09-09 21:10:03 +0000417 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(MF->getFunction());
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000418 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 }
Reid Kleckner94b704c2015-09-09 21:10:03 +0000494
Reid Kleckner0a57f652015-01-14 01:05:27 +0000495 // 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.
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000501 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000502 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
Rafael Espindola629cdba2015-02-27 18:18:39 +0000514 MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
515 MCSymbol *EHFuncEndSym = Asm->getFunctionEnd();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000516
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.
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000522 NumEntries += CSE.LPad->SEHHandlers.size();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000523 }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000524 OS.EmitIntValue(NumEntries, 4);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000525
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000526 // If there are no actions, we don't need to iterate again.
527 if (NumEntries == 0)
528 return;
529
Reid Kleckner0a57f652015-01-14 01:05:27 +0000530 // 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 =
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000543 create32bitRef(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000544 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.
Reid Klecknerc71d6272015-09-28 23:56:30 +0000548 End = getLabelPlusOne(CSE.EndLabel);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000549 } else {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000550 End = create32bitRef(EHFuncEndSym);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000551 }
552
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000553 // Emit an entry for each action.
554 for (SEHHandler Handler : LPad->SEHHandlers) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000555 OS.EmitValue(Begin, 4);
556 OS.EmitValue(End, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000557
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)
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000562 OS.EmitValue(create32bitRef(Asm->getSymbol(F)), 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000563 else
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000564 OS.EmitIntValue(1, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000565
566 // Emit the recovery address, if present. Otherwise, this must be a
567 // finally.
568 const BlockAddress *BA = Handler.RecoverBA;
569 if (BA)
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000570 OS.EmitValue(
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000571 create32bitRef(Asm->GetBlockAddressSymbol(BA)), 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000572 else
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000573 OS.EmitIntValue(0, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000574 }
Reid Kleckner0a57f652015-01-14 01:05:27 +0000575 }
576}
David Majnemercde33032015-03-30 22:58:10 +0000577
Reid Kleckner60b640b2015-05-28 22:47:01 +0000578void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
David Majnemercde33032015-03-30 22:58:10 +0000579 const Function *F = MF->getFunction();
Lang Hames9ff69c82015-04-24 19:11:51 +0000580 auto &OS = *Asm->OutStreamer;
Reid Kleckner813f1b62015-09-16 22:14:46 +0000581 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
David Majnemercde33032015-03-30 22:58:10 +0000582
Reid Kleckner813f1b62015-09-16 22:14:46 +0000583 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
David Majnemercde33032015-03-30 22:58:10 +0000584
Reid Klecknerc71d6272015-09-28 23:56:30 +0000585 SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000586 MCSymbol *FuncInfoXData = nullptr;
587 if (shouldEmitPersonality) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000588 // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
589 // IPs to state numbers.
Reid Kleckner813f1b62015-09-16 22:14:46 +0000590 FuncInfoXData =
591 Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000592 computeIP2StateTable(MF, FuncInfo, IPToStateTable);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000593 } else {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000594 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
595 emitEHRegistrationOffsetLabel(FuncInfo, FuncLinkageName);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000596 }
597
598 MCSymbol *UnwindMapXData = nullptr;
599 MCSymbol *TryBlockMapXData = nullptr;
600 MCSymbol *IPToStateXData = nullptr;
601 if (!FuncInfo.UnwindMap.empty())
602 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000603 Twine("$stateUnwindMap$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000604 if (!FuncInfo.TryBlockMap.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000605 TryBlockMapXData =
606 Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000607 if (!IPToStateTable.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000608 IPToStateXData =
609 Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000610
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.
Reid Kleckner85a24502015-07-10 00:08:49 +0000626 OS.EmitValueToAlignment(4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000627 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
Reid Klecknerc71d6272015-09-28 23:56:30 +0000633 OS.EmitIntValue(IPToStateTable.size(), 4); // IPMapEntries
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000634 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) {
Reid Kleckner78783912015-09-10 00:25:23 +0000647 MCSymbol *CleanupSym = getMCSymbolForMBBOrGV(Asm, UME.Cleanup);
648 OS.EmitIntValue(UME.ToState, 4); // ToState
649 OS.EmitValue(create32bitRef(CleanupSym), 4); // Action
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000650 }
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];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000665
Reid Kleckner813f1b62015-09-16 22:14:46 +0000666 MCSymbol *HandlerMapXData = nullptr;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000667 if (!TBME.HandlerArray.empty())
668 HandlerMapXData =
669 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
670 .concat(Twine(I))
671 .concat("$")
Reid Kleckner813f1b62015-09-16 22:14:46 +0000672 .concat(FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000673 HandlerMaps.push_back(HandlerMapXData);
674
Reid Kleckner813f1b62015-09-16 22:14:46 +0000675 // 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");
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000681
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000682 OS.EmitIntValue(TBME.TryLow, 4); // TryLow
683 OS.EmitIntValue(TBME.TryHigh, 4); // TryHigh
Reid Kleckner813f1b62015-09-16 22:14:46 +0000684 OS.EmitIntValue(TBME.CatchHigh, 4); // CatchHigh
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000685 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(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000710 FuncLinkageName, HT.CatchObjRecoverIdx);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000711 FrameAllocOffsetRef = MCSymbolRefExpr::create(
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000712 FrameAllocOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
Reid Klecknerb005d282015-09-16 20:16:27 +0000713 } 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);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000723 } else {
Jim Grosbach13760bd2015-05-30 01:25:56 +0000724 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000725 }
726
Reid Kleckner94b704c2015-09-09 21:10:03 +0000727 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
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000733
734 if (shouldEmitPersonality) {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000735 // 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
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000740 }
741 }
742 }
743 }
744
745 // IPToStateMapEntry {
746 // void *IP;
747 // int32_t State;
748 // };
749 if (IPToStateXData) {
750 OS.EmitLabel(IPToStateXData);
Reid Klecknerc71d6272015-09-28 23:56:30 +0000751 for (auto &IPStatePair : IPToStateTable) {
752 OS.EmitValue(IPStatePair.first, 4); // IP
753 OS.EmitIntValue(IPStatePair.second, 4); // State
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000754 }
755 }
756}
757
Reid Klecknerc71d6272015-09-28 23:56:30 +0000758void WinException::computeIP2StateTable(
759 const MachineFunction *MF, WinEHFuncInfo &FuncInfo,
760 SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000761 // 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");
David Majnemercde33032015-03-30 22:58:10 +0000767
Reid Klecknerc71d6272015-09-28 23:56:30 +0000768 // 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));
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000772
David Majnemercde33032015-03-30 22:58:10 +0000773 for (const auto &MBB : *MF) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000774 // FIXME: Do we need to emit entries for funclet base states?
775
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000776 for (InvokeRange &I : invoke_ranges(FuncInfo, MBB)) {
777 assert(I.BeginLabel && I.EndLabel);
Reid Klecknerc71d6272015-09-28 23:56:30 +0000778 // 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.
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000781 if (I.SawPotentiallyThrowing && LastEHState != -1) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000782 IPToStateTable.push_back(
783 std::make_pair(getLabelPlusOne(LastEndLabel), -1));
David Majnemercde33032015-03-30 22:58:10 +0000784 LastEHState = -1;
785 }
786
Reid Klecknerc71d6272015-09-28 23:56:30 +0000787 // Emit an entry indicating that PCs after 'Label' have this EH state.
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000788 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;
David Majnemercde33032015-03-30 22:58:10 +0000793 }
794 }
Reid Klecknerc71d6272015-09-28 23:56:30 +0000795
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 }
David Majnemercde33032015-03-30 22:58:10 +0000802}
Reid Klecknerf12c0302015-06-09 21:42:19 +0000803
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000804void 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 &&
Reid Kleckner60381792015-07-07 22:25:32 +0000811 "no EH reg node localescape index");
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000812 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
Reid Klecknerf12c0302015-06-09 21:42:19 +0000821/// 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.
824void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
Reid Klecknera9d62532015-06-11 22:32:23 +0000825 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknera9d62532015-06-11 22:32:23 +0000826 const Function *F = MF->getFunction();
Reid Klecknera9d62532015-06-11 22:32:23 +0000827 StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000828
829 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
830 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000831
832 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
Reid Klecknerf12c0302015-06-09 21:42:19 +0000833 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
Reid Kleckner85a24502015-07-10 00:08:49 +0000834 OS.EmitValueToAlignment(4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000835 OS.EmitLabel(LSDALabel);
836
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000837 const Function *Per =
838 dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Reid Klecknerf12c0302015-06-09 21:42:19 +0000839 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
Reid Kleckner94b704c2015-09-09 21:10:03 +0000863 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
Reid Klecknerf12c0302015-06-09 21:42:19 +0000876 // 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;
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000890 // int32_t (__cdecl *Filter)();
891 // void *HandlerOrFinally;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000892 // };
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;
Reid Kleckner7912d9b2015-06-10 00:04:53 +0000899 assert(CurState + int(LPInfo->SEHHandlers.size()) - 1 ==
900 LPInfo->WinEHState &&
Reid Klecknerf12c0302015-06-09 21:42:19 +0000901 "gaps in the SEH scope table");
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000902 for (auto I = LPInfo->SEHHandlers.rbegin(), E = LPInfo->SEHHandlers.rend();
903 I != E; ++I) {
904 const SEHHandler &Handler = *I;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000905 const BlockAddress *BA = Handler.RecoverBA;
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000906 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));
Reid Klecknerf12c0302015-06-09 21:42:19 +0000912
913 OS.EmitIntValue(EnclosingLevel, 4);
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000914 OS.EmitValue(FilterOrNull, 4);
915 OS.EmitValue(ExceptOrFinally, 4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000916
917 // The next state unwinds to this state.
918 EnclosingLevel = CurState;
919 CurState++;
920 }
921 }
922}