LLVM 23.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 isThumb = Asm->TM.getTargetTriple().isThumb();
42}
43
45
46/// endModule - Emit all exception information that should come after the
47/// content.
49 auto &OS = *Asm->OutStreamer;
50 const Module *M = MMI->getModule();
51 for (const Function &F : *M)
52 if (F.hasFnAttribute("safeseh"))
53 OS.emitCOFFSafeSEH(Asm->getSymbol(&F));
54
55 if (M->getModuleFlag("ehcontguard") && !EHContTargets.empty()) {
56 // Emit the symbol index of each ehcont target.
57 OS.switchSection(Asm->OutContext.getObjectFileInfo()->getGEHContSection());
58 for (const MCSymbol *S : EHContTargets) {
59 OS.emitCOFFSymbolIndex(S);
60 }
61 }
62}
63
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
79 const Function *PerFn = nullptr;
80 if (F.hasPersonalityFn()) {
81 PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
82 Per = classifyEHPersonality(PerFn);
83 }
84
85 bool forceEmitPersonality = F.hasPersonalityFn() &&
86 !isNoOpWithoutInvoke(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 =
107 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
108 }
109 shouldEmitLSDA = hasEHFunclets;
110 shouldEmitPersonality = false;
111 return;
112 }
113
114 beginFunclet(MF->front(), Asm->CurrentFnSym);
115}
116
118 if (isAArch64 && CurrentFuncletEntry &&
119 (shouldEmitMoves || shouldEmitPersonality))
120 Asm->OutStreamer->emitWinCFIFuncletOrFuncEnd();
121}
122
123/// endFunction - Gather and emit post-function exception information.
124///
126 if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
127 return;
128
129 const Function &F = MF->getFunction();
131 if (F.hasPersonalityFn())
132 Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
133
134 endFuncletImpl();
135
136 // endFunclet will emit the necessary .xdata tables for table-based SEH.
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 Asm->OutStreamer->getCurrentSectionOnly());
146 Asm->OutStreamer->switchSection(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.
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
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(EHContTargets, MF->getEHContTargets());
167 }
168}
169
170/// Retrieve the MCSymbol for a GlobalValue or MachineBasicBlock.
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(F.getName());
183 MCContext &Ctx = MF->getContext();
184 StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
185 return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
186 Twine(MBB->getNumber()) + "@?0?" +
187 FuncLinkageName + "@4HA");
188}
189
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);
198
199 // Describe our funclet symbol as a function with internal linkage.
200 Asm->OutStreamer->beginCOFFSymbolDef(Sym);
201 Asm->OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
202 Asm->OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
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 std::max(Asm->MF->getPreferredAlignment(), MBB.getAlignment()), &F);
210
211 // Now that we've emitted the alignment directive, point at our funclet.
212 Asm->OutStreamer->emitLabel(Sym);
213 }
214
215 // Mark 'Sym' as starting our funclet.
216 if (shouldEmitMoves || shouldEmitPersonality) {
217 CurrentFuncletTextSection = Asm->OutStreamer->getCurrentSectionOnly();
218 Asm->OutStreamer->emitWinCFIStartProc(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>(F.getPersonalityFn()->stripPointerCasts());
228 const MCSymbol *PersHandlerSym =
229 TLOF.getCFIPersonalitySymbol(PerFn, 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(PersHandlerSym, true, true);
238 }
239}
240
242 if (isAArch64 && CurrentFuncletEntry &&
243 (shouldEmitMoves || shouldEmitPersonality)) {
244 Asm->OutStreamer->switchSection(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();
259 if (F.hasPersonalityFn())
260 Per = classifyEHPersonality(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(F.getName());
270 MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
271 Twine("$cppxdata$", FuncLinkageName));
272 Asm->OutStreamer->emitValue(create32bitRef(FuncInfoXData), 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(EHContTargets, 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(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(0, Asm->OutContext);
312 auto Spec = useImageRel32 ? uint16_t(MCSymbolRefExpr::VK_COFF_IMGREL32) : 0;
313 return MCSymbolRefExpr::create(Value, Spec, Asm->OutContext);
314}
315
316const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
317 if (!GV)
318 return MCConstantExpr::create(0, Asm->OutContext);
319 return create32bitRef(Asm->getSymbol(GV));
320}
321
322const MCExpr *WinException::getLabel(const MCSymbol *Label) {
324 Asm->OutContext);
325}
326
327const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
328 const MCSymbol *OffsetFrom) {
330 MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
331 MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
332}
333
334const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
335 const MCSymbol *OffsetFrom) {
336 return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
337 MCConstantExpr::create(1, Asm->OutContext),
338 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(*Asm->MF, FrameIndex, 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(*Asm->MF, FrameIndex, UnusedReg);
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,
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:
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(End)->end();
415 return make_range(
416 InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
417 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;
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 &&
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(0).getMCSymbol();
483 if (Label == CurrentEndLabel) {
484 VisitingInvoke = false;
485 continue;
486 }
487 auto InvokeMapIter = EHInfo.LabelToStateMap.find(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(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 =
572 MCSymbol *ParentFrameOffset =
573 Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
574 const MCExpr *MCOffset =
576 Asm->OutStreamer->emitAssignment(ParentFrameOffset, 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("lsda_begin", /*AlwaysAddSuffix=*/true);
583 MCSymbol *TableEnd =
584 Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
585 const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
586 const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
587 const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
588 AddComment("Number of call sites");
589 OS.emitValue(EntryCount, 4);
590
591 OS.emitLabel(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.
605 MachineFunction::const_iterator Stop = std::next(MF->begin());
606 while (Stop != End && !Stop->isEHFuncletEntry())
607 ++Stop;
608 for (const auto &StateChange :
609 InvokeStateChangeIterator::range(FuncInfo, MF->begin(), 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, LastStartLabel,
614 StateChange.PreviousEndLabel, LastEHState);
615 LastStartLabel = StateChange.NewStartLabel;
616 LastEHState = StateChange.NewState;
617 }
618
619 OS.emitLabel(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(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 *>(UME.Handler);
639 if (UME.IsFinally) {
640 FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
641 ExceptOrNull = MCConstantExpr::create(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(UME.Filter)
646 : MCConstantExpr::create(1, Ctx);
647 ExceptOrNull = create32bitRef(Handler->getSymbol());
648 }
649
650 AddComment("LabelStart");
651 OS.emitValue(getLabel(BeginLabel), 4);
652 AddComment("LabelEnd");
653 OS.emitValue(getLabel(EndLabel), 4);
654 AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
655 : "CatchAll");
656 OS.emitValue(FilterOrFinally, 4);
657 AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
658 OS.emitValue(ExceptOrNull, 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(F.getName());
671
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(Twine("$cppxdata$", FuncLinkageName));
679 computeIP2StateTable(MF, FuncInfo, IPToStateTable);
680 } else {
681 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(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(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 Twine("$stateUnwindMap$", FuncLinkageName));
700 if (!FuncInfo.TryBlockMap.empty())
701 TryBlockMapXData =
702 Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
703 if (!IPToStateTable.empty())
704 IPToStateXData =
705 Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
706
707 bool VerboseAsm = OS.isVerboseAsm();
708 auto AddComment = [&](const Twine &Comment) {
709 if (VerboseAsm)
710 OS.AddComment(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(Align(4));
729 OS.emitLabel(FuncInfoXData);
730
731 AddComment("MagicNumber");
732 OS.emitInt32(0x19930522);
733
734 AddComment("MaxState");
735 OS.emitInt32(FuncInfo.CxxUnwindMap.size());
736
737 AddComment("UnwindMap");
738 OS.emitValue(create32bitRef(UnwindMapXData), 4);
739
740 AddComment("NumTryBlocks");
741 OS.emitInt32(FuncInfo.TryBlockMap.size());
742
743 AddComment("TryBlockMap");
744 OS.emitValue(create32bitRef(TryBlockMapXData), 4);
745
746 AddComment("IPMapEntries");
747 OS.emitInt32(IPToStateTable.size());
748
749 AddComment("IPToStateXData");
750 OS.emitValue(create32bitRef(IPToStateXData), 4);
751
752 if (Asm->MAI.usesWindowsCFI() &&
753 FuncInfo.UnwindHelpFrameIdx != std::numeric_limits<int>::max()) {
754 AddComment("UnwindHelp");
755 OS.emitInt32(UnwindHelpOffset);
756 }
757
758 AddComment("ESTypeList");
759 OS.emitInt32(0);
760
761 AddComment("EHFlags");
762 if (MMI->getModule()->getModuleFlag("eh-asynch")) {
763 OS.emitInt32(0);
764 } else {
765 OS.emitInt32(1);
766 }
767
768 // UnwindMapEntry {
769 // int32_t ToState;
770 // void (*Action)();
771 // };
772 if (UnwindMapXData) {
773 OS.emitLabel(UnwindMapXData);
774 for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
775 MCSymbol *CleanupSym = getMCSymbolForMBB(
777 AddComment("ToState");
778 OS.emitInt32(UME.ToState);
779
780 AddComment("Action");
781 OS.emitValue(create32bitRef(CleanupSym), 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(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(Twine("$handlerMap$")
802 .concat(Twine(I))
803 .concat("$")
804 .concat(FuncLinkageName));
805 HandlerMaps.push_back(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(TBME.TryLow);
816
817 AddComment("TryHigh");
818 OS.emitInt32(TBME.TryHigh);
819
820 AddComment("CatchHigh");
821 OS.emitInt32(TBME.CatchHigh);
822
823 AddComment("NumCatches");
824 OS.emitInt32(TBME.HandlerArray.size());
825
826 AddComment("HandlerArray");
827 OS.emitValue(create32bitRef(HandlerMapXData), 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);
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(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(HT.CatchObj.FrameIndex, FuncInfo);
857 assert(Offset != 0 && "Illegal offset for catch object!");
858 FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
859 } else {
860 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
861 }
862
863 MCSymbol *HandlerSym = getMCSymbolForMBB(
865
866 AddComment("Adjectives");
867 OS.emitInt32(HT.Adjectives);
868
869 AddComment("Type");
870 OS.emitValue(create32bitRef(HT.TypeDescriptor), 4);
871
872 AddComment("CatchObjOffset");
873 OS.emitValue(FrameAllocOffsetRef, 4);
874
875 AddComment("Handler");
876 OS.emitValue(create32bitRef(HandlerSym), 4);
877
878 if (shouldEmitPersonality) {
879 AddComment("ParentFrameOffset");
880 OS.emitInt32(ParentFrameOffset);
881 }
882 }
883 }
884 }
885
886 // IPToStateMapEntry {
887 // void *IP;
888 // int32_t State;
889 // };
890 if (IPToStateXData) {
891 OS.emitLabel(IPToStateXData);
892 for (auto &IPStatePair : IPToStateTable) {
893 AddComment("IP");
894 OS.emitValue(IPStatePair.first, 4);
895 AddComment("ToState");
896 OS.emitInt32(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 FuncletStart->getBasicBlock()->getFirstNonPHIIt());
930 assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
931 BaseState = FuncInfo.FuncletBaseStateMap.find(FuncletPad)->second;
932 StartLabel = getMCSymbolForMBB(Asm, &*FuncletStart);
933 }
934 assert(StartLabel && "need local function start label");
935 IPToStateTable.push_back(
936 std::make_pair(create32bitRef(StartLabel), BaseState));
937
938 for (const auto &StateChange : InvokeStateChangeIterator::range(
939 FuncInfo, FuncletStart, 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(ChangeLabel);
949 IPToStateTable.push_back(
950 std::make_pair(LabelExpression, 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();
972 }
973
974 MCContext &Ctx = Asm->OutContext;
975 MCSymbol *ParentFrameOffset =
976 Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
977 Asm->OutStreamer->emitAssignment(ParentFrameOffset,
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(F.getName());
988
989 bool VerboseAsm = OS.isVerboseAsm();
990 auto AddComment = [&](const Twine &Comment) {
991 if (VerboseAsm)
992 OS.AddComment(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(FLinkageName);
1001 OS.emitLabel(LSDALabel);
1002
1003 const auto *Per = cast<Function>(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, SSPIdx, 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, EHGuardIdx, UnusedReg).getFixed();
1048 }
1049
1050 AddComment("GSCookieOffset");
1051 OS.emitInt32(GSCookieOffset);
1052 AddComment("GSCookieXOROffset");
1053 OS.emitInt32(0);
1054 AddComment("EHCookieOffset");
1055 OS.emitInt32(EHCookieOffset);
1056 AddComment("EHCookieXOROffset");
1057 OS.emitInt32(0);
1058 BaseState = -2;
1059 }
1060
1061 assert(!FuncInfo.SEHUnwindMap.empty());
1062 for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
1063 auto *Handler = cast<MachineBasicBlock *>(UME.Handler);
1064 const MCSymbol *ExceptOrFinally =
1065 UME.IsFinally ? getMCSymbolForMBB(Asm, 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(ToState);
1071 AddComment(UME.IsFinally ? "Null" : "FilterFunction");
1072 OS.emitValue(create32bitRef(UME.Filter), 4);
1073 AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
1074 OS.emitValue(create32bitRef(ExceptOrFinally), 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, Left);
1089 int RightRank = getTryRank(FuncInfo, 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 };
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 *>(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(0xffffffff);
1148 // Write out the number of funclets
1149 OS.emitInt32(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.
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, &*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(getOffset(EndSymbol, FuncBeginSym), 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(FuncInfo, FuncletStart, FuncletEnd)) {
1200 // Close any try regions we're not still under
1201 int StillPendingState =
1202 getTryAncestor(FuncInfo, CurrentState, 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({CurrentStartLabel, StateChange.PreviousEndLabel,
1208 CurrentState, 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(CurrentStartLabel, 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(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(Clause.StartLabel, FuncBeginSym);
1292 const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
1293
1294 const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
1295 MachineBasicBlock *HandlerBlock = cast<MachineBasicBlock *>(Entry.Handler);
1296 MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
1297 const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
1298 MCSymbol *EndSym = EndSymbolMap[Clause.State];
1299 const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
1300
1301 uint32_t Flags = 0;
1302 switch (Entry.HandlerType) {
1304 // Leaving bits 0-2 clear indicates catch.
1305 break;
1307 Flags |= 1;
1308 break;
1310 Flags |= 2;
1311 break;
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(Flags);
1323
1324 // Write the clause start/end
1325 OS.emitValue(ClauseBegin, 4);
1326 OS.emitValue(ClauseEnd, 4);
1327
1328 // Write out the handler start/end
1329 OS.emitValue(HandlerBegin, 4);
1330 OS.emitValue(HandlerEnd, 4);
1331
1332 // Write out the type token or filter offset
1333 assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
1334 OS.emitInt32(Entry.TypeToken);
1335 }
1336}
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:91
MachineFunction * MF
The current machine function.
Definition AsmPrinter.h:109
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition AsmPrinter.h:101
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition AsmPrinter.h:106
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:343
static const MCBinaryExpr * createDiv(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:353
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:428
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:83
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:573
virtual bool isVerboseAsm() const
Return true if this streamer supports verbose assembly and if it is enabled.
Definition MCStreamer.h:371
virtual void AddComment(const Twine &T, bool EOL=true)
Add a textual comment.
Definition MCStreamer.h:394
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:757
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:214
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
Function & getFunction()
Return the LLVM function that this machine code represents.
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:67
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:46
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:39
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:318
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:869
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
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:2264
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2142
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:2207
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:1151
bool isNoOpWithoutInvoke(EHPersonality Pers)
Return true if this personality may be safely removed if there are no invoke instructions remaining i...
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
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