1//===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains support for writing Win64 exception info into asm files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "WinException.h"
14#include "llvm/ADT/Twine.h"
15#include "llvm/BinaryFormat/COFF.h"
16#include "llvm/BinaryFormat/Dwarf.h"
17#include "llvm/CodeGen/AsmPrinter.h"
18#include "llvm/CodeGen/MachineFrameInfo.h"
19#include "llvm/CodeGen/MachineFunction.h"
20#include "llvm/CodeGen/MachineModuleInfo.h"
21#include "llvm/CodeGen/TargetFrameLowering.h"
22#include "llvm/CodeGen/TargetLowering.h"
23#include "llvm/CodeGen/TargetSubtargetInfo.h"
24#include "llvm/CodeGen/WinEHFuncInfo.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Module.h"
27#include "llvm/MC/MCAsmInfo.h"
28#include "llvm/MC/MCContext.h"
29#include "llvm/MC/MCExpr.h"
30#include "llvm/MC/MCStreamer.h"
31#include "llvm/Target/TargetLoweringObjectFile.h"
32#include "llvm/Target/TargetMachine.h"
33using namespace llvm;
34
35WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
36 // MSVC's EH tables are always composed of 32-bit words. All known
37 // architectures use an imagerel32 relocation to refer to symbols, except
38 // 32-bit x86.
39 useImageRel32 = A->TM.getTargetTriple().getArch() != Triple::x86;
40 isAArch64 = Asm->TM.getTargetTriple().isAArch64();
41 isThumb = Asm->TM.getTargetTriple().isThumb();
42}
43
44WinException::~WinException() = default;
45
46/// endModule - Emit all exception information that should come after the
47/// content.
48void WinException::endModule() {
49 auto &OS = *Asm->OutStreamer;
50 const Module *M = MMI->getModule();
51 for (const Function &F : *M)
52 if (F.hasFnAttribute(Kind: "safeseh"))
53 OS.emitCOFFSafeSEH(Symbol: Asm->getSymbol(GV: &F));
54
55 if (M->getModuleFlag(Key: "ehcontguard") && !EHContTargets.empty()) {
56 // Emit the symbol index of each ehcont target.
57 OS.switchSection(Section: Asm->OutContext.getObjectFileInfo()->getGEHContSection());
58 for (const MCSymbol *S : EHContTargets) {
59 OS.emitCOFFSymbolIndex(Symbol: S);
60 }
61 }
62}
63
64void WinException::beginFunction(const MachineFunction *MF) {
65 shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
66
67 // If any landing pads survive, we need an EH table.
68 bool hasLandingPads = !MF->getLandingPads().empty();
69 bool hasEHFunclets = MF->hasEHFunclets();
70
71 const Function &F = MF->getFunction();
72
73 shouldEmitMoves = Asm->needsSEHMoves() && MF->hasWinCFI();
74
75 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
76 unsigned PerEncoding = TLOF.getPersonalityEncoding();
77
78 EHPersonality Per = EHPersonality::Unknown;
79 const Function *PerFn = nullptr;
80 if (F.hasPersonalityFn()) {
81 PerFn = dyn_cast<Function>(Val: F.getPersonalityFn()->stripPointerCasts());
82 Per = classifyEHPersonality(Pers: PerFn);
83 }
84
85 bool forceEmitPersonality = F.hasPersonalityFn() &&
86 !isNoOpWithoutInvoke(Pers: Per) &&
87 F.needsUnwindTableEntry();
88
89 shouldEmitPersonality =
90 forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
91 PerEncoding != dwarf::DW_EH_PE_omit && PerFn);
92
93 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
94 shouldEmitLSDA = shouldEmitPersonality &&
95 LSDAEncoding != dwarf::DW_EH_PE_omit;
96
97 // If we're not using CFI, we don't want the CFI or the personality, but we
98 // might want EH tables if we had EH pads.
99 if (!Asm->MAI.usesWindowsCFI()) {
100 if (Per == EHPersonality::MSVC_X86SEH && !hasEHFunclets) {
101 // If this is 32-bit SEH and we don't have any funclets (really invokes),
102 // make sure we emit the parent offset label. Some unreferenced filter
103 // functions may still refer to it.
104 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
105 StringRef FLinkageName =
106 GlobalValue::dropLLVMManglingEscape(Name: MF->getFunction().getName());
107 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
108 }
109 shouldEmitLSDA = hasEHFunclets;
110 shouldEmitPersonality = false;
111 return;
112 }
113
114 beginFunclet(MBB: MF->front(), Sym: Asm->CurrentFnSym);
115}
116
117void WinException::markFunctionEnd() {
118 if (isAArch64 && CurrentFuncletEntry &&
119 (shouldEmitMoves || shouldEmitPersonality))
120 Asm->OutStreamer->emitWinCFIFuncletOrFuncEnd();
121}
122
123/// endFunction - Gather and emit post-function exception information.
124///
125void WinException::endFunction(const MachineFunction *MF) {
126 if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
127 return;
128
129 const Function &F = MF->getFunction();
130 EHPersonality Per = EHPersonality::Unknown;
131 if (F.hasPersonalityFn())
132 Per = classifyEHPersonality(Pers: F.getPersonalityFn()->stripPointerCasts());
133
134 endFuncletImpl();
135
136 // endFunclet will emit the necessary .xdata tables for table-based SEH.
137 if (Per == EHPersonality::MSVC_TableSEH && MF->hasEHFunclets())
138 return;
139
140 if (shouldEmitPersonality || shouldEmitLSDA) {
141 Asm->OutStreamer->pushSection();
142
143 // Just switch sections to the right xdata section.
144 MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
145 TextSec: Asm->OutStreamer->getCurrentSectionOnly());
146 Asm->OutStreamer->switchSection(Section: XData);
147
148 // Emit the tables appropriate to the personality function in use. If we
149 // don't recognize the personality, assume it uses an Itanium-style LSDA.
150 if (Per == EHPersonality::MSVC_TableSEH)
151 emitCSpecificHandlerTable(MF);
152 else if (Per == EHPersonality::MSVC_X86SEH)
153 emitExceptHandlerTable(MF);
154 else if (Per == EHPersonality::MSVC_CXX)
155 emitCXXFrameHandler3Table(MF);
156 else if (Per == EHPersonality::CoreCLR)
157 emitCLRExceptionTable(MF);
158 else
159 emitExceptionTable();
160
161 Asm->OutStreamer->popSection();
162 }
163
164 if (!MF->getEHContTargets().empty()) {
165 // Copy the function's EH Continuation targets to a module-level list.
166 llvm::append_range(C&: EHContTargets, R: MF->getEHContTargets());
167 }
168}
169
170/// Retrieve the MCSymbol for a GlobalValue or MachineBasicBlock.
171static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
172 const MachineBasicBlock *MBB) {
173 if (!MBB)
174 return nullptr;
175
176 assert(MBB->isEHFuncletEntry());
177
178 // Give catches and cleanups a name based off of their parent function and
179 // their funclet entry block's number.
180 const MachineFunction *MF = MBB->getParent();
181 const Function &F = MF->getFunction();
182 StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(Name: F.getName());
183 MCContext &Ctx = MF->getContext();
184 StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
185 return Ctx.getOrCreateSymbol(Name: "?" + HandlerPrefix + "$" +
186 Twine(MBB->getNumber()) + "@?0?" +
187 FuncLinkageName + "@4HA");
188}
189
190void WinException::beginFunclet(const MachineBasicBlock &MBB,
191 MCSymbol *Sym) {
192 CurrentFuncletEntry = &MBB;
193
194 const Function &F = Asm->MF->getFunction();
195 // If a symbol was not provided for the funclet, invent one.
196 if (!Sym) {
197 Sym = getMCSymbolForMBB(Asm, MBB: &MBB);
198
199 // Describe our funclet symbol as a function with internal linkage.
200 Asm->OutStreamer->beginCOFFSymbolDef(Symbol: Sym);
201 Asm->OutStreamer->emitCOFFSymbolStorageClass(StorageClass: COFF::IMAGE_SYM_CLASS_STATIC);
202 Asm->OutStreamer->emitCOFFSymbolType(Type: COFF::IMAGE_SYM_DTYPE_FUNCTION
203 << COFF::SCT_COMPLEX_TYPE_SHIFT);
204 Asm->OutStreamer->endCOFFSymbolDef();
205
206 // We want our funclet's entry point to be aligned such that no nops will be
207 // present after the label.
208 Asm->emitAlignment(
209 Alignment: std::max(a: Asm->MF->getPreferredAlignment(), b: MBB.getAlignment()), GV: &F);
210
211 // Now that we've emitted the alignment directive, point at our funclet.
212 Asm->OutStreamer->emitLabel(Symbol: Sym);
213 }
214
215 // Mark 'Sym' as starting our funclet.
216 if (shouldEmitMoves || shouldEmitPersonality) {
217 CurrentFuncletTextSection = Asm->OutStreamer->getCurrentSectionOnly();
218 Asm->OutStreamer->emitWinCFIStartProc(Symbol: Sym);
219 }
220
221 if (shouldEmitPersonality) {
222 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
223 const Function *PerFn = nullptr;
224
225 // Determine which personality routine we are using for this funclet.
226 if (F.hasPersonalityFn())
227 PerFn = dyn_cast<Function>(Val: F.getPersonalityFn()->stripPointerCasts());
228 const MCSymbol *PersHandlerSym =
229 TLOF.getCFIPersonalitySymbol(GV: PerFn, TM: Asm->TM, MMI);
230
231 // Do not emit a .seh_handler directives for cleanup funclets.
232 // FIXME: This means cleanup funclets cannot handle exceptions. Given that
233 // Clang doesn't produce EH constructs inside cleanup funclets and LLVM's
234 // inliner doesn't allow inlining them, this isn't a major problem in
235 // practice.
236 if (!CurrentFuncletEntry->isCleanupFuncletEntry())
237 Asm->OutStreamer->emitWinEHHandler(Sym: PersHandlerSym, Unwind: true, Except: true);
238 }
239}
240
241void WinException::endFunclet() {
242 if (isAArch64 && CurrentFuncletEntry &&
243 (shouldEmitMoves || shouldEmitPersonality)) {
244 Asm->OutStreamer->switchSection(Section: CurrentFuncletTextSection);
245 Asm->OutStreamer->emitWinCFIFuncletOrFuncEnd();
246 }
247 endFuncletImpl();
248}
249
250void WinException::endFuncletImpl() {
251 // No funclet to process? Great, we have nothing to do.
252 if (!CurrentFuncletEntry)
253 return;
254
255 const MachineFunction *MF = Asm->MF;
256 if (shouldEmitMoves || shouldEmitPersonality) {
257 const Function &F = MF->getFunction();
258 EHPersonality Per = EHPersonality::Unknown;
259 if (F.hasPersonalityFn())
260 Per = classifyEHPersonality(Pers: F.getPersonalityFn()->stripPointerCasts());
261
262 if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
263 !CurrentFuncletEntry->isCleanupFuncletEntry()) {
264 // Emit an UNWIND_INFO struct describing the prologue.
265 Asm->OutStreamer->emitWinEHHandlerData();
266
267 // If this is a C++ catch funclet (or the parent function),
268 // emit a reference to the LSDA for the parent function.
269 StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(Name: F.getName());
270 MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
271 Name: Twine("$cppxdata$", FuncLinkageName));
272 Asm->OutStreamer->emitValue(Value: create32bitRef(Value: FuncInfoXData), Size: 4);
273 } else if (Per == EHPersonality::MSVC_TableSEH && MF->hasEHFunclets() &&
274 !CurrentFuncletEntry->isEHFuncletEntry()) {
275 // Emit an UNWIND_INFO struct describing the prologue.
276 Asm->OutStreamer->emitWinEHHandlerData();
277
278 // If this is the parent function in Win64 SEH, emit the LSDA immediately
279 // following .seh_handlerdata.
280 emitCSpecificHandlerTable(MF);
281 } else if (shouldEmitPersonality || shouldEmitLSDA) {
282 // Emit an UNWIND_INFO struct describing the prologue.
283 Asm->OutStreamer->emitWinEHHandlerData();
284 // In these cases, no further info is written to the .xdata section
285 // right here, but is written by e.g. emitExceptionTable in endFunction()
286 // above.
287 } else {
288 // No need to emit the EH handler data right here if nothing needs
289 // writing to the .xdata section; it will be emitted for all
290 // functions that need it in the end anyway.
291 }
292
293 if (!MF->getEHContTargets().empty()) {
294 // Copy the function's EH Continuation targets to a module-level list.
295 llvm::append_range(C&: EHContTargets, R: MF->getEHContTargets());
296 }
297
298 // Switch back to the funclet start .text section now that we are done
299 // writing to .xdata, and emit an .seh_endproc directive to mark the end of
300 // the function.
301 Asm->OutStreamer->switchSection(Section: CurrentFuncletTextSection);
302 Asm->OutStreamer->emitWinCFIEndProc();
303 }
304
305 // Let's make sure we don't try to end the same funclet twice.
306 CurrentFuncletEntry = nullptr;
307}
308
309const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
310 if (!Value)
311 return MCConstantExpr::create(Value: 0, Ctx&: Asm->OutContext);
312 auto Spec = useImageRel32 ? uint16_t(MCSymbolRefExpr::VK_COFF_IMGREL32) : 0;
313 return MCSymbolRefExpr::create(Symbol: Value, specifier: Spec, Ctx&: Asm->OutContext);
314}
315
316const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
317 if (!GV)
318 return MCConstantExpr::create(Value: 0, Ctx&: Asm->OutContext);
319 return create32bitRef(Value: Asm->getSymbol(GV));
320}
321
322const MCExpr *WinException::getLabel(const MCSymbol *Label) {
323 return MCSymbolRefExpr::create(Symbol: Label, specifier: MCSymbolRefExpr::VK_COFF_IMGREL32,
324 Ctx&: Asm->OutContext);
325}
326
327const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
328 const MCSymbol *OffsetFrom) {
329 return MCBinaryExpr::createSub(
330 LHS: MCSymbolRefExpr::create(Symbol: OffsetOf, Ctx&: Asm->OutContext),
331 RHS: MCSymbolRefExpr::create(Symbol: OffsetFrom, Ctx&: Asm->OutContext), Ctx&: Asm->OutContext);
332}
333
334const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
335 const MCSymbol *OffsetFrom) {
336 return MCBinaryExpr::createAdd(LHS: getOffset(OffsetOf, OffsetFrom),
337 RHS: MCConstantExpr::create(Value: 1, Ctx&: Asm->OutContext),
338 Ctx&: Asm->OutContext);
339}
340
341int WinException::getFrameIndexOffset(int FrameIndex,
342 const WinEHFuncInfo &FuncInfo) {
343 const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
344 Register UnusedReg;
345 if (Asm->MAI.usesWindowsCFI()) {
346 StackOffset Offset =
347 TFI.getFrameIndexReferencePreferSP(MF: *Asm->MF, FI: FrameIndex, FrameReg&: UnusedReg,
348 /*IgnoreSPUpdates*/ true);
349 assert(UnusedReg ==
350 Asm->MF->getSubtarget()
351 .getTargetLowering()
352 ->getStackPointerRegisterToSaveRestore());
353 return Offset.getFixed();
354 }
355
356 // For 32-bit, offsets should be relative to the end of the EH registration
357 // node. For 64-bit, it's relative to SP at the end of the prologue.
358 assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
359 StackOffset Offset = TFI.getFrameIndexReference(MF: *Asm->MF, FI: FrameIndex, FrameReg&: UnusedReg);
360 Offset += StackOffset::getFixed(Fixed: FuncInfo.EHRegNodeEndOffset);
361 assert(!Offset.getScalable() &&
362 "Frame offsets with a scalable component are not supported");
363 return Offset.getFixed();
364}
365
366namespace {
367
368/// Top-level state used to represent unwind to caller
369const int NullState = -1;
370
371struct InvokeStateChange {
372 /// EH Label immediately after the last invoke in the previous state, or
373 /// nullptr if the previous state was the null state.
374 const MCSymbol *PreviousEndLabel;
375
376 /// EH label immediately before the first invoke in the new state, or nullptr
377 /// if the new state is the null state.
378 const MCSymbol *NewStartLabel;
379
380 /// State of the invoke following NewStartLabel, or NullState to indicate
381 /// the presence of calls which may unwind to caller.
382 int NewState;
383};
384
385/// Iterator that reports all the invoke state changes in a range of machine
386/// basic blocks. Changes to the null state are reported whenever a call that
387/// may unwind to caller is encountered. The MBB range is expected to be an
388/// entire function or funclet, and the start and end of the range are treated
389/// as being in the NullState even if there's not an unwind-to-caller call
390/// before the first invoke or after the last one (i.e., the first state change
391/// reported is the first change to something other than NullState, and a
392/// change back to NullState is always reported at the end of iteration).
393class InvokeStateChangeIterator {
394 InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
395 MachineFunction::const_iterator MFI,
396 MachineFunction::const_iterator MFE,
397 MachineBasicBlock::const_iterator MBBI,
398 int BaseState)
399 : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
400 LastStateChange.PreviousEndLabel = nullptr;
401 LastStateChange.NewStartLabel = nullptr;
402 LastStateChange.NewState = BaseState;
403 scan();
404 }
405
406public:
407 static iterator_range<InvokeStateChangeIterator>
408 range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
409 MachineFunction::const_iterator End, int BaseState = NullState) {
410 // Reject empty ranges to simplify bookkeeping by ensuring that we can get
411 // the end of the last block.
412 assert(Begin != End);
413 auto BlockBegin = Begin->begin();
414 auto BlockEnd = std::prev(x: End)->end();
415 return make_range(
416 x: InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
417 y: InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
418 }
419
420 // Iterator methods.
421 bool operator==(const InvokeStateChangeIterator &O) const {
422 assert(BaseState == O.BaseState);
423 // Must be visiting same block.
424 if (MFI != O.MFI)
425 return false;
426 // Must be visiting same isntr.
427 if (MBBI != O.MBBI)
428 return false;
429 // At end of block/instr iteration, we can still have two distinct states:
430 // one to report the final EndLabel, and another indicating the end of the
431 // state change iteration. Check for CurrentEndLabel equality to
432 // distinguish these.
433 return CurrentEndLabel == O.CurrentEndLabel;
434 }
435
436 bool operator!=(const InvokeStateChangeIterator &O) const {
437 return !operator==(O);
438 }
439 InvokeStateChange &operator*() { return LastStateChange; }
440 InvokeStateChange *operator->() { return &LastStateChange; }
441 InvokeStateChangeIterator &operator++() { return scan(); }
442
443private:
444 InvokeStateChangeIterator &scan();
445
446 const WinEHFuncInfo &EHInfo;
447 const MCSymbol *CurrentEndLabel = nullptr;
448 MachineFunction::const_iterator MFI;
449 MachineFunction::const_iterator MFE;
450 MachineBasicBlock::const_iterator MBBI;
451 InvokeStateChange LastStateChange;
452 bool VisitingInvoke = false;
453 int BaseState;
454};
455
456} // end anonymous namespace
457
458InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
459 bool IsNewBlock = false;
460 for (; MFI != MFE; ++MFI, IsNewBlock = true) {
461 if (IsNewBlock)
462 MBBI = MFI->begin();
463 for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
464 const MachineInstr &MI = *MBBI;
465 if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
466 MI.isCall() && !EHStreamer::callToNoUnwindFunction(MI: &MI)) {
467 // Indicate a change of state to the null state. We don't have
468 // start/end EH labels handy but the caller won't expect them for
469 // null state regions.
470 LastStateChange.PreviousEndLabel = CurrentEndLabel;
471 LastStateChange.NewStartLabel = nullptr;
472 LastStateChange.NewState = BaseState;
473 CurrentEndLabel = nullptr;
474 // Don't re-visit this instr on the next scan
475 ++MBBI;
476 return *this;
477 }
478
479 // All other state changes are at EH labels before/after invokes.
480 if (!MI.isEHLabel())
481 continue;
482 MCSymbol *Label = MI.getOperand(i: 0).getMCSymbol();
483 if (Label == CurrentEndLabel) {
484 VisitingInvoke = false;
485 continue;
486 }
487 auto InvokeMapIter = EHInfo.LabelToStateMap.find(Val: Label);
488 // Ignore EH labels that aren't the ones inserted before an invoke
489 if (InvokeMapIter == EHInfo.LabelToStateMap.end())
490 continue;
491 auto &StateAndEnd = InvokeMapIter->second;
492 int NewState = StateAndEnd.first;
493 // Keep track of the fact that we're between EH start/end labels so
494 // we know not to treat the inoke we'll see as unwinding to caller.
495 VisitingInvoke = true;
496 if (NewState == LastStateChange.NewState) {
497 // The state isn't actually changing here. Record the new end and
498 // keep going.
499 CurrentEndLabel = StateAndEnd.second;
500 continue;
501 }
502 // Found a state change to report
503 LastStateChange.PreviousEndLabel = CurrentEndLabel;
504 LastStateChange.NewStartLabel = Label;
505 LastStateChange.NewState = NewState;
506 // Start keeping track of the new current end
507 CurrentEndLabel = StateAndEnd.second;
508 // Don't re-visit this instr on the next scan
509 ++MBBI;
510 return *this;
511 }
512 }
513 // Iteration hit the end of the block range.
514 if (LastStateChange.NewState != BaseState) {
515 // Report the end of the last new state
516 LastStateChange.PreviousEndLabel = CurrentEndLabel;
517 LastStateChange.NewStartLabel = nullptr;
518 LastStateChange.NewState = BaseState;
519 // Leave CurrentEndLabel non-null to distinguish this state from end.
520 assert(CurrentEndLabel != nullptr);
521 return *this;
522 }
523 // We've reported all state changes and hit the end state.
524 CurrentEndLabel = nullptr;
525 return *this;
526}
527
528/// Emit the language-specific data that __C_specific_handler expects. This
529/// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
530/// up after faults with __try, __except, and __finally. The typeinfo values
531/// are not really RTTI data, but pointers to filter functions that return an
532/// integer (1, 0, or -1) indicating how to handle the exception. For __finally
533/// blocks and other cleanups, the landing pad label is zero, and the filter
534/// function is actually a cleanup handler with the same prototype. A catch-all
535/// entry is modeled with a null filter function field and a non-zero landing
536/// pad label.
537///
538/// Possible filter function return values:
539/// EXCEPTION_EXECUTE_HANDLER (1):
540/// Jump to the landing pad label after cleanups.
541/// EXCEPTION_CONTINUE_SEARCH (0):
542/// Continue searching this table or continue unwinding.
543/// EXCEPTION_CONTINUE_EXECUTION (-1):
544/// Resume execution at the trapping PC.
545///
546/// Inferred table structure:
547/// struct Table {
548/// int NumEntries;
549/// struct Entry {
550/// imagerel32 LabelStart; // Inclusive
551/// imagerel32 LabelEnd; // Exclusive
552/// imagerel32 FilterOrFinally; // One means catch-all.
553/// imagerel32 LabelLPad; // Zero means __finally.
554/// } Entries[NumEntries];
555/// };
556void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
557 auto &OS = *Asm->OutStreamer;
558 MCContext &Ctx = Asm->OutContext;
559 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
560
561 bool VerboseAsm = OS.isVerboseAsm();
562 auto AddComment = [&](const Twine &Comment) {
563 if (VerboseAsm)
564 OS.AddComment(T: Comment);
565 };
566
567 if (!isAArch64) {
568 // Emit a label assignment with the SEH frame offset so we can use it for
569 // llvm.eh.recoverfp.
570 StringRef FLinkageName =
571 GlobalValue::dropLLVMManglingEscape(Name: MF->getFunction().getName());
572 MCSymbol *ParentFrameOffset =
573 Ctx.getOrCreateParentFrameOffsetSymbol(FuncName: FLinkageName);
574 const MCExpr *MCOffset =
575 MCConstantExpr::create(Value: FuncInfo.SEHSetFrameOffset, Ctx);
576 Asm->OutStreamer->emitAssignment(Symbol: ParentFrameOffset, Value: MCOffset);
577 }
578
579 // Use the assembler to compute the number of table entries through label
580 // difference and division.
581 MCSymbol *TableBegin =
582 Ctx.createTempSymbol(Name: "lsda_begin", /*AlwaysAddSuffix=*/true);
583 MCSymbol *TableEnd =
584 Ctx.createTempSymbol(Name: "lsda_end", /*AlwaysAddSuffix=*/true);
585 const MCExpr *LabelDiff = getOffset(OffsetOf: TableEnd, OffsetFrom: TableBegin);
586 const MCExpr *EntrySize = MCConstantExpr::create(Value: 16, Ctx);
587 const MCExpr *EntryCount = MCBinaryExpr::createDiv(LHS: LabelDiff, RHS: EntrySize, Ctx);
588 AddComment("Number of call sites");
589 OS.emitValue(Value: EntryCount, Size: 4);
590
591 OS.emitLabel(Symbol: TableBegin);
592
593 // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
594 // models exceptions from invokes. LLVM also allows arbitrary reordering of
595 // the code, so our tables end up looking a bit different. Rather than
596 // trying to match MSVC's tables exactly, we emit a denormalized table. For
597 // each range of invokes in the same state, we emit table entries for all
598 // the actions that would be taken in that state. This means our tables are
599 // slightly bigger, which is OK.
600 const MCSymbol *LastStartLabel = nullptr;
601 int LastEHState = -1;
602 // Break out before we enter into a finally funclet.
603 // FIXME: We need to emit separate EH tables for cleanups.
604 MachineFunction::const_iterator End = MF->end();
605 MachineFunction::const_iterator Stop = std::next(x: MF->begin());
606 while (Stop != End && !Stop->isEHFuncletEntry())
607 ++Stop;
608 for (const auto &StateChange :
609 InvokeStateChangeIterator::range(EHInfo: FuncInfo, Begin: MF->begin(), End: Stop)) {
610 // Emit all the actions for the state we just transitioned out of
611 // if it was not the null state
612 if (LastEHState != -1)
613 emitSEHActionsForRange(FuncInfo, BeginLabel: LastStartLabel,
614 EndLabel: StateChange.PreviousEndLabel, State: LastEHState);
615 LastStartLabel = StateChange.NewStartLabel;
616 LastEHState = StateChange.NewState;
617 }
618
619 OS.emitLabel(Symbol: TableEnd);
620}
621
622void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
623 const MCSymbol *BeginLabel,
624 const MCSymbol *EndLabel, int State) {
625 auto &OS = *Asm->OutStreamer;
626 MCContext &Ctx = Asm->OutContext;
627 bool VerboseAsm = OS.isVerboseAsm();
628 auto AddComment = [&](const Twine &Comment) {
629 if (VerboseAsm)
630 OS.AddComment(T: Comment);
631 };
632
633 assert(BeginLabel && EndLabel);
634 while (State != -1) {
635 const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
636 const MCExpr *FilterOrFinally;
637 const MCExpr *ExceptOrNull;
638 auto *Handler = cast<MachineBasicBlock *>(Val: UME.Handler);
639 if (UME.IsFinally) {
640 FilterOrFinally = create32bitRef(Value: getMCSymbolForMBB(Asm, MBB: Handler));
641 ExceptOrNull = MCConstantExpr::create(Value: 0, Ctx);
642 } else {
643 // For an except, the filter can be 1 (catch-all) or a function
644 // label.
645 FilterOrFinally = UME.Filter ? create32bitRef(GV: UME.Filter)
646 : MCConstantExpr::create(Value: 1, Ctx);
647 ExceptOrNull = create32bitRef(Value: Handler->getSymbol());
648 }
649
650 AddComment("LabelStart");
651 OS.emitValue(Value: getLabel(Label: BeginLabel), Size: 4);
652 AddComment("LabelEnd");
653 OS.emitValue(Value: getLabel(Label: EndLabel), Size: 4);
654 AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
655 : "CatchAll");
656 OS.emitValue(Value: FilterOrFinally, Size: 4);
657 AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
658 OS.emitValue(Value: ExceptOrNull, Size: 4);
659
660 assert(UME.ToState < State && "states should decrease");
661 State = UME.ToState;
662 }
663}
664
665void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
666 const Function &F = MF->getFunction();
667 auto &OS = *Asm->OutStreamer;
668 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
669
670 StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(Name: F.getName());
671
672 SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
673 MCSymbol *FuncInfoXData = nullptr;
674 if (shouldEmitPersonality) {
675 // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
676 // IPs to state numbers.
677 FuncInfoXData =
678 Asm->OutContext.getOrCreateSymbol(Name: Twine("$cppxdata$", FuncLinkageName));
679 computeIP2StateTable(MF, FuncInfo, IPToStateTable);
680 } else {
681 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncName: FuncLinkageName);
682 }
683
684 int UnwindHelpOffset = 0;
685 // TODO: The check for UnwindHelpFrameIdx against max() below (and the
686 // second check further below) can be removed if MS C++ unwinding is
687 // implemented for ARM, when test/CodeGen/ARM/Windows/wineh-basic.ll
688 // passes without the check.
689 if (Asm->MAI.usesWindowsCFI() &&
690 FuncInfo.UnwindHelpFrameIdx != std::numeric_limits<int>::max())
691 UnwindHelpOffset =
692 getFrameIndexOffset(FrameIndex: FuncInfo.UnwindHelpFrameIdx, FuncInfo);
693
694 MCSymbol *UnwindMapXData = nullptr;
695 MCSymbol *TryBlockMapXData = nullptr;
696 MCSymbol *IPToStateXData = nullptr;
697 if (!FuncInfo.CxxUnwindMap.empty())
698 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
699 Name: Twine("$stateUnwindMap$", FuncLinkageName));
700 if (!FuncInfo.TryBlockMap.empty())
701 TryBlockMapXData =
702 Asm->OutContext.getOrCreateSymbol(Name: Twine("$tryMap$", FuncLinkageName));
703 if (!IPToStateTable.empty())
704 IPToStateXData =
705 Asm->OutContext.getOrCreateSymbol(Name: Twine("$ip2state$", FuncLinkageName));
706
707 bool VerboseAsm = OS.isVerboseAsm();
708 auto AddComment = [&](const Twine &Comment) {
709 if (VerboseAsm)
710 OS.AddComment(T: Comment);
711 };
712
713 // FuncInfo {
714 // uint32_t MagicNumber
715 // int32_t MaxState;
716 // UnwindMapEntry *UnwindMap;
717 // uint32_t NumTryBlocks;
718 // TryBlockMapEntry *TryBlockMap;
719 // uint32_t IPMapEntries; // always 0 for x86
720 // IPToStateMapEntry *IPToStateMap; // always 0 for x86
721 // uint32_t UnwindHelp; // non-x86 only
722 // ESTypeList *ESTypeList;
723 // int32_t EHFlags;
724 // }
725 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
726 // EHFlags & 2 -> ???
727 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
728 OS.emitValueToAlignment(Alignment: Align(4));
729 OS.emitLabel(Symbol: FuncInfoXData);
730
731 AddComment("MagicNumber");
732 OS.emitInt32(Value: 0x19930522);
733
734 AddComment("MaxState");
735 OS.emitInt32(Value: FuncInfo.CxxUnwindMap.size());
736
737 AddComment("UnwindMap");
738 OS.emitValue(Value: create32bitRef(Value: UnwindMapXData), Size: 4);
739
740 AddComment("NumTryBlocks");
741 OS.emitInt32(Value: FuncInfo.TryBlockMap.size());
742
743 AddComment("TryBlockMap");
744 OS.emitValue(Value: create32bitRef(Value: TryBlockMapXData), Size: 4);
745
746 AddComment("IPMapEntries");
747 OS.emitInt32(Value: IPToStateTable.size());
748
749 AddComment("IPToStateXData");
750 OS.emitValue(Value: create32bitRef(Value: IPToStateXData), Size: 4);
751
752 if (Asm->MAI.usesWindowsCFI() &&
753 FuncInfo.UnwindHelpFrameIdx != std::numeric_limits<int>::max()) {
754 AddComment("UnwindHelp");
755 OS.emitInt32(Value: UnwindHelpOffset);
756 }
757
758 AddComment("ESTypeList");
759 OS.emitInt32(Value: 0);
760
761 AddComment("EHFlags");
762 if (MMI->getModule()->getModuleFlag(Key: "eh-asynch")) {
763 OS.emitInt32(Value: 0);
764 } else {
765 OS.emitInt32(Value: 1);
766 }
767
768 // UnwindMapEntry {
769 // int32_t ToState;
770 // void (*Action)();
771 // };
772 if (UnwindMapXData) {
773 OS.emitLabel(Symbol: UnwindMapXData);
774 for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
775 MCSymbol *CleanupSym = getMCSymbolForMBB(
776 Asm, MBB: dyn_cast_if_present<MachineBasicBlock *>(Val: UME.Cleanup));
777 AddComment("ToState");
778 OS.emitInt32(Value: UME.ToState);
779
780 AddComment("Action");
781 OS.emitValue(Value: create32bitRef(Value: CleanupSym), Size: 4);
782 }
783 }
784
785 // TryBlockMap {
786 // int32_t TryLow;
787 // int32_t TryHigh;
788 // int32_t CatchHigh;
789 // int32_t NumCatches;
790 // HandlerType *HandlerArray;
791 // };
792 if (TryBlockMapXData) {
793 OS.emitLabel(Symbol: TryBlockMapXData);
794 SmallVector<MCSymbol *, 1> HandlerMaps;
795 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
796 const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
797
798 MCSymbol *HandlerMapXData = nullptr;
799 if (!TBME.HandlerArray.empty())
800 HandlerMapXData =
801 Asm->OutContext.getOrCreateSymbol(Name: Twine("$handlerMap$")
802 .concat(Suffix: Twine(I))
803 .concat(Suffix: "$")
804 .concat(Suffix: FuncLinkageName));
805 HandlerMaps.push_back(Elt: HandlerMapXData);
806
807 // TBMEs should form intervals.
808 assert(0 <= TBME.TryLow && "bad trymap interval");
809 assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
810 assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
811 assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
812 "bad trymap interval");
813
814 AddComment("TryLow");
815 OS.emitInt32(Value: TBME.TryLow);
816
817 AddComment("TryHigh");
818 OS.emitInt32(Value: TBME.TryHigh);
819
820 AddComment("CatchHigh");
821 OS.emitInt32(Value: TBME.CatchHigh);
822
823 AddComment("NumCatches");
824 OS.emitInt32(Value: TBME.HandlerArray.size());
825
826 AddComment("HandlerArray");
827 OS.emitValue(Value: create32bitRef(Value: HandlerMapXData), Size: 4);
828 }
829
830 // All funclets use the same parent frame offset currently.
831 unsigned ParentFrameOffset = 0;
832 if (shouldEmitPersonality) {
833 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
834 ParentFrameOffset = TFI->getWinEHParentFrameOffset(MF: *MF);
835 }
836
837 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
838 const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
839 MCSymbol *HandlerMapXData = HandlerMaps[I];
840 if (!HandlerMapXData)
841 continue;
842 // HandlerType {
843 // int32_t Adjectives;
844 // TypeDescriptor *Type;
845 // int32_t CatchObjOffset;
846 // void (*Handler)();
847 // int32_t ParentFrameOffset; // x64 and AArch64 only
848 // };
849 OS.emitLabel(Symbol: HandlerMapXData);
850 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
851 // Get the frame escape label with the offset of the catch object. If
852 // the index is INT_MAX, then there is no catch object, and we should
853 // emit an offset of zero, indicating that no copy will occur.
854 const MCExpr *FrameAllocOffsetRef = nullptr;
855 if (HT.CatchObj.FrameIndex != INT_MAX) {
856 int Offset = getFrameIndexOffset(FrameIndex: HT.CatchObj.FrameIndex, FuncInfo);
857 assert(Offset != 0 && "Illegal offset for catch object!");
858 FrameAllocOffsetRef = MCConstantExpr::create(Value: Offset, Ctx&: Asm->OutContext);
859 } else {
860 FrameAllocOffsetRef = MCConstantExpr::create(Value: 0, Ctx&: Asm->OutContext);
861 }
862
863 MCSymbol *HandlerSym = getMCSymbolForMBB(
864 Asm, MBB: dyn_cast_if_present<MachineBasicBlock *>(Val: HT.Handler));
865
866 AddComment("Adjectives");
867 OS.emitInt32(Value: HT.Adjectives);
868
869 AddComment("Type");
870 OS.emitValue(Value: create32bitRef(GV: HT.TypeDescriptor), Size: 4);
871
872 AddComment("CatchObjOffset");
873 OS.emitValue(Value: FrameAllocOffsetRef, Size: 4);
874
875 AddComment("Handler");
876 OS.emitValue(Value: create32bitRef(Value: HandlerSym), Size: 4);
877
878 if (shouldEmitPersonality) {
879 AddComment("ParentFrameOffset");
880 OS.emitInt32(Value: ParentFrameOffset);
881 }
882 }
883 }
884 }
885
886 // IPToStateMapEntry {
887 // void *IP;
888 // int32_t State;
889 // };
890 if (IPToStateXData) {
891 OS.emitLabel(Symbol: IPToStateXData);
892 for (auto &IPStatePair : IPToStateTable) {
893 AddComment("IP");
894 OS.emitValue(Value: IPStatePair.first, Size: 4);
895 AddComment("ToState");
896 OS.emitInt32(Value: IPStatePair.second);
897 }
898 }
899}
900
901void WinException::computeIP2StateTable(
902 const MachineFunction *MF, const WinEHFuncInfo &FuncInfo,
903 SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
904
905 for (MachineFunction::const_iterator FuncletStart = MF->begin(),
906 FuncletEnd = MF->begin(),
907 End = MF->end();
908 FuncletStart != End; FuncletStart = FuncletEnd) {
909 // Find the end of the funclet
910 while (++FuncletEnd != End) {
911 if (FuncletEnd->isEHFuncletEntry()) {
912 break;
913 }
914 }
915
916 // Don't emit ip2state entries for cleanup funclets. Any interesting
917 // exceptional actions in cleanups must be handled in a separate IR
918 // function.
919 if (FuncletStart->isCleanupFuncletEntry())
920 continue;
921
922 MCSymbol *StartLabel;
923 int BaseState;
924 if (FuncletStart == MF->begin()) {
925 BaseState = NullState;
926 StartLabel = Asm->getFunctionBegin();
927 } else {
928 auto *FuncletPad = cast<FuncletPadInst>(
929 Val: FuncletStart->getBasicBlock()->getFirstNonPHIIt());
930 assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
931 BaseState = FuncInfo.FuncletBaseStateMap.find(Val: FuncletPad)->second;
932 StartLabel = getMCSymbolForMBB(Asm, MBB: &*FuncletStart);
933 }
934 assert(StartLabel && "need local function start label");
935 IPToStateTable.push_back(
936 Elt: std::make_pair(x: create32bitRef(Value: StartLabel), y&: BaseState));
937
938 for (const auto &StateChange : InvokeStateChangeIterator::range(
939 EHInfo: FuncInfo, Begin: FuncletStart, End: FuncletEnd, BaseState)) {
940 // Compute the label to report as the start of this entry; use the EH
941 // start label for the invoke if we have one, otherwise (this is a call
942 // which may unwind to our caller and does not have an EH start label, so)
943 // use the previous end label.
944 const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
945 if (!ChangeLabel)
946 ChangeLabel = StateChange.PreviousEndLabel;
947 // Emit an entry indicating that PCs after 'Label' have this EH state.
948 const MCExpr *LabelExpression = getLabel(Label: ChangeLabel);
949 IPToStateTable.push_back(
950 Elt: std::make_pair(x&: LabelExpression, y: StateChange.NewState));
951 // FIXME: assert that NewState is between CatchLow and CatchHigh.
952 }
953 }
954}
955
956void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
957 StringRef FLinkageName) {
958 // Outlined helpers called by the EH runtime need to know the offset of the EH
959 // registration in order to recover the parent frame pointer. Now that we know
960 // we've code generated the parent, we can emit the label assignment that
961 // those helpers use to get the offset of the registration node.
962
963 // Compute the parent frame offset. The EHRegNodeFrameIndex will be invalid if
964 // after optimization all the invokes were eliminated. We still need to emit
965 // the parent frame offset label, but it should be garbage and should never be
966 // used.
967 int64_t Offset = 0;
968 int FI = FuncInfo.EHRegNodeFrameIndex;
969 if (FI != INT_MAX) {
970 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
971 Offset = TFI->getNonLocalFrameIndexReference(MF: *Asm->MF, FI).getFixed();
972 }
973
974 MCContext &Ctx = Asm->OutContext;
975 MCSymbol *ParentFrameOffset =
976 Ctx.getOrCreateParentFrameOffsetSymbol(FuncName: FLinkageName);
977 Asm->OutStreamer->emitAssignment(Symbol: ParentFrameOffset,
978 Value: MCConstantExpr::create(Value: Offset, Ctx));
979}
980
981/// Emit the language-specific data that _except_handler3 and 4 expect. This is
982/// functionally equivalent to the __C_specific_handler table, except it is
983/// indexed by state number instead of IP.
984void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
985 MCStreamer &OS = *Asm->OutStreamer;
986 const Function &F = MF->getFunction();
987 StringRef FLinkageName = GlobalValue::dropLLVMManglingEscape(Name: F.getName());
988
989 bool VerboseAsm = OS.isVerboseAsm();
990 auto AddComment = [&](const Twine &Comment) {
991 if (VerboseAsm)
992 OS.AddComment(T: Comment);
993 };
994
995 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
996 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
997
998 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
999 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FuncName: FLinkageName);
1000 OS.emitValueToAlignment(Alignment: Align(4));
1001 OS.emitLabel(Symbol: LSDALabel);
1002
1003 const auto *Per = cast<Function>(Val: F.getPersonalityFn()->stripPointerCasts());
1004 StringRef PerName = Per->getName();
1005 int BaseState = -1;
1006 if (PerName == "_except_handler4") {
1007 // The LSDA for _except_handler4 starts with this struct, followed by the
1008 // scope table:
1009 //
1010 // struct EH4ScopeTable {
1011 // int32_t GSCookieOffset;
1012 // int32_t GSCookieXOROffset;
1013 // int32_t EHCookieOffset;
1014 // int32_t EHCookieXOROffset;
1015 // ScopeTableEntry ScopeRecord[];
1016 // };
1017 //
1018 // Offsets are %ebp relative.
1019 //
1020 // The GS cookie is present only if the function needs stack protection.
1021 // GSCookieOffset = -2 means that GS cookie is not used.
1022 //
1023 // The EH cookie is always present.
1024 //
1025 // Check is done the following way:
1026 // (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie
1027
1028 // Retrieve the Guard Stack slot.
1029 int GSCookieOffset = -2;
1030 const MachineFrameInfo &MFI = MF->getFrameInfo();
1031 if (MFI.hasStackProtectorIndex()) {
1032 Register UnusedReg;
1033 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
1034 int SSPIdx = MFI.getStackProtectorIndex();
1035 GSCookieOffset =
1036 TFI->getFrameIndexReference(MF: *MF, FI: SSPIdx, FrameReg&: UnusedReg).getFixed();
1037 }
1038
1039 // Retrieve the EH Guard slot.
1040 // TODO(etienneb): Get rid of this value and change it for and assertion.
1041 int EHCookieOffset = 9999;
1042 if (FuncInfo.EHGuardFrameIndex != INT_MAX) {
1043 Register UnusedReg;
1044 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
1045 int EHGuardIdx = FuncInfo.EHGuardFrameIndex;
1046 EHCookieOffset =
1047 TFI->getFrameIndexReference(MF: *MF, FI: EHGuardIdx, FrameReg&: UnusedReg).getFixed();
1048 }
1049
1050 AddComment("GSCookieOffset");
1051 OS.emitInt32(Value: GSCookieOffset);
1052 AddComment("GSCookieXOROffset");
1053 OS.emitInt32(Value: 0);
1054 AddComment("EHCookieOffset");
1055 OS.emitInt32(Value: EHCookieOffset);
1056 AddComment("EHCookieXOROffset");
1057 OS.emitInt32(Value: 0);
1058 BaseState = -2;
1059 }
1060
1061 assert(!FuncInfo.SEHUnwindMap.empty());
1062 for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
1063 auto *Handler = cast<MachineBasicBlock *>(Val: UME.Handler);
1064 const MCSymbol *ExceptOrFinally =
1065 UME.IsFinally ? getMCSymbolForMBB(Asm, MBB: Handler) : Handler->getSymbol();
1066 // -1 is usually the base state for "unwind to caller", but for
1067 // _except_handler4 it's -2. Do that replacement here if necessary.
1068 int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
1069 AddComment("ToState");
1070 OS.emitInt32(Value: ToState);
1071 AddComment(UME.IsFinally ? "Null" : "FilterFunction");
1072 OS.emitValue(Value: create32bitRef(GV: UME.Filter), Size: 4);
1073 AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
1074 OS.emitValue(Value: create32bitRef(Value: ExceptOrFinally), Size: 4);
1075 }
1076}
1077
1078static int getTryRank(const WinEHFuncInfo &FuncInfo, int State) {
1079 int Rank = 0;
1080 while (State != -1) {
1081 ++Rank;
1082 State = FuncInfo.ClrEHUnwindMap[State].TryParentState;
1083 }
1084 return Rank;
1085}
1086
1087static int getTryAncestor(const WinEHFuncInfo &FuncInfo, int Left, int Right) {
1088 int LeftRank = getTryRank(FuncInfo, State: Left);
1089 int RightRank = getTryRank(FuncInfo, State: Right);
1090
1091 while (LeftRank < RightRank) {
1092 Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
1093 --RightRank;
1094 }
1095
1096 while (RightRank < LeftRank) {
1097 Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
1098 --LeftRank;
1099 }
1100
1101 while (Left != Right) {
1102 Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
1103 Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
1104 }
1105
1106 return Left;
1107}
1108
1109void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
1110 // CLR EH "states" are really just IDs that identify handlers/funclets;
1111 // states, handlers, and funclets all have 1:1 mappings between them, and a
1112 // handler/funclet's "state" is its index in the ClrEHUnwindMap.
1113 MCStreamer &OS = *Asm->OutStreamer;
1114 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
1115 MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
1116 MCSymbol *FuncEndSym = Asm->getFunctionEnd();
1117
1118 // A ClrClause describes a protected region.
1119 struct ClrClause {
1120 const MCSymbol *StartLabel; // Start of protected region
1121 const MCSymbol *EndLabel; // End of protected region
1122 int State; // Index of handler protecting the protected region
1123 int EnclosingState; // Index of funclet enclosing the protected region
1124 };
1125 SmallVector<ClrClause, 8> Clauses;
1126
1127 // Build a map from handler MBBs to their corresponding states (i.e. their
1128 // indices in the ClrEHUnwindMap).
1129 int NumStates = FuncInfo.ClrEHUnwindMap.size();
1130 assert(NumStates > 0 && "Don't need exception table!");
1131 DenseMap<const MachineBasicBlock *, int> HandlerStates;
1132 for (int State = 0; State < NumStates; ++State) {
1133 MachineBasicBlock *HandlerBlock =
1134 cast<MachineBasicBlock *>(Val: FuncInfo.ClrEHUnwindMap[State].Handler);
1135 HandlerStates[HandlerBlock] = State;
1136 // Use this loop through all handlers to verify our assumption (used in
1137 // the MinEnclosingState computation) that enclosing funclets have lower
1138 // state numbers than their enclosed funclets.
1139 assert(FuncInfo.ClrEHUnwindMap[State].HandlerParentState < State &&
1140 "ill-formed state numbering");
1141 }
1142 // Map the main function to the NullState.
1143 HandlerStates[&MF->front()] = NullState;
1144
1145 // Write out a sentinel indicating the end of the standard (Windows) xdata
1146 // and the start of the additional (CLR) info.
1147 OS.emitInt32(Value: 0xffffffff);
1148 // Write out the number of funclets
1149 OS.emitInt32(Value: NumStates);
1150
1151 // Walk the machine blocks/instrs, computing and emitting a few things:
1152 // 1. Emit a list of the offsets to each handler entry, in lexical order.
1153 // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
1154 // 3. Compute the list of ClrClauses, in the required order (inner before
1155 // outer, earlier before later; the order by which a forward scan with
1156 // early termination will find the innermost enclosing clause covering
1157 // a given address).
1158 // 4. A map (MinClauseMap) from each handler index to the index of the
1159 // outermost funclet/function which contains a try clause targeting the
1160 // key handler. This will be used to determine IsDuplicate-ness when
1161 // emitting ClrClauses. The NullState value is used to indicate that the
1162 // top-level function contains a try clause targeting the key handler.
1163 // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
1164 // try regions we entered before entering the PendingState try but which
1165 // we haven't yet exited.
1166 SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
1167 // EndSymbolMap and MinClauseMap are maps described above.
1168 std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
1169 SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
1170
1171 // Visit the root function and each funclet.
1172 for (MachineFunction::const_iterator FuncletStart = MF->begin(),
1173 FuncletEnd = MF->begin(),
1174 End = MF->end();
1175 FuncletStart != End; FuncletStart = FuncletEnd) {
1176 int FuncletState = HandlerStates[&*FuncletStart];
1177 // Find the end of the funclet
1178 MCSymbol *EndSymbol = FuncEndSym;
1179 while (++FuncletEnd != End) {
1180 if (FuncletEnd->isEHFuncletEntry()) {
1181 EndSymbol = getMCSymbolForMBB(Asm, MBB: &*FuncletEnd);
1182 break;
1183 }
1184 }
1185 // Emit the function/funclet end and, if this is a funclet (and not the
1186 // root function), record it in the EndSymbolMap.
1187 OS.emitValue(Value: getOffset(OffsetOf: EndSymbol, OffsetFrom: FuncBeginSym), Size: 4);
1188 if (FuncletState != NullState) {
1189 // Record the end of the handler.
1190 EndSymbolMap[FuncletState] = EndSymbol;
1191 }
1192
1193 // Walk the state changes in this function/funclet and compute its clauses.
1194 // Funclets always start in the null state.
1195 const MCSymbol *CurrentStartLabel = nullptr;
1196 int CurrentState = NullState;
1197 assert(HandlerStack.empty());
1198 for (const auto &StateChange :
1199 InvokeStateChangeIterator::range(EHInfo: FuncInfo, Begin: FuncletStart, End: FuncletEnd)) {
1200 // Close any try regions we're not still under
1201 int StillPendingState =
1202 getTryAncestor(FuncInfo, Left: CurrentState, Right: StateChange.NewState);
1203 while (CurrentState != StillPendingState) {
1204 assert(CurrentState != NullState &&
1205 "Failed to find still-pending state!");
1206 // Close the pending clause
1207 Clauses.push_back(Elt: {.StartLabel: CurrentStartLabel, .EndLabel: StateChange.PreviousEndLabel,
1208 .State: CurrentState, .EnclosingState: FuncletState});
1209 // Now the next-outer try region is current
1210 CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].TryParentState;
1211 // Pop the new start label from the handler stack if we've exited all
1212 // inner try regions of the corresponding try region.
1213 if (HandlerStack.back().second == CurrentState)
1214 CurrentStartLabel = HandlerStack.pop_back_val().first;
1215 }
1216
1217 if (StateChange.NewState != CurrentState) {
1218 // For each clause we're starting, update the MinClauseMap so we can
1219 // know which is the topmost funclet containing a clause targeting
1220 // it.
1221 for (int EnteredState = StateChange.NewState;
1222 EnteredState != CurrentState;
1223 EnteredState =
1224 FuncInfo.ClrEHUnwindMap[EnteredState].TryParentState) {
1225 int &MinEnclosingState = MinClauseMap[EnteredState];
1226 if (FuncletState < MinEnclosingState)
1227 MinEnclosingState = FuncletState;
1228 }
1229 // Save the previous current start/label on the stack and update to
1230 // the newly-current start/state.
1231 HandlerStack.emplace_back(Args&: CurrentStartLabel, Args&: CurrentState);
1232 CurrentStartLabel = StateChange.NewStartLabel;
1233 CurrentState = StateChange.NewState;
1234 }
1235 }
1236 assert(HandlerStack.empty());
1237 }
1238
1239 // Now emit the clause info, starting with the number of clauses.
1240 OS.emitInt32(Value: Clauses.size());
1241 for (ClrClause &Clause : Clauses) {
1242 // Emit a CORINFO_EH_CLAUSE :
1243 /*
1244 struct CORINFO_EH_CLAUSE
1245 {
1246 CORINFO_EH_CLAUSE_FLAGS Flags; // actually a CorExceptionFlag
1247 DWORD TryOffset;
1248 DWORD TryLength; // actually TryEndOffset
1249 DWORD HandlerOffset;
1250 DWORD HandlerLength; // actually HandlerEndOffset
1251 union
1252 {
1253 DWORD ClassToken; // use for catch clauses
1254 DWORD FilterOffset; // use for filter clauses
1255 };
1256 };
1257
1258 enum CORINFO_EH_CLAUSE_FLAGS
1259 {
1260 CORINFO_EH_CLAUSE_NONE = 0,
1261 CORINFO_EH_CLAUSE_FILTER = 0x0001, // This clause is for a filter
1262 CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
1263 CORINFO_EH_CLAUSE_FAULT = 0x0004, // This clause is a fault clause
1264 };
1265 typedef enum CorExceptionFlag
1266 {
1267 COR_ILEXCEPTION_CLAUSE_NONE,
1268 COR_ILEXCEPTION_CLAUSE_FILTER = 0x0001, // This is a filter clause
1269 COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
1270 COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004, // This is a fault clause
1271 COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
1272 // clause was duplicated
1273 // to a funclet which was
1274 // pulled out of line
1275 } CorExceptionFlag;
1276 */
1277 // Add 1 to the start/end of the EH clause; the IP associated with a
1278 // call when the runtime does its scan is the IP of the next instruction
1279 // (the one to which control will return after the call), so we need
1280 // to add 1 to the end of the clause to cover that offset. We also add
1281 // 1 to the start of the clause to make sure that the ranges reported
1282 // for all clauses are disjoint. Note that we'll need some additional
1283 // logic when machine traps are supported, since in that case the IP
1284 // that the runtime uses is the offset of the faulting instruction
1285 // itself; if such an instruction immediately follows a call but the
1286 // two belong to different clauses, we'll need to insert a nop between
1287 // them so the runtime can distinguish the point to which the call will
1288 // return from the point at which the fault occurs.
1289
1290 const MCExpr *ClauseBegin =
1291 getOffsetPlusOne(OffsetOf: Clause.StartLabel, OffsetFrom: FuncBeginSym);
1292 const MCExpr *ClauseEnd = getOffsetPlusOne(OffsetOf: Clause.EndLabel, OffsetFrom: FuncBeginSym);
1293
1294 const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
1295 MachineBasicBlock *HandlerBlock = cast<MachineBasicBlock *>(Val: Entry.Handler);
1296 MCSymbol *BeginSym = getMCSymbolForMBB(Asm, MBB: HandlerBlock);
1297 const MCExpr *HandlerBegin = getOffset(OffsetOf: BeginSym, OffsetFrom: FuncBeginSym);
1298 MCSymbol *EndSym = EndSymbolMap[Clause.State];
1299 const MCExpr *HandlerEnd = getOffset(OffsetOf: EndSym, OffsetFrom: FuncBeginSym);
1300
1301 uint32_t Flags = 0;
1302 switch (Entry.HandlerType) {
1303 case ClrHandlerType::Catch:
1304 // Leaving bits 0-2 clear indicates catch.
1305 break;
1306 case ClrHandlerType::Filter:
1307 Flags |= 1;
1308 break;
1309 case ClrHandlerType::Finally:
1310 Flags |= 2;
1311 break;
1312 case ClrHandlerType::Fault:
1313 Flags |= 4;
1314 break;
1315 }
1316 if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
1317 // This is a "duplicate" clause; the handler needs to be entered from a
1318 // frame above the one holding the invoke.
1319 assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
1320 Flags |= 8;
1321 }
1322 OS.emitInt32(Value: Flags);
1323
1324 // Write the clause start/end
1325 OS.emitValue(Value: ClauseBegin, Size: 4);
1326 OS.emitValue(Value: ClauseEnd, Size: 4);
1327
1328 // Write out the handler start/end
1329 OS.emitValue(Value: HandlerBegin, Size: 4);
1330 OS.emitValue(Value: HandlerEnd, Size: 4);
1331
1332 // Write out the type token or filter offset
1333 assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
1334 OS.emitInt32(Value: Entry.TypeToken);
1335 }
1336}
1337