1 //===-- CodeGen/AsmPrinter/DwarfException.cpp - Dwarf Exception Impl ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing DWARF exception info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfException.h"
15 #include "llvm/Module.h"
16 #include "llvm/CodeGen/AsmPrinter.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineLocation.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Target/Mangler.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetFrameInfo.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Support/Dwarf.h"
35 #include "llvm/Support/FormattedStream.h"
36 #include "llvm/Support/Timer.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/Twine.h"
42 DwarfException::DwarfException(AsmPrinter *A)
43 : Asm(A), MMI(Asm->MMI), shouldEmitTable(false), shouldEmitMoves(false),
44 shouldEmitTableModule(false), shouldEmitMovesModule(false),
46 if (TimePassesIsEnabled)
47 ExceptionTimer = new Timer("DWARF Exception Writer");
50 DwarfException::~DwarfException() {
51 delete ExceptionTimer;
54 /// EmitCIE - Emit a Common Information Entry (CIE). This holds information that
55 /// is shared among many Frame Description Entries. There is at least one CIE
56 /// in every non-empty .debug_frame section.
57 void DwarfException::EmitCIE(const Function *PersonalityFn, unsigned Index) {
58 // Size and sign of stack growth.
59 int stackGrowth = Asm->getTargetData().getPointerSize();
60 if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
61 TargetFrameInfo::StackGrowsDown)
64 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
66 // Begin eh frame section.
67 Asm->OutStreamer.SwitchSection(TLOF.getEHFrameSection());
70 if (TLOF.isFunctionEHFrameSymbolPrivate())
71 EHFrameSym = Asm->GetTempSymbol("EH_frame", Index);
73 EHFrameSym = Asm->OutContext.GetOrCreateSymbol(Twine("EH_frame") +
75 Asm->OutStreamer.EmitLabel(EHFrameSym);
77 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_eh_frame", Index));
79 // Define base labels.
80 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_frame_common", Index));
82 // Define the eh frame length.
83 Asm->OutStreamer.AddComment("Length of Common Information Entry");
84 Asm->EmitLabelDifference(Asm->GetTempSymbol("eh_frame_common_end", Index),
85 Asm->GetTempSymbol("eh_frame_common_begin", Index),
89 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_frame_common_begin",Index));
90 Asm->OutStreamer.AddComment("CIE Identifier Tag");
91 Asm->OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
92 Asm->OutStreamer.AddComment("DW_CIE_VERSION");
93 Asm->OutStreamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1/*size*/, 0/*addr*/);
95 // The personality presence indicates that language specific information will
96 // show up in the eh frame. Find out how we are supposed to lower the
97 // personality function reference:
99 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
100 unsigned FDEEncoding = TLOF.getFDEEncoding();
101 unsigned PerEncoding = TLOF.getPersonalityEncoding();
103 char Augmentation[6] = { 0 };
104 unsigned AugmentationSize = 0;
105 char *APtr = Augmentation + 1;
108 // There is a personality function.
110 AugmentationSize += 1 + Asm->GetSizeOfEncodedValue(PerEncoding);
113 if (UsesLSDA[Index]) {
114 // An LSDA pointer is in the FDE augmentation.
119 if (FDEEncoding != dwarf::DW_EH_PE_absptr) {
120 // A non-default pointer encoding for the FDE.
125 if (APtr != Augmentation + 1)
126 Augmentation[0] = 'z';
128 Asm->OutStreamer.AddComment("CIE Augmentation");
129 Asm->OutStreamer.EmitBytes(StringRef(Augmentation, strlen(Augmentation)+1),0);
132 Asm->EmitULEB128(1, "CIE Code Alignment Factor");
133 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
134 Asm->OutStreamer.AddComment("CIE Return Address Column");
136 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
137 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
139 if (Augmentation[0]) {
140 Asm->EmitULEB128(AugmentationSize, "Augmentation Size");
142 // If there is a personality, we need to indicate the function's location.
144 Asm->EmitEncodingByte(PerEncoding, "Personality");
145 Asm->OutStreamer.AddComment("Personality");
146 Asm->EmitReference(PersonalityFn, PerEncoding);
149 Asm->EmitEncodingByte(LSDAEncoding, "LSDA");
150 if (FDEEncoding != dwarf::DW_EH_PE_absptr)
151 Asm->EmitEncodingByte(FDEEncoding, "FDE");
154 // Indicate locations of general callee saved registers in frame.
155 std::vector<MachineMove> Moves;
156 RI->getInitialFrameState(Moves);
157 Asm->EmitFrameMoves(Moves, 0, true);
159 // On Darwin the linker honors the alignment of eh_frame, which means it must
160 // be 8-byte on 64-bit targets to match what gcc does. Otherwise you get
161 // holes which confuse readers of eh_frame.
162 Asm->EmitAlignment(Asm->getTargetData().getPointerSize() == 4 ? 2 : 3,
164 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_frame_common_end", Index));
167 /// EmitFDE - Emit the Frame Description Entry (FDE) for the function.
168 void DwarfException::EmitFDE(const FunctionEHFrameInfo &EHFrameInfo) {
169 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
170 "Should not emit 'available externally' functions at all");
172 const Function *TheFunc = EHFrameInfo.function;
173 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
175 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
176 unsigned FDEEncoding = TLOF.getFDEEncoding();
178 Asm->OutStreamer.SwitchSection(TLOF.getEHFrameSection());
180 // Externally visible entry into the functions eh frame info. If the
181 // corresponding function is static, this should not be externally visible.
182 if (!TheFunc->hasLocalLinkage() && TLOF.isFunctionEHSymbolGlobal())
183 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,MCSA_Global);
185 // If corresponding function is weak definition, this should be too.
186 if (TheFunc->isWeakForLinker() && Asm->MAI->getWeakDefDirective())
187 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
188 MCSA_WeakDefinition);
190 // If corresponding function is hidden, this should be too.
191 if (TheFunc->hasHiddenVisibility())
192 if (MCSymbolAttr HiddenAttr = Asm->MAI->getHiddenVisibilityAttr())
193 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
196 // If there are no calls then you can't unwind. This may mean we can omit the
197 // EH Frame, but some environments do not handle weak absolute symbols. If
198 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
199 // info is to be available for non-EH uses.
200 if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
201 (!TheFunc->isWeakForLinker() ||
202 !Asm->MAI->getWeakDefDirective() ||
203 TLOF.getSupportsWeakOmittedEHFrame())) {
204 Asm->OutStreamer.EmitAssignment(EHFrameInfo.FunctionEHSym,
205 MCConstantExpr::Create(0, Asm->OutContext));
206 // This name has no connection to the function, so it might get
207 // dead-stripped when the function is not, erroneously. Prohibit
208 // dead-stripping unconditionally.
209 if (Asm->MAI->hasNoDeadStrip())
210 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
213 Asm->OutStreamer.EmitLabel(EHFrameInfo.FunctionEHSym);
216 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
217 Asm->EmitLabelDifference(
218 Asm->GetTempSymbol("eh_frame_end", EHFrameInfo.Number),
219 Asm->GetTempSymbol("eh_frame_begin", EHFrameInfo.Number), 4);
221 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_frame_begin",
222 EHFrameInfo.Number));
224 Asm->OutStreamer.AddComment("FDE CIE offset");
225 Asm->EmitLabelDifference(
226 Asm->GetTempSymbol("eh_frame_begin", EHFrameInfo.Number),
227 Asm->GetTempSymbol("eh_frame_common",
228 EHFrameInfo.PersonalityIndex), 4);
230 MCSymbol *EHFuncBeginSym =
231 Asm->GetTempSymbol("eh_func_begin", EHFrameInfo.Number);
233 Asm->OutStreamer.AddComment("FDE initial location");
234 Asm->EmitReference(EHFuncBeginSym, FDEEncoding);
236 Asm->OutStreamer.AddComment("FDE address range");
237 Asm->EmitLabelDifference(Asm->GetTempSymbol("eh_func_end",
240 Asm->GetSizeOfEncodedValue(FDEEncoding));
242 // If there is a personality and landing pads then point to the language
243 // specific data area in the exception table.
244 if (MMI->getPersonalities()[0] != NULL) {
245 unsigned Size = Asm->GetSizeOfEncodedValue(LSDAEncoding);
247 Asm->EmitULEB128(Size, "Augmentation size");
248 Asm->OutStreamer.AddComment("Language Specific Data Area");
249 if (EHFrameInfo.hasLandingPads)
250 Asm->EmitReference(Asm->GetTempSymbol("exception", EHFrameInfo.Number),
253 Asm->OutStreamer.EmitIntValue(0, Size/*size*/, 0/*addrspace*/);
256 Asm->EmitULEB128(0, "Augmentation size");
259 // Indicate locations of function specific callee saved registers in frame.
260 Asm->EmitFrameMoves(EHFrameInfo.Moves, EHFuncBeginSym, true);
262 // On Darwin the linker honors the alignment of eh_frame, which means it
263 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
264 // get holes which confuse readers of eh_frame.
265 Asm->EmitAlignment(Asm->getTargetData().getPointerSize() == 4 ? 2 : 3,
267 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_frame_end",
268 EHFrameInfo.Number));
270 // If the function is marked used, this table should be also. We cannot
271 // make the mark unconditional in this case, since retaining the table also
272 // retains the function in this case, and there is code around that depends
273 // on unused functions (calling undefined externals) being dead-stripped to
274 // link correctly. Yes, there really is.
275 if (MMI->isUsedFunction(EHFrameInfo.function))
276 if (Asm->MAI->hasNoDeadStrip())
277 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
280 Asm->OutStreamer.AddBlankLine();
283 /// SharedTypeIds - How many leading type ids two landing pads have in common.
284 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
285 const LandingPadInfo *R) {
286 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
287 unsigned LSize = LIds.size(), RSize = RIds.size();
288 unsigned MinSize = LSize < RSize ? LSize : RSize;
291 for (; Count != MinSize; ++Count)
292 if (LIds[Count] != RIds[Count])
298 /// PadLT - Order landing pads lexicographically by type id.
299 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
300 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
301 unsigned LSize = LIds.size(), RSize = RIds.size();
302 unsigned MinSize = LSize < RSize ? LSize : RSize;
304 for (unsigned i = 0; i != MinSize; ++i)
305 if (LIds[i] != RIds[i])
306 return LIds[i] < RIds[i];
308 return LSize < RSize;
311 /// ComputeActionsTable - Compute the actions table and gather the first action
312 /// index for each landing pad site.
313 unsigned DwarfException::
314 ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
315 SmallVectorImpl<ActionEntry> &Actions,
316 SmallVectorImpl<unsigned> &FirstActions) {
318 // The action table follows the call-site table in the LSDA. The individual
319 // records are of two types:
322 // * Exception specification
324 // The two record kinds have the same format, with only small differences.
325 // They are distinguished by the "switch value" field: Catch clauses
326 // (TypeInfos) have strictly positive switch values, and exception
327 // specifications (FilterIds) have strictly negative switch values. Value 0
328 // indicates a catch-all clause.
330 // Negative type IDs index into FilterIds. Positive type IDs index into
331 // TypeInfos. The value written for a positive type ID is just the type ID
332 // itself. For a negative type ID, however, the value written is the
333 // (negative) byte offset of the corresponding FilterIds entry. The byte
334 // offset is usually equal to the type ID (because the FilterIds entries are
335 // written using a variable width encoding, which outputs one byte per entry
336 // as long as the value written is not too large) but can differ. This kind
337 // of complication does not occur for positive type IDs because type infos are
338 // output using a fixed width encoding. FilterOffsets[i] holds the byte
339 // offset corresponding to FilterIds[i].
341 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
342 SmallVector<int, 16> FilterOffsets;
343 FilterOffsets.reserve(FilterIds.size());
346 for (std::vector<unsigned>::const_iterator
347 I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
348 FilterOffsets.push_back(Offset);
349 Offset -= MCAsmInfo::getULEB128Size(*I);
352 FirstActions.reserve(LandingPads.size());
355 unsigned SizeActions = 0;
356 const LandingPadInfo *PrevLPI = 0;
358 for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
359 I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
360 const LandingPadInfo *LPI = *I;
361 const std::vector<int> &TypeIds = LPI->TypeIds;
362 unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
363 unsigned SizeSiteActions = 0;
365 if (NumShared < TypeIds.size()) {
366 unsigned SizeAction = 0;
367 unsigned PrevAction = (unsigned)-1;
370 unsigned SizePrevIds = PrevLPI->TypeIds.size();
371 assert(Actions.size());
372 PrevAction = Actions.size() - 1;
374 MCAsmInfo::getSLEB128Size(Actions[PrevAction].NextAction) +
375 MCAsmInfo::getSLEB128Size(Actions[PrevAction].ValueForTypeID);
377 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
378 assert(PrevAction != (unsigned)-1 && "PrevAction is invalid!");
380 MCAsmInfo::getSLEB128Size(Actions[PrevAction].ValueForTypeID);
381 SizeAction += -Actions[PrevAction].NextAction;
382 PrevAction = Actions[PrevAction].Previous;
386 // Compute the actions.
387 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
388 int TypeID = TypeIds[J];
389 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
390 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
391 unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
393 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
394 SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
395 SizeSiteActions += SizeAction;
397 ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
398 Actions.push_back(Action);
399 PrevAction = Actions.size() - 1;
402 // Record the first action of the landing pad site.
403 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
404 } // else identical - re-use previous FirstAction
406 // Information used when created the call-site table. The action record
407 // field of the call site record is the offset of the first associated
408 // action record, relative to the start of the actions table. This value is
409 // biased by 1 (1 indicating the start of the actions table), and 0
410 // indicates that there are no actions.
411 FirstActions.push_back(FirstAction);
413 // Compute this sites contribution to size.
414 SizeActions += SizeSiteActions;
422 /// CallToNoUnwindFunction - Return `true' if this is a call to a function
423 /// marked `nounwind'. Return `false' otherwise.
424 bool DwarfException::CallToNoUnwindFunction(const MachineInstr *MI) {
425 assert(MI->getDesc().isCall() && "This should be a call instruction!");
427 bool MarkedNoUnwind = false;
428 bool SawFunc = false;
430 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
431 const MachineOperand &MO = MI->getOperand(I);
433 if (!MO.isGlobal()) continue;
435 Function *F = dyn_cast<Function>(MO.getGlobal());
436 if (F == 0) continue;
439 // Be conservative. If we have more than one function operand for this
440 // call, then we can't make the assumption that it's the callee and
441 // not a parameter to the call.
443 // FIXME: Determine if there's a way to say that `F' is the callee or
445 MarkedNoUnwind = false;
449 MarkedNoUnwind = F->doesNotThrow();
453 return MarkedNoUnwind;
456 /// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
457 /// has a try-range containing the call, a non-zero landing pad, and an
458 /// appropriate action. The entry for an ordinary call has a try-range
459 /// containing the call and zero for the landing pad and the action. Calls
460 /// marked 'nounwind' have no entry and must not be contained in the try-range
461 /// of any entry - they form gaps in the table. Entries must be ordered by
462 /// try-range address.
463 void DwarfException::
464 ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
465 const RangeMapType &PadMap,
466 const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
467 const SmallVectorImpl<unsigned> &FirstActions) {
468 // The end label of the previous invoke or nounwind try-range.
469 MCSymbol *LastLabel = 0;
471 // Whether there is a potentially throwing instruction (currently this means
472 // an ordinary call) between the end of the previous try-range and now.
473 bool SawPotentiallyThrowing = false;
475 // Whether the last CallSite entry was for an invoke.
476 bool PreviousIsInvoke = false;
478 // Visit all instructions in order of address.
479 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
481 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
483 if (!MI->isLabel()) {
484 if (MI->getDesc().isCall())
485 SawPotentiallyThrowing |= !CallToNoUnwindFunction(MI);
489 // End of the previous try-range?
490 MCSymbol *BeginLabel = MI->getOperand(0).getMCSymbol();
491 if (BeginLabel == LastLabel)
492 SawPotentiallyThrowing = false;
494 // Beginning of a new try-range?
495 RangeMapType::const_iterator L = PadMap.find(BeginLabel);
496 if (L == PadMap.end())
497 // Nope, it was just some random label.
500 const PadRange &P = L->second;
501 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
502 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
503 "Inconsistent landing pad map!");
505 // For Dwarf exception handling (SjLj handling doesn't use this). If some
506 // instruction between the previous try-range and this one may throw,
507 // create a call-site entry with no landing pad for the region between the
509 if (SawPotentiallyThrowing &&
510 Asm->MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
511 CallSiteEntry Site = { LastLabel, BeginLabel, 0, 0 };
512 CallSites.push_back(Site);
513 PreviousIsInvoke = false;
516 LastLabel = LandingPad->EndLabels[P.RangeIndex];
517 assert(BeginLabel && LastLabel && "Invalid landing pad!");
519 if (!LandingPad->LandingPadLabel) {
521 PreviousIsInvoke = false;
523 // This try-range is for an invoke.
524 CallSiteEntry Site = {
527 LandingPad->LandingPadLabel,
528 FirstActions[P.PadIndex]
531 // Try to merge with the previous call-site. SJLJ doesn't do this
532 if (PreviousIsInvoke &&
533 Asm->MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
534 CallSiteEntry &Prev = CallSites.back();
535 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
536 // Extend the range of the previous entry.
537 Prev.EndLabel = Site.EndLabel;
542 // Otherwise, create a new call-site.
543 if (Asm->MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf)
544 CallSites.push_back(Site);
546 // SjLj EH must maintain the call sites in the order assigned
547 // to them by the SjLjPrepare pass.
548 unsigned SiteNo = MMI->getCallSiteBeginLabel(BeginLabel);
549 if (CallSites.size() < SiteNo)
550 CallSites.resize(SiteNo);
551 CallSites[SiteNo - 1] = Site;
553 PreviousIsInvoke = true;
558 // If some instruction between the previous try-range and the end of the
559 // function may throw, create a call-site entry with no landing pad for the
560 // region following the try-range.
561 if (SawPotentiallyThrowing &&
562 Asm->MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
563 CallSiteEntry Site = { LastLabel, 0, 0, 0 };
564 CallSites.push_back(Site);
568 /// EmitExceptionTable - Emit landing pads and actions.
570 /// The general organization of the table is complex, but the basic concepts are
571 /// easy. First there is a header which describes the location and organization
572 /// of the three components that follow.
574 /// 1. The landing pad site information describes the range of code covered by
575 /// the try. In our case it's an accumulation of the ranges covered by the
576 /// invokes in the try. There is also a reference to the landing pad that
577 /// handles the exception once processed. Finally an index into the actions
579 /// 2. The action table, in our case, is composed of pairs of type IDs and next
580 /// action offset. Starting with the action index from the landing pad
581 /// site, each type ID is checked for a match to the current exception. If
582 /// it matches then the exception and type id are passed on to the landing
583 /// pad. Otherwise the next action is looked up. This chain is terminated
584 /// with a next action of zero. If no type id is found then the frame is
585 /// unwound and handling continues.
586 /// 3. Type ID table contains references to all the C++ typeinfo for all
587 /// catches in the function. This tables is reverse indexed base 1.
588 void DwarfException::EmitExceptionTable() {
589 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
590 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
591 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
593 // Sort the landing pads in order of their type ids. This is used to fold
594 // duplicate actions.
595 SmallVector<const LandingPadInfo *, 64> LandingPads;
596 LandingPads.reserve(PadInfos.size());
598 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
599 LandingPads.push_back(&PadInfos[i]);
601 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
603 // Compute the actions table and gather the first action index for each
605 SmallVector<ActionEntry, 32> Actions;
606 SmallVector<unsigned, 64> FirstActions;
607 unsigned SizeActions=ComputeActionsTable(LandingPads, Actions, FirstActions);
609 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
610 // by try-range labels when lowered). Ordinary calls do not, so appropriate
611 // try-ranges for them need be deduced when using DWARF exception handling.
613 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
614 const LandingPadInfo *LandingPad = LandingPads[i];
615 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
616 MCSymbol *BeginLabel = LandingPad->BeginLabels[j];
617 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
618 PadRange P = { i, j };
619 PadMap[BeginLabel] = P;
623 // Compute the call-site table.
624 SmallVector<CallSiteEntry, 64> CallSites;
625 ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
630 bool IsSJLJ = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
631 bool HaveTTData = IsSJLJ ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
633 unsigned CallSiteTableLength;
635 CallSiteTableLength = 0;
637 unsigned SiteStartSize = 4; // dwarf::DW_EH_PE_udata4
638 unsigned SiteLengthSize = 4; // dwarf::DW_EH_PE_udata4
639 unsigned LandingPadSize = 4; // dwarf::DW_EH_PE_udata4
640 CallSiteTableLength =
641 CallSites.size() * (SiteStartSize + SiteLengthSize + LandingPadSize);
644 for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
645 CallSiteTableLength += MCAsmInfo::getULEB128Size(CallSites[i].Action);
647 CallSiteTableLength += MCAsmInfo::getULEB128Size(i);
651 const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
652 unsigned TTypeEncoding;
653 unsigned TypeFormatSize;
656 // For SjLj exceptions, if there is no TypeInfo, then we just explicitly say
657 // that we're omitting that bit.
658 TTypeEncoding = dwarf::DW_EH_PE_omit;
659 // dwarf::DW_EH_PE_absptr
660 TypeFormatSize = Asm->getTargetData().getPointerSize();
662 // Okay, we have actual filters or typeinfos to emit. As such, we need to
663 // pick a type encoding for them. We're about to emit a list of pointers to
664 // typeinfo objects at the end of the LSDA. However, unless we're in static
665 // mode, this reference will require a relocation by the dynamic linker.
667 // Because of this, we have a couple of options:
669 // 1) If we are in -static mode, we can always use an absolute reference
670 // from the LSDA, because the static linker will resolve it.
672 // 2) Otherwise, if the LSDA section is writable, we can output the direct
673 // reference to the typeinfo and allow the dynamic linker to relocate
674 // it. Since it is in a writable section, the dynamic linker won't
677 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
678 // we need to use some form of indirection. For example, on Darwin,
679 // we can output a statically-relocatable reference to a dyld stub. The
680 // offset to the stub is constant, but the contents are in a section
681 // that is updated by the dynamic linker. This is easy enough, but we
682 // need to tell the personality function of the unwinder to indirect
683 // through the dyld stub.
685 // FIXME: When (3) is actually implemented, we'll have to emit the stubs
686 // somewhere. This predicate should be moved to a shared location that is
687 // in target-independent code.
689 TTypeEncoding = Asm->getObjFileLowering().getTTypeEncoding();
690 TypeFormatSize = Asm->GetSizeOfEncodedValue(TTypeEncoding);
693 // Begin the exception table.
694 Asm->OutStreamer.SwitchSection(LSDASection);
695 Asm->EmitAlignment(2, 0, 0, false);
699 Asm->OutContext.GetOrCreateSymbol(Twine("GCC_except_table")+
700 Twine(Asm->getFunctionNumber()));
701 Asm->OutStreamer.EmitLabel(GCCETSym);
702 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("exception",
703 Asm->getFunctionNumber()));
706 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("_LSDA_",
707 Asm->getFunctionNumber()));
709 // Emit the LSDA header.
710 Asm->EmitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
711 Asm->EmitEncodingByte(TTypeEncoding, "@TType");
713 // The type infos need to be aligned. GCC does this by inserting padding just
714 // before the type infos. However, this changes the size of the exception
715 // table, so you need to take this into account when you output the exception
716 // table size. However, the size is output using a variable length encoding.
717 // So by increasing the size by inserting padding, you may increase the number
718 // of bytes used for writing the size. If it increases, say by one byte, then
719 // you now need to output one less byte of padding to get the type infos
720 // aligned. However this decreases the size of the exception table. This
721 // changes the value you have to output for the exception table size. Due to
722 // the variable length encoding, the number of bytes used for writing the
723 // length may decrease. If so, you then have to increase the amount of
724 // padding. And so on. If you look carefully at the GCC code you will see that
725 // it indeed does this in a loop, going on and on until the values stabilize.
726 // We chose another solution: don't output padding inside the table like GCC
727 // does, instead output it before the table.
728 unsigned SizeTypes = TypeInfos.size() * TypeFormatSize;
729 unsigned CallSiteTableLengthSize =
730 MCAsmInfo::getULEB128Size(CallSiteTableLength);
731 unsigned TTypeBaseOffset =
732 sizeof(int8_t) + // Call site format
733 CallSiteTableLengthSize + // Call site table length size
734 CallSiteTableLength + // Call site table length
735 SizeActions + // Actions size
737 unsigned TTypeBaseOffsetSize = MCAsmInfo::getULEB128Size(TTypeBaseOffset);
739 sizeof(int8_t) + // LPStart format
740 sizeof(int8_t) + // TType format
741 (HaveTTData ? TTypeBaseOffsetSize : 0) + // TType base offset size
742 TTypeBaseOffset; // TType base offset
743 unsigned SizeAlign = (4 - TotalSize) & 3;
746 // Account for any extra padding that will be added to the call site table
748 Asm->EmitULEB128(TTypeBaseOffset, "@TType base offset", SizeAlign);
752 // SjLj Exception handling
754 Asm->EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
756 // Add extra padding if it wasn't added to the TType base offset.
757 Asm->EmitULEB128(CallSiteTableLength, "Call site table length", SizeAlign);
759 // Emit the landing pad site information.
761 for (SmallVectorImpl<CallSiteEntry>::const_iterator
762 I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
763 const CallSiteEntry &S = *I;
765 // Offset of the landing pad, counted in 16-byte bundles relative to the
767 Asm->EmitULEB128(idx, "Landing pad");
769 // Offset of the first associated action record, relative to the start of
770 // the action table. This value is biased by 1 (1 indicates the start of
771 // the action table), and 0 indicates that there are no actions.
772 Asm->EmitULEB128(S.Action, "Action");
775 // DWARF Exception handling
776 assert(Asm->MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
778 // The call-site table is a list of all call sites that may throw an
779 // exception (including C++ 'throw' statements) in the procedure
780 // fragment. It immediately follows the LSDA header. Each entry indicates,
781 // for a given call, the first corresponding action record and corresponding
784 // The table begins with the number of bytes, stored as an LEB128
785 // compressed, unsigned integer. The records immediately follow the record
786 // count. They are sorted in increasing call-site address. Each record
789 // * The position of the call-site.
790 // * The position of the landing pad.
791 // * The first action record for that call site.
793 // A missing entry in the call-site table indicates that a call is not
794 // supposed to throw.
796 // Emit the landing pad call site table.
797 Asm->EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
799 // Add extra padding if it wasn't added to the TType base offset.
800 Asm->EmitULEB128(CallSiteTableLength, "Call site table length", SizeAlign);
802 for (SmallVectorImpl<CallSiteEntry>::const_iterator
803 I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
804 const CallSiteEntry &S = *I;
806 MCSymbol *EHFuncBeginSym =
807 Asm->GetTempSymbol("eh_func_begin", Asm->getFunctionNumber());
809 MCSymbol *BeginLabel = S.BeginLabel;
811 BeginLabel = EHFuncBeginSym;
812 MCSymbol *EndLabel = S.EndLabel;
814 EndLabel = Asm->GetTempSymbol("eh_func_end", Asm->getFunctionNumber());
816 // Offset of the call site relative to the previous call site, counted in
817 // number of 16-byte bundles. The first call site is counted relative to
818 // the start of the procedure fragment.
819 Asm->OutStreamer.AddComment("Region start");
820 Asm->EmitLabelDifference(BeginLabel, EHFuncBeginSym, 4);
822 Asm->OutStreamer.AddComment("Region length");
823 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
826 // Offset of the landing pad, counted in 16-byte bundles relative to the
828 Asm->OutStreamer.AddComment("Landing pad");
830 Asm->OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
832 Asm->EmitLabelDifference(S.PadLabel, EHFuncBeginSym, 4);
834 // Offset of the first associated action record, relative to the start of
835 // the action table. This value is biased by 1 (1 indicates the start of
836 // the action table), and 0 indicates that there are no actions.
837 Asm->EmitULEB128(S.Action, "Action");
841 // Emit the Action Table.
842 if (Actions.size() != 0) {
843 Asm->OutStreamer.AddComment("-- Action Record Table --");
844 Asm->OutStreamer.AddBlankLine();
847 for (SmallVectorImpl<ActionEntry>::const_iterator
848 I = Actions.begin(), E = Actions.end(); I != E; ++I) {
849 const ActionEntry &Action = *I;
850 Asm->OutStreamer.AddComment("Action Record");
851 Asm->OutStreamer.AddBlankLine();
855 // Used by the runtime to match the type of the thrown exception to the
856 // type of the catch clauses or the types in the exception specification.
857 Asm->EmitSLEB128(Action.ValueForTypeID, " TypeInfo index");
861 // Self-relative signed displacement in bytes of the next action record,
862 // or 0 if there is no next action record.
863 Asm->EmitSLEB128(Action.NextAction, " Next action");
866 // Emit the Catch TypeInfos.
867 if (!TypeInfos.empty()) {
868 Asm->OutStreamer.AddComment("-- Catch TypeInfos --");
869 Asm->OutStreamer.AddBlankLine();
871 for (std::vector<GlobalVariable *>::const_reverse_iterator
872 I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
873 const GlobalVariable *GV = *I;
875 Asm->OutStreamer.AddComment("TypeInfo");
877 Asm->EmitReference(GV, TTypeEncoding);
879 Asm->OutStreamer.EmitIntValue(0,Asm->GetSizeOfEncodedValue(TTypeEncoding),
883 // Emit the Exception Specifications.
884 if (!FilterIds.empty()) {
885 Asm->OutStreamer.AddComment("-- Filter IDs --");
886 Asm->OutStreamer.AddBlankLine();
888 for (std::vector<unsigned>::const_iterator
889 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
890 unsigned TypeID = *I;
891 Asm->EmitULEB128(TypeID, TypeID != 0 ? "Exception specification" : 0);
894 Asm->EmitAlignment(2, 0, 0, false);
897 /// EndModule - Emit all exception information that should come after the
899 void DwarfException::EndModule() {
900 if (Asm->MAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
903 if (!shouldEmitMovesModule && !shouldEmitTableModule)
906 TimeRegion Timer(ExceptionTimer);
908 const std::vector<Function *> Personalities = MMI->getPersonalities();
910 for (unsigned I = 0, E = Personalities.size(); I < E; ++I)
911 EmitCIE(Personalities[I], I);
913 for (std::vector<FunctionEHFrameInfo>::iterator
914 I = EHFrames.begin(), E = EHFrames.end(); I != E; ++I)
918 /// BeginFunction - Gather pre-function exception information. Assumes it's
919 /// being emitted immediately after the function entry point.
920 void DwarfException::BeginFunction(const MachineFunction *MF) {
921 TimeRegion Timer(ExceptionTimer);
922 shouldEmitTable = shouldEmitMoves = false;
924 // If any landing pads survive, we need an EH table.
925 shouldEmitTable = !MMI->getLandingPads().empty();
927 // See if we need frame move info.
929 !Asm->MF->getFunction()->doesNotThrow() || UnwindTablesMandatory;
931 if (shouldEmitMoves || shouldEmitTable)
932 // Assumes in correct section after the entry point.
933 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_begin",
934 Asm->getFunctionNumber()));
936 shouldEmitTableModule |= shouldEmitTable;
937 shouldEmitMovesModule |= shouldEmitMoves;
940 /// EndFunction - Gather and emit post-function exception information.
942 void DwarfException::EndFunction() {
943 if (!shouldEmitMoves && !shouldEmitTable) return;
945 TimeRegion Timer(ExceptionTimer);
946 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_end",
947 Asm->getFunctionNumber()));
949 // Record if this personality index uses a landing pad.
950 bool HasLandingPad = !MMI->getLandingPads().empty();
951 UsesLSDA[MMI->getPersonalityIndex()] |= HasLandingPad;
953 // Map all labels and get rid of any dead landing pads.
954 MMI->TidyLandingPads();
957 EmitExceptionTable();
959 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
960 MCSymbol *FunctionEHSym =
961 Asm->GetSymbolWithGlobalValueBase(Asm->MF->getFunction(), ".eh",
962 TLOF.isFunctionEHFrameSymbolPrivate());
964 // Save EH frame information
965 EHFrames.push_back(FunctionEHFrameInfo(FunctionEHSym,
966 Asm->getFunctionNumber(),
967 MMI->getPersonalityIndex(),
968 Asm->MF->getFrameInfo()->hasCalls(),
969 !MMI->getLandingPads().empty(),
970 MMI->getFrameMoves(),
971 Asm->MF->getFunction()));