LLVM 24.0.0git
EHStreamer.cpp
Go to the documentation of this file.
1//===- CodeGen/AsmPrinter/EHStreamer.cpp - Exception Directive Streamer ---===//
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 exception info into assembly files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "EHStreamer.h"
15#include "llvm/ADT/Twine.h"
21#include "llvm/IR/Function.h"
22#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCContext.h"
24#include "llvm/MC/MCStreamer.h"
25#include "llvm/MC/MCSymbol.h"
27#include "llvm/Support/LEB128.h"
29#include <algorithm>
30#include <cassert>
31#include <cstdint>
32#include <vector>
33
34using namespace llvm;
35
37
38EHStreamer::~EHStreamer() = default;
39
40/// How many leading type ids two landing pads have in common.
42 const LandingPadInfo *R) {
43 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
44 return std::mismatch(LIds.begin(), LIds.end(), RIds.begin(), RIds.end())
45 .first -
46 LIds.begin();
47}
48
49/// Compute the actions table and gather the first action index for each landing
50/// pad site.
54 SmallVectorImpl<unsigned> &FirstActions) {
55 // The action table follows the call-site table in the LSDA. The individual
56 // records are of two types:
57 //
58 // * Catch clause
59 // * Exception specification
60 //
61 // The two record kinds have the same format, with only small differences.
62 // They are distinguished by the "switch value" field: Catch clauses
63 // (TypeInfos) have strictly positive switch values, and exception
64 // specifications (FilterIds) have strictly negative switch values. Value 0
65 // indicates a catch-all clause.
66 //
67 // Negative type IDs index into FilterIds. Positive type IDs index into
68 // TypeInfos. The value written for a positive type ID is just the type ID
69 // itself. For a negative type ID, however, the value written is the
70 // (negative) byte offset of the corresponding FilterIds entry. The byte
71 // offset is usually equal to the type ID (because the FilterIds entries are
72 // written using a variable width encoding, which outputs one byte per entry
73 // as long as the value written is not too large) but can differ. This kind
74 // of complication does not occur for positive type IDs because type infos are
75 // output using a fixed width encoding. FilterOffsets[i] holds the byte
76 // offset corresponding to FilterIds[i].
77
78 const std::vector<unsigned> &FilterIds = Asm->MF->getFilterIds();
79 SmallVector<int, 16> FilterOffsets;
80 FilterOffsets.reserve(FilterIds.size());
81 int Offset = -1;
82
83 for (unsigned FilterId : FilterIds) {
84 FilterOffsets.push_back(Offset);
85 Offset -= getULEB128Size(FilterId);
86 }
87
88 FirstActions.reserve(LandingPads.size());
89
90 int FirstAction = 0;
91 unsigned SizeActions = 0; // Total size of all action entries for a function
92 const LandingPadInfo *PrevLPI = nullptr;
93
94 for (const LandingPadInfo *LPI : LandingPads) {
95 const std::vector<int> &TypeIds = LPI->TypeIds;
96 unsigned NumShared = PrevLPI ? sharedTypeIDs(LPI, PrevLPI) : 0;
97 unsigned SizeSiteActions = 0; // Total size of all entries for a landingpad
98
99 if (NumShared < TypeIds.size()) {
100 // Size of one action entry (typeid + next action)
101 unsigned SizeActionEntry = 0;
102 unsigned PrevAction = (unsigned)-1;
103
104 if (NumShared) {
105 unsigned SizePrevIds = PrevLPI->TypeIds.size();
106 assert(Actions.size());
107 PrevAction = Actions.size() - 1;
108 SizeActionEntry = getSLEB128Size(Actions[PrevAction].NextAction) +
109 getSLEB128Size(Actions[PrevAction].ValueForTypeID);
110
111 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
112 assert(PrevAction != (unsigned)-1 && "PrevAction is invalid!");
113 SizeActionEntry -= getSLEB128Size(Actions[PrevAction].ValueForTypeID);
114 SizeActionEntry += -Actions[PrevAction].NextAction;
115 PrevAction = Actions[PrevAction].Previous;
116 }
117 }
118
119 // Compute the actions.
120 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
121 int TypeID = TypeIds[J];
122 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
123 int ValueForTypeID =
124 isFilterEHSelector(TypeID) ? FilterOffsets[-1 - TypeID] : TypeID;
125 unsigned SizeTypeID = getSLEB128Size(ValueForTypeID);
126
127 int NextAction = SizeActionEntry ? -(SizeActionEntry + SizeTypeID) : 0;
128 SizeActionEntry = SizeTypeID + getSLEB128Size(NextAction);
129 SizeSiteActions += SizeActionEntry;
130
131 ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
132 Actions.push_back(Action);
133 PrevAction = Actions.size() - 1;
134 }
135
136 // Record the first action of the landing pad site.
137 FirstAction = SizeActions + SizeSiteActions - SizeActionEntry + 1;
138 } // else identical - re-use previous FirstAction
139
140 // Information used when creating the call-site table. The action record
141 // field of the call site record is the offset of the first associated
142 // action record, relative to the start of the actions table. This value is
143 // biased by 1 (1 indicating the start of the actions table), and 0
144 // indicates that there are no actions.
145 FirstActions.push_back(FirstAction);
146
147 // Compute this sites contribution to size.
148 SizeActions += SizeSiteActions;
149
150 PrevLPI = LPI;
151 }
152}
153
154/// Return `true' if this is a call to a function marked `nounwind'. Return
155/// `false' otherwise.
157 assert(MI->isCall() && "This should be a call instruction!");
158
159 bool MarkedNoUnwind = false;
160 bool SawFunc = false;
161
162 for (const MachineOperand &MO : MI->operands()) {
163 if (!MO.isGlobal()) continue;
164
165 const Function *F = dyn_cast<Function>(MO.getGlobal());
166 if (!F) continue;
167
168 if (SawFunc) {
169 // Be conservative. If we have more than one function operand for this
170 // call, then we can't make the assumption that it's the callee and
171 // not a parameter to the call.
172 //
173 // FIXME: Determine if there's a way to say that `F' is the callee or
174 // parameter.
176 break;
177 }
178
179 MarkedNoUnwind = F->doesNotThrow();
180 SawFunc = true;
181 }
182
183 return MarkedNoUnwind;
184}
185
188 RangeMapType &PadMap) {
189 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
190 // by try-range labels when lowered). Ordinary calls do not, so appropriate
191 // try-ranges for them need be deduced so we can put them in the LSDA.
192 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
193 const LandingPadInfo *LandingPad = LandingPads[i];
194 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
195 MCSymbol *BeginLabel = LandingPad->BeginLabels[j];
196 MCSymbol *EndLabel = LandingPad->EndLabels[j];
197 // If we have deleted the code for a given invoke after registering it in
198 // the LandingPad label list, the associated symbols will not have been
199 // emitted. In that case, ignore this callsite entry.
200 if (!BeginLabel->isDefined() || !EndLabel->isDefined())
201 continue;
202 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
203 PadRange P = { i, j };
204 PadMap[BeginLabel] = P;
205 }
206 }
207}
208
209/// Compute the call-site table. The entry for an invoke has a try-range
210/// containing the call, a non-zero landing pad, and an appropriate action. The
211/// entry for an ordinary call has a try-range containing the call and zero for
212/// the landing pad and the action. Calls marked 'nounwind' have no entry and
213/// must not be contained in the try-range of any entry - they form gaps in the
214/// table. Entries must be ordered by try-range address.
215///
216/// Call-sites are split into one or more call-site ranges associated with
217/// different sections of the function.
218///
219/// - Without -basic-block-sections, all call-sites are grouped into one
220/// call-site-range corresponding to the function section.
221///
222/// - With -basic-block-sections, one call-site range is created for each
223/// section, with its FragmentBeginLabel and FragmentEndLabel respectively
224// set to the beginning and ending of the corresponding section and its
225// ExceptionLabel set to the exception symbol dedicated for this section.
226// Later, one LSDA header will be emitted for each call-site range with its
227// call-sites following. The action table and type info table will be
228// shared across all ranges.
231 SmallVectorImpl<CallSiteRange> &CallSiteRanges,
233 const SmallVectorImpl<unsigned> &FirstActions) {
234 RangeMapType PadMap;
235 computePadMap(LandingPads, PadMap);
236
237 // The end label of the previous invoke or nounwind try-range.
238 MCSymbol *LastLabel = Asm->getFunctionBegin();
239
240 // Whether there is a potentially throwing instruction (currently this means
241 // an ordinary call) between the end of the previous try-range and now.
242 bool SawPotentiallyThrowing = false;
243
244 // Whether the last CallSite entry was for an invoke.
245 bool PreviousIsInvoke = false;
246
247 bool IsSJLJ = Asm->MAI.getExceptionHandlingType() == ExceptionHandling::SjLj;
248
249 // Visit all instructions in order of address.
250 for (const auto &MBB : *Asm->MF) {
251 if (&MBB == &Asm->MF->front() || MBB.isBeginSection()) {
252 // We start a call-site range upon function entry and at the beginning of
253 // every basic block section.
254 auto &Range = Asm->MBBSectionRanges[MBB.getSectionID()];
255 CallSiteRanges.push_back({Range.BeginLabel, Range.EndLabel,
256 Asm->getMBBExceptionSym(MBB),
257 CallSites.size()});
258 PreviousIsInvoke = false;
259 SawPotentiallyThrowing = false;
260 LastLabel = nullptr;
261 }
262
263 if (MBB.isEHPad())
264 CallSiteRanges.back().IsLPRange = true;
265
266 for (const auto &MI : MBB) {
267 if (!MI.isEHLabel()) {
268 if (MI.isCall())
269 SawPotentiallyThrowing |= !callToNoUnwindFunction(&MI);
270 else if (MI.isInlineAsm()) {
271 // An inline asm call may unwind iff it contains the `unwind` keyword.
272 unsigned ExtraInfo =
273 MI.getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
274 SawPotentiallyThrowing |= ExtraInfo & InlineAsm::Extra_MayUnwind;
275 }
276 continue;
277 }
278
279 // End of the previous try-range?
280 MCSymbol *BeginLabel = MI.getOperand(0).getMCSymbol();
281 if (BeginLabel == LastLabel)
282 SawPotentiallyThrowing = false;
283
284 // Beginning of a new try-range?
285 RangeMapType::const_iterator L = PadMap.find(BeginLabel);
286 if (L == PadMap.end())
287 // Nope, it was just some random label.
288 continue;
289
290 const PadRange &P = L->second;
291 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
292 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
293 "Inconsistent landing pad map!");
294
295 // For Dwarf and AIX exception handling (SjLj handling doesn't use this).
296 // If some instruction between the previous try-range and this one may
297 // throw, create a call-site entry with no landing pad for the region
298 // between the try-ranges.
299 if (SawPotentiallyThrowing &&
300 (Asm->MAI.usesCFIForEH() ||
301 Asm->MAI.getExceptionHandlingType() == ExceptionHandling::AIX)) {
302 CallSites.push_back({LastLabel, BeginLabel, nullptr, 0});
303 PreviousIsInvoke = false;
304 }
305
306 LastLabel = LandingPad->EndLabels[P.RangeIndex];
307 assert(BeginLabel && LastLabel && "Invalid landing pad!");
308
309 if (!LandingPad->LandingPadLabel) {
310 // Create a gap.
311 PreviousIsInvoke = false;
312 } else {
313 // This try-range is for an invoke.
314 CallSiteEntry Site = {
315 BeginLabel,
316 LastLabel,
317 LandingPad,
318 FirstActions[P.PadIndex]
319 };
320
321 // Try to merge with the previous call-site. SJLJ doesn't do this
322 if (PreviousIsInvoke && !IsSJLJ) {
323 CallSiteEntry &Prev = CallSites.back();
324 if (Site.LPad == Prev.LPad && Site.Action == Prev.Action) {
325 // Extend the range of the previous entry.
326 Prev.EndLabel = Site.EndLabel;
327 continue;
328 }
329 }
330
331 // Otherwise, create a new call-site.
332 if (!IsSJLJ)
333 CallSites.push_back(Site);
334 else {
335 // SjLj EH must maintain the call sites in the order assigned
336 // to them by the SjLjPrepare pass.
337 unsigned SiteNo = Asm->MF->getCallSiteBeginLabel(BeginLabel);
338 if (CallSites.size() < SiteNo)
339 CallSites.resize(SiteNo);
340 CallSites[SiteNo - 1] = Site;
341 }
342 PreviousIsInvoke = true;
343 }
344 }
345
346 // We end the call-site range upon function exit and at the end of every
347 // basic block section.
348 if (&MBB == &Asm->MF->back() || MBB.isEndSection()) {
349 // If some instruction between the previous try-range and the end of the
350 // function may throw, create a call-site entry with no landing pad for
351 // the region following the try-range.
352 if (SawPotentiallyThrowing && !IsSJLJ) {
353 CallSiteEntry Site = {LastLabel, CallSiteRanges.back().FragmentEndLabel,
354 nullptr, 0};
355 CallSites.push_back(Site);
356 SawPotentiallyThrowing = false;
357 }
358 CallSiteRanges.back().CallSiteEndIdx = CallSites.size();
359 }
360 }
361}
362
363/// Emit landing pads and actions.
364///
365/// The general organization of the table is complex, but the basic concepts are
366/// easy. First there is a header which describes the location and organization
367/// of the three components that follow.
368///
369/// 1. The landing pad site information describes the range of code covered by
370/// the try. In our case it's an accumulation of the ranges covered by the
371/// invokes in the try. There is also a reference to the landing pad that
372/// handles the exception once processed. Finally an index into the actions
373/// table.
374/// 2. The action table, in our case, is composed of pairs of type IDs and next
375/// action offset. Starting with the action index from the landing pad
376/// site, each type ID is checked for a match to the current exception. If
377/// it matches then the exception and type id are passed on to the landing
378/// pad. Otherwise the next action is looked up. This chain is terminated
379/// with a next action of zero. If no type id is found then the frame is
380/// unwound and handling continues.
381/// 3. Type ID table contains references to all the C++ typeinfo for all
382/// catches in the function. This tables is reverse indexed base 1.
383///
384/// Returns the starting symbol of an exception table.
386 const MachineFunction *MF = Asm->MF;
387 const std::vector<const GlobalValue *> &TypeInfos = MF->getTypeInfos();
388 const std::vector<unsigned> &FilterIds = MF->getFilterIds();
389 const std::vector<LandingPadInfo> &PadInfos = MF->getLandingPads();
390
391 // Sort the landing pads in order of their type ids. This is used to fold
392 // duplicate actions.
394 LandingPads.reserve(PadInfos.size());
395
396 for (const LandingPadInfo &LPI : PadInfos) {
397 // If a landing-pad has an associated label, but the label wasn't ever
398 // emitted, then skip it. (This can occur if the landingpad's MBB was
399 // deleted).
400 if (LPI.LandingPadLabel && !LPI.LandingPadLabel->isDefined())
401 continue;
402 LandingPads.push_back(&LPI);
403 }
404
405 // Order landing pads lexicographically by type id.
406 llvm::sort(LandingPads, [](const LandingPadInfo *L, const LandingPadInfo *R) {
407 return L->TypeIds < R->TypeIds;
408 });
409
410 // Compute the actions table and gather the first action index for each
411 // landing pad site.
413 SmallVector<unsigned, 64> FirstActions;
414 computeActionsTable(LandingPads, Actions, FirstActions);
415
416 // Compute the call-site table and call-site ranges. Normally, there is only
417 // one call-site-range which covers the whole function. With
418 // -basic-block-sections, there is one call-site-range per basic block
419 // section.
421 SmallVector<CallSiteRange, 4> CallSiteRanges;
422 computeCallSiteTable(CallSites, CallSiteRanges, LandingPads, FirstActions);
423
424 bool IsSJLJ = Asm->MAI.getExceptionHandlingType() == ExceptionHandling::SjLj;
425 bool IsWasm = Asm->MAI.getExceptionHandlingType() == ExceptionHandling::Wasm;
426 bool HasLEB128Directives = Asm->MAI.hasLEB128Directives();
427 unsigned CallSiteEncoding =
428 IsSJLJ ? static_cast<unsigned>(dwarf::DW_EH_PE_udata4) :
429 Asm->getObjFileLowering().getCallSiteEncoding();
430 bool HaveTTData = !TypeInfos.empty() || !FilterIds.empty();
431
432 // Type infos.
433 MCSection *LSDASection = Asm->getObjFileLowering().getSectionForLSDA(
434 MF->getFunction(), *Asm->CurrentFnSym, Asm->TM);
435 unsigned TTypeEncoding;
436
437 if (!HaveTTData) {
438 // If there is no TypeInfo, then we just explicitly say that we're omitting
439 // that bit.
440 TTypeEncoding = dwarf::DW_EH_PE_omit;
441 } else {
442 // Okay, we have actual filters or typeinfos to emit. As such, we need to
443 // pick a type encoding for them. We're about to emit a list of pointers to
444 // typeinfo objects at the end of the LSDA. However, unless we're in static
445 // mode, this reference will require a relocation by the dynamic linker.
446 //
447 // Because of this, we have a couple of options:
448 //
449 // 1) If we are in -static mode, we can always use an absolute reference
450 // from the LSDA, because the static linker will resolve it.
451 //
452 // 2) Otherwise, if the LSDA section is writable, we can output the direct
453 // reference to the typeinfo and allow the dynamic linker to relocate
454 // it. Since it is in a writable section, the dynamic linker won't
455 // have a problem.
456 //
457 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
458 // we need to use some form of indirection. For example, on Darwin,
459 // we can output a statically-relocatable reference to a dyld stub. The
460 // offset to the stub is constant, but the contents are in a section
461 // that is updated by the dynamic linker. This is easy enough, but we
462 // need to tell the personality function of the unwinder to indirect
463 // through the dyld stub.
464 //
465 // FIXME: When (3) is actually implemented, we'll have to emit the stubs
466 // somewhere. This predicate should be moved to a shared location that is
467 // in target-independent code.
468 //
469 TTypeEncoding = Asm->getObjFileLowering().getTTypeEncoding();
470 }
471
472 // Begin the exception table.
473 // Sometimes we want not to emit the data into separate section (e.g. ARM
474 // EHABI). In this case LSDASection will be NULL.
475 if (LSDASection)
476 Asm->OutStreamer->switchSection(LSDASection);
477 Asm->emitAlignment(Align(4));
478
479 // Emit the LSDA.
480 MCSymbol *GCCETSym =
481 Asm->OutContext.getOrCreateSymbol(Twine("GCC_except_table")+
482 Twine(Asm->getFunctionNumber()));
483 Asm->OutStreamer->emitLabel(GCCETSym);
484 MCSymbol *CstEndLabel = Asm->createTempSymbol(
485 CallSiteRanges.size() > 1 ? "action_table_base" : "cst_end");
486
487 MCSymbol *TTBaseLabel = nullptr;
488 if (HaveTTData)
489 TTBaseLabel = Asm->createTempSymbol("ttbase");
490
491 const bool VerboseAsm = Asm->OutStreamer->isVerboseAsm();
492
493 // Helper for emitting references (offsets) for type table and the end of the
494 // call-site table (which marks the beginning of the action table).
495 // * For Itanium, these references will be emitted for every callsite range.
496 // * For SJLJ and Wasm, they will be emitted only once in the LSDA header.
497 auto EmitTypeTableRefAndCallSiteTableEndRef = [&]() {
498 Asm->emitEncodingByte(TTypeEncoding, "@TType");
499 if (HaveTTData) {
500 // N.B.: There is a dependency loop between the size of the TTBase uleb128
501 // here and the amount of padding before the aligned type table. The
502 // assembler must sometimes pad this uleb128 or insert extra padding
503 // before the type table. See PR35809 or GNU as bug 4029.
504 MCSymbol *TTBaseRefLabel = Asm->createTempSymbol("ttbaseref");
505 Asm->emitLabelDifferenceAsULEB128(TTBaseLabel, TTBaseRefLabel);
506 Asm->OutStreamer->emitLabel(TTBaseRefLabel);
507 }
508
509 // The Action table follows the call-site table. So we emit the
510 // label difference from here (start of the call-site table for SJLJ and
511 // Wasm, and start of a call-site range for Itanium) to the end of the
512 // whole call-site table (end of the last call-site range for Itanium).
513 MCSymbol *CstBeginLabel = Asm->createTempSymbol("cst_begin");
514 Asm->emitEncodingByte(CallSiteEncoding, "Call site");
515 Asm->emitLabelDifferenceAsULEB128(CstEndLabel, CstBeginLabel);
516 Asm->OutStreamer->emitLabel(CstBeginLabel);
517 };
518
519 // An alternative path to EmitTypeTableRefAndCallSiteTableEndRef.
520 // For some platforms, the system assembler does not accept the form of
521 // `.uleb128 label2 - label1`. In those situations, we would need to calculate
522 // the size between label1 and label2 manually.
523 // In this case, we would need to calculate the LSDA size and the call
524 // site table size.
525 auto EmitTypeTableOffsetAndCallSiteTableOffset = [&]() {
526 assert(CallSiteEncoding == dwarf::DW_EH_PE_udata4 && !HasLEB128Directives &&
527 "Targets supporting .uleb128 do not need to take this path.");
528 if (CallSiteRanges.size() > 1)
530 "-fbasic-block-sections is not yet supported on "
531 "platforms that do not have general LEB128 directive support.");
532
533 uint64_t CallSiteTableSize = 0;
534 const CallSiteRange &CSRange = CallSiteRanges.back();
535 for (size_t CallSiteIdx = CSRange.CallSiteBeginIdx;
536 CallSiteIdx < CSRange.CallSiteEndIdx; ++CallSiteIdx) {
537 const CallSiteEntry &S = CallSites[CallSiteIdx];
538 // Each call site entry consists of 3 udata4 fields (12 bytes) and
539 // 1 ULEB128 field.
540 CallSiteTableSize += 12 + getULEB128Size(S.Action);
541 assert(isUInt<32>(CallSiteTableSize) && "CallSiteTableSize overflows.");
542 }
543
544 Asm->emitEncodingByte(TTypeEncoding, "@TType");
545 if (HaveTTData) {
546 const unsigned ByteSizeOfCallSiteOffset =
547 getULEB128Size(CallSiteTableSize);
548 uint64_t ActionTableSize = 0;
549 for (const ActionEntry &Action : Actions) {
550 // Each action entry consists of two SLEB128 fields.
551 ActionTableSize += getSLEB128Size(Action.ValueForTypeID) +
552 getSLEB128Size(Action.NextAction);
553 assert(isUInt<32>(ActionTableSize) && "ActionTableSize overflows.");
554 }
555
556 const unsigned TypeInfoSize =
557 Asm->GetSizeOfEncodedValue(TTypeEncoding) * MF->getTypeInfos().size();
558
559 const uint64_t LSDASizeBeforeAlign =
560 1 // Call site encoding byte.
561 + ByteSizeOfCallSiteOffset // ULEB128 encoding of CallSiteTableSize.
562 + CallSiteTableSize // Call site table content.
563 + ActionTableSize; // Action table content.
564
565 const uint64_t LSDASizeWithoutAlign = LSDASizeBeforeAlign + TypeInfoSize;
566 const unsigned ByteSizeOfLSDAWithoutAlign =
567 getULEB128Size(LSDASizeWithoutAlign);
568 const uint64_t DisplacementBeforeAlign =
569 2 // LPStartEncoding and TypeTableEncoding.
570 + ByteSizeOfLSDAWithoutAlign + LSDASizeBeforeAlign;
571
572 // The type info area starts with 4 byte alignment.
573 const unsigned NeedAlignVal = (4 - DisplacementBeforeAlign % 4) % 4;
574 uint64_t LSDASizeWithAlign = LSDASizeWithoutAlign + NeedAlignVal;
575 const unsigned ByteSizeOfLSDAWithAlign =
576 getULEB128Size(LSDASizeWithAlign);
577
578 // The LSDASizeWithAlign could use 1 byte less padding for alignment
579 // when the data we use to represent the LSDA Size "needs" to be 1 byte
580 // larger than the one previously calculated without alignment.
581 if (ByteSizeOfLSDAWithAlign > ByteSizeOfLSDAWithoutAlign)
582 LSDASizeWithAlign -= 1;
583
584 Asm->OutStreamer->emitULEB128IntValue(LSDASizeWithAlign,
585 ByteSizeOfLSDAWithAlign);
586 }
587
588 Asm->emitEncodingByte(CallSiteEncoding, "Call site");
589 Asm->OutStreamer->emitULEB128IntValue(CallSiteTableSize);
590 };
591
592 // SjLj / Wasm Exception handling
593 if (IsSJLJ || IsWasm) {
594 Asm->OutStreamer->emitLabel(Asm->getMBBExceptionSym(Asm->MF->front()));
595
596 // emit the LSDA header.
597 Asm->emitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
598 EmitTypeTableRefAndCallSiteTableEndRef();
599
600 unsigned idx = 0;
602 I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
603 const CallSiteEntry &S = *I;
604
605 // Index of the call site entry.
606 if (VerboseAsm) {
607 Asm->OutStreamer->AddComment(">> Call Site " + Twine(idx) + " <<");
608 Asm->OutStreamer->AddComment(" On exception at call site "+Twine(idx));
609 }
610 Asm->emitULEB128(idx);
611
612 // Offset of the first associated action record, relative to the start of
613 // the action table. This value is biased by 1 (1 indicates the start of
614 // the action table), and 0 indicates that there are no actions.
615 if (VerboseAsm) {
616 if (S.Action == 0)
617 Asm->OutStreamer->AddComment(" Action: cleanup");
618 else
619 Asm->OutStreamer->AddComment(" Action: " +
620 Twine((S.Action - 1) / 2 + 1));
621 }
622 Asm->emitULEB128(S.Action);
623 }
624 Asm->OutStreamer->emitLabel(CstEndLabel);
625 } else {
626 // Itanium LSDA exception handling
627
628 // The call-site table is a list of all call sites that may throw an
629 // exception (including C++ 'throw' statements) in the procedure
630 // fragment. It immediately follows the LSDA header. Each entry indicates,
631 // for a given call, the first corresponding action record and corresponding
632 // landing pad.
633 //
634 // The table begins with the number of bytes, stored as an LEB128
635 // compressed, unsigned integer. The records immediately follow the record
636 // count. They are sorted in increasing call-site address. Each record
637 // indicates:
638 //
639 // * The position of the call-site.
640 // * The position of the landing pad.
641 // * The first action record for that call site.
642 //
643 // A missing entry in the call-site table indicates that a call is not
644 // supposed to throw.
645
646 assert(CallSiteRanges.size() != 0 && "No call-site ranges!");
647
648 // There should be only one call-site range which includes all the landing
649 // pads. Find that call-site range here.
650 const CallSiteRange *LandingPadRange = nullptr;
651 for (const CallSiteRange &CSRange : CallSiteRanges) {
652 if (CSRange.IsLPRange) {
653 assert(LandingPadRange == nullptr &&
654 "All landing pads must be in a single callsite range.");
655 LandingPadRange = &CSRange;
656 }
657 }
658
659 // The call-site table is split into its call-site ranges, each being
660 // emitted as:
661 // [ LPStartEncoding | LPStart ]
662 // [ TypeTableEncoding | TypeTableOffset ]
663 // [ CallSiteEncoding | CallSiteTableEndOffset ]
664 // cst_begin -> { call-site entries contained in this range }
665 //
666 // and is followed by the next call-site range.
667 //
668 // For each call-site range, CallSiteTableEndOffset is computed as the
669 // difference between cst_begin of that range and the last call-site-table's
670 // end label. This offset is used to find the action table.
671
672 unsigned Entry = 0;
673 for (const CallSiteRange &CSRange : CallSiteRanges) {
674 if (CSRange.CallSiteBeginIdx != 0) {
675 // Align the call-site range for all ranges except the first. The
676 // first range is already aligned due to the exception table alignment.
677 Asm->emitAlignment(Align(4));
678 }
679 Asm->OutStreamer->emitLabel(CSRange.ExceptionLabel);
680
681 // Emit the LSDA header.
682 // LPStart is omitted if either we have a single call-site range (in which
683 // case the function entry is treated as @LPStart) or if this function has
684 // no landing pads (in which case @LPStart is undefined).
685 if (CallSiteRanges.size() == 1 || LandingPadRange == nullptr) {
686 Asm->emitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
687 } else if (!Asm->isPositionIndependent()) {
688 // For more than one call-site ranges, LPStart must be explicitly
689 // specified.
690 // For non-PIC we can simply use the absolute value.
691 Asm->emitEncodingByte(dwarf::DW_EH_PE_absptr, "@LPStart");
692 Asm->OutStreamer->emitSymbolValue(LandingPadRange->FragmentBeginLabel,
693 Asm->MAI.getCodePointerSize());
694 } else {
695 // For PIC mode, we Emit a PC-relative address for LPStart.
696 Asm->emitEncodingByte(dwarf::DW_EH_PE_pcrel, "@LPStart");
697 MCContext &Context = Asm->OutStreamer->getContext();
698 MCSymbol *Dot = Context.createTempSymbol();
699 Asm->OutStreamer->emitLabel(Dot);
700 Asm->OutStreamer->emitValue(
703 Context),
704 MCSymbolRefExpr::create(Dot, Context), Context),
705 Asm->MAI.getCodePointerSize());
706 }
707
708 if (HasLEB128Directives)
709 EmitTypeTableRefAndCallSiteTableEndRef();
710 else
711 EmitTypeTableOffsetAndCallSiteTableOffset();
712
713 for (size_t CallSiteIdx = CSRange.CallSiteBeginIdx;
714 CallSiteIdx != CSRange.CallSiteEndIdx; ++CallSiteIdx) {
715 const CallSiteEntry &S = CallSites[CallSiteIdx];
716
717 MCSymbol *EHFuncBeginSym = CSRange.FragmentBeginLabel;
718 MCSymbol *EHFuncEndSym = CSRange.FragmentEndLabel;
719
720 MCSymbol *BeginLabel = S.BeginLabel;
721 if (!BeginLabel)
722 BeginLabel = EHFuncBeginSym;
723 MCSymbol *EndLabel = S.EndLabel;
724 if (!EndLabel)
725 EndLabel = EHFuncEndSym;
726
727 // Offset of the call site relative to the start of the procedure.
728 if (VerboseAsm)
729 Asm->OutStreamer->AddComment(">> Call Site " + Twine(++Entry) +
730 " <<");
731 Asm->emitCallSiteOffset(BeginLabel, EHFuncBeginSym, CallSiteEncoding);
732 if (VerboseAsm)
733 Asm->OutStreamer->AddComment(Twine(" Call between ") +
734 BeginLabel->getName() + " and " +
735 EndLabel->getName());
736 Asm->emitCallSiteOffset(EndLabel, BeginLabel, CallSiteEncoding);
737
738 // Offset of the landing pad relative to the start of the landing pad
739 // fragment.
740 if (!S.LPad) {
741 if (VerboseAsm)
742 Asm->OutStreamer->AddComment(" has no landing pad");
743 Asm->emitCallSiteValue(0, CallSiteEncoding);
744 } else {
745 if (VerboseAsm)
746 Asm->OutStreamer->AddComment(Twine(" jumps to ") +
748 Asm->emitCallSiteOffset(S.LPad->LandingPadLabel,
749 LandingPadRange->FragmentBeginLabel,
750 CallSiteEncoding);
751 }
752
753 // Offset of the first associated action record, relative to the start
754 // of the action table. This value is biased by 1 (1 indicates the start
755 // of the action table), and 0 indicates that there are no actions.
756 if (VerboseAsm) {
757 if (S.Action == 0)
758 Asm->OutStreamer->AddComment(" On action: cleanup");
759 else
760 Asm->OutStreamer->AddComment(" On action: " +
761 Twine((S.Action - 1) / 2 + 1));
762 }
763 Asm->emitULEB128(S.Action);
764 }
765 }
766 Asm->OutStreamer->emitLabel(CstEndLabel);
767 }
768
769 // Emit the Action Table.
770 int Entry = 0;
771 for (const ActionEntry &Action : Actions) {
772 if (VerboseAsm) {
773 // Emit comments that decode the action table.
774 Asm->OutStreamer->AddComment(">> Action Record " + Twine(++Entry) + " <<");
775 }
776
777 // Type Filter
778 //
779 // Used by the runtime to match the type of the thrown exception to the
780 // type of the catch clauses or the types in the exception specification.
781 if (VerboseAsm) {
782 if (Action.ValueForTypeID > 0)
783 Asm->OutStreamer->AddComment(" Catch TypeInfo " +
784 Twine(Action.ValueForTypeID));
785 else if (Action.ValueForTypeID < 0)
786 Asm->OutStreamer->AddComment(" Filter TypeInfo " +
787 Twine(Action.ValueForTypeID));
788 else
789 Asm->OutStreamer->AddComment(" Cleanup");
790 }
791 Asm->emitSLEB128(Action.ValueForTypeID);
792
793 // Action Record
794 if (VerboseAsm) {
795 if (Action.Previous == unsigned(-1)) {
796 Asm->OutStreamer->AddComment(" No further actions");
797 } else {
798 Asm->OutStreamer->AddComment(" Continue to action " +
799 Twine(Action.Previous + 1));
800 }
801 }
802 Asm->emitSLEB128(Action.NextAction);
803 }
804
805 if (HaveTTData) {
806 Asm->emitAlignment(Align(4));
807 emitTypeInfos(TTypeEncoding, TTBaseLabel);
808 }
809
810 Asm->emitAlignment(Align(4));
811 return GCCETSym;
812}
813
814void EHStreamer::emitTypeInfos(unsigned TTypeEncoding, MCSymbol *TTBaseLabel) {
815 const MachineFunction *MF = Asm->MF;
816 const std::vector<const GlobalValue *> &TypeInfos = MF->getTypeInfos();
817 const std::vector<unsigned> &FilterIds = MF->getFilterIds();
818
819 const bool VerboseAsm = Asm->OutStreamer->isVerboseAsm();
820
821 int Entry = 0;
822 // Emit the Catch TypeInfos.
823 if (VerboseAsm && !TypeInfos.empty()) {
824 Asm->OutStreamer->AddComment(">> Catch TypeInfos <<");
825 Asm->OutStreamer->addBlankLine();
826 Entry = TypeInfos.size();
827 }
828
829 for (const GlobalValue *GV : llvm::reverse(TypeInfos)) {
830 if (VerboseAsm)
831 Asm->OutStreamer->AddComment("TypeInfo " + Twine(Entry--));
832 Asm->emitTTypeReference(GV, TTypeEncoding);
833 }
834
835 Asm->OutStreamer->emitLabel(TTBaseLabel);
836
837 // Emit the Exception Specifications.
838 if (VerboseAsm && !FilterIds.empty()) {
839 Asm->OutStreamer->AddComment(">> Filter TypeInfos <<");
840 Asm->OutStreamer->addBlankLine();
841 Entry = 0;
842 }
843 for (std::vector<unsigned>::const_iterator
844 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
845 unsigned TypeID = *I;
846 if (VerboseAsm) {
847 --Entry;
848 if (isFilterEHSelector(TypeID))
849 Asm->OutStreamer->AddComment("FilterInfo " + Twine(Entry));
850 }
851
852 Asm->emitULEB128(TypeID);
853 }
854}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file contains constants used for implementing Dwarf debug support.
SawFunc
MarkedNoUnwind
Return ‘true’ if this is a call to a function marked ‘nounwind’.
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
This file defines the SmallVector class.
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:95
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:763
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:767
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:680
iterator end()
Definition DenseMap.h:687
virtual void emitTypeInfos(unsigned TTypeEncoding, MCSymbol *TTBaseLabel)
void computeActionsTable(const SmallVectorImpl< const LandingPadInfo * > &LandingPads, SmallVectorImpl< ActionEntry > &Actions, SmallVectorImpl< unsigned > &FirstActions)
Compute the actions table and gather the first action index for each landing pad site.
static bool callToNoUnwindFunction(const MachineInstr *MI)
Return ‘true’ if this is a call to a function marked ‘nounwind’.
void computePadMap(const SmallVectorImpl< const LandingPadInfo * > &LandingPads, RangeMapType &PadMap)
AsmPrinter * Asm
Target of directive emission.
Definition EHStreamer.h:33
MCSymbol * emitExceptionTable()
Emit landing pads and actions.
virtual void computeCallSiteTable(SmallVectorImpl< CallSiteEntry > &CallSites, SmallVectorImpl< CallSiteRange > &CallSiteRanges, const SmallVectorImpl< const LandingPadInfo * > &LandingPads, const SmallVectorImpl< unsigned > &FirstActions)
Compute the call-site table and the call-site ranges.
static bool isFilterEHSelector(int Selector)
Definition EHStreamer.h:145
~EHStreamer() override
static unsigned sharedTypeIDs(const LandingPadInfo *L, const LandingPadInfo *R)
How many leading type ids two landing pads have in common.
DenseMap< MCSymbol *, PadRange > RangeMapType
Definition EHStreamer.h:51
MachineModuleInfo * MMI
Collected machine module information.
Definition EHStreamer.h:36
EHStreamer(AsmPrinter *A)
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:427
Context object for machine code objects.
Definition MCContext.h:83
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition MCSection.h:580
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
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition MCSymbol.h:233
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
const std::vector< unsigned > & getFilterIds() const
Return a reference to the typeids encoding filters used in the current function.
const std::vector< const GlobalValue * > & getTypeInfos() const
Return a reference to the C++ typeinfo for the current function.
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.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
typename SuperClass::const_iterator const_iterator
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
@ DW_EH_PE_pcrel
Definition Dwarf.h:977
@ DW_EH_PE_absptr
Definition Dwarf.h:966
@ DW_EH_PE_udata4
Definition Dwarf.h:970
@ DW_EH_PE_omit
Definition Dwarf.h:967
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
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
LLVM_ABI unsigned getULEB128Size(uint64_t Value)
Utility function to get the size of the ULEB128-encoded value.
Definition LEB128.cpp:19
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:58
@ AIX
AIX Exception Handling.
Definition CodeGen.h:63
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:61
LLVM_ABI unsigned getSLEB128Size(int64_t Value)
Utility function to get the size of the SLEB128-encoded value.
Definition LEB128.cpp:29
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Structure describing an entry in the actions table.
Definition EHStreamer.h:54
Structure describing an entry in the call-site table.
Definition EHStreamer.h:61
const LandingPadInfo * LPad
Definition EHStreamer.h:67
Structure describing a contiguous range of call-sites which reside in the same procedure fragment.
Definition EHStreamer.h:76
Structure holding a try-range and the associated landing pad.
Definition EHStreamer.h:43
This structure is used to retain landing pad info for the current function.
SmallVector< MCSymbol *, 1 > EndLabels
SmallVector< MCSymbol *, 1 > BeginLabels
std::vector< int > TypeIds