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