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/MachineModuleInfo.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineLocation.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetFrameInfo.h"
24 #include "llvm/Target/TargetLoweringObjectFile.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include "llvm/Target/TargetRegisterInfo.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/StringExtras.h"
33 static TimerGroup &getDwarfTimerGroup() {
34 static TimerGroup DwarfTimerGroup("Dwarf Exception");
35 return DwarfTimerGroup;
38 DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A,
40 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
41 shouldEmitTableModule(false), shouldEmitMovesModule(false),
43 if (TimePassesIsEnabled)
44 ExceptionTimer = new Timer("Dwarf Exception Writer",
45 getDwarfTimerGroup());
48 DwarfException::~DwarfException() {
49 delete ExceptionTimer;
52 /// EmitCommonInformationEntry - Emit a Common Information Entry (CIE). This
53 /// holds information that is shared among many Frame Description Entries.
54 /// There is at least one CIE in every non-empty .debug_frame section.
55 void DwarfException::EmitCommonInformationEntry(const Function *Personality,
57 // Size and sign of stack growth.
59 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
60 TargetFrameInfo::StackGrowsUp ?
61 TD->getPointerSize() : -TD->getPointerSize();
63 // Begin eh frame section.
64 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
66 if (MAI->is_EHSymbolPrivate())
67 O << MAI->getPrivateGlobalPrefix();
69 O << "EH_frame" << Index << ":\n";
70 EmitLabel("section_eh_frame", Index);
72 // Define base labels.
73 EmitLabel("eh_frame_common", Index);
75 // Define the eh frame length.
76 EmitDifference("eh_frame_common_end", Index,
77 "eh_frame_common_begin", Index, true);
78 Asm->EOL("Length of Common Information Entry");
81 EmitLabel("eh_frame_common_begin", Index);
82 Asm->EmitInt32((int)0);
83 Asm->EOL("CIE Identifier Tag");
84 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
85 Asm->EOL("CIE Version");
87 // The personality presence indicates that language specific information will
88 // show up in the eh frame.
89 Asm->EmitString(Personality ? "zPLR" : "zR");
90 Asm->EOL("CIE Augmentation");
93 Asm->EmitULEB128Bytes(1);
94 Asm->EOL("CIE Code Alignment Factor");
95 Asm->EmitSLEB128Bytes(stackGrowth);
96 Asm->EOL("CIE Data Alignment Factor");
97 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
98 Asm->EOL("CIE Return Address Column");
100 // If there is a personality, we need to indicate the functions location.
102 Asm->EmitULEB128Bytes(7);
103 Asm->EOL("Augmentation Size");
105 if (MAI->getNeedsIndirectEncoding()) {
106 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 |
107 dwarf::DW_EH_PE_indirect);
108 Asm->EOL("Personality (pcrel sdata4 indirect)");
110 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
111 Asm->EOL("Personality (pcrel sdata4)");
114 PrintRelDirective(true);
115 O << MAI->getPersonalityPrefix();
116 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
117 O << MAI->getPersonalitySuffix();
118 if (strcmp(MAI->getPersonalitySuffix(), "+4@GOTPCREL"))
119 O << "-" << MAI->getPCSymbol();
120 Asm->EOL("Personality");
122 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
123 Asm->EOL("LSDA Encoding (pcrel sdata4)");
125 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
126 Asm->EOL("FDE Encoding (pcrel sdata4)");
128 Asm->EmitULEB128Bytes(1);
129 Asm->EOL("Augmentation Size");
131 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
132 Asm->EOL("FDE Encoding (pcrel sdata4)");
135 // Indicate locations of general callee saved registers in frame.
136 std::vector<MachineMove> Moves;
137 RI->getInitialFrameState(Moves);
138 EmitFrameMoves(NULL, 0, Moves, true);
140 // On Darwin the linker honors the alignment of eh_frame, which means it must
141 // be 8-byte on 64-bit targets to match what gcc does. Otherwise you get
142 // holes which confuse readers of eh_frame.
143 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
145 EmitLabel("eh_frame_common_end", Index);
150 /// EmitFrameDescriptionEntry - Emit the Frame Description Entry (FDE) for the
152 void DwarfException::
153 EmitFrameDescriptionEntry(const FunctionEHFrameInfo &EHFrameInfo) {
154 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
155 "Should not emit 'available externally' functions at all");
157 const Function *TheFunc = EHFrameInfo.function;
159 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
161 // Externally visible entry into the functions eh frame info. If the
162 // corresponding function is static, this should not be externally visible.
163 if (!TheFunc->hasLocalLinkage())
164 if (const char *GlobalEHDirective = MAI->getGlobalEHDirective())
165 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
167 // If corresponding function is weak definition, this should be too.
168 if (TheFunc->isWeakForLinker() && MAI->getWeakDefDirective())
169 O << MAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
171 // If there are no calls then you can't unwind. This may mean we can omit the
172 // EH Frame, but some environments do not handle weak absolute symbols. If
173 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
174 // info is to be available for non-EH uses.
175 if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
176 (!TheFunc->isWeakForLinker() ||
177 !MAI->getWeakDefDirective() ||
178 MAI->getSupportsWeakOmittedEHFrame())) {
179 O << EHFrameInfo.FnName << " = 0\n";
180 // This name has no connection to the function, so it might get
181 // dead-stripped when the function is not, erroneously. Prohibit
182 // dead-stripping unconditionally.
183 if (const char *UsedDirective = MAI->getUsedDirective())
184 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
186 O << EHFrameInfo.FnName << ":\n";
189 EmitDifference("eh_frame_end", EHFrameInfo.Number,
190 "eh_frame_begin", EHFrameInfo.Number, true);
191 Asm->EOL("Length of Frame Information Entry");
193 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
195 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
196 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
199 Asm->EOL("FDE CIE offset");
201 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
202 Asm->EOL("FDE initial location");
203 EmitDifference("eh_func_end", EHFrameInfo.Number,
204 "eh_func_begin", EHFrameInfo.Number, true);
205 Asm->EOL("FDE address range");
207 // If there is a personality and landing pads then point to the language
208 // specific data area in the exception table.
209 if (EHFrameInfo.PersonalityIndex) {
210 Asm->EmitULEB128Bytes(4);
211 Asm->EOL("Augmentation size");
213 if (EHFrameInfo.hasLandingPads)
214 EmitReference("exception", EHFrameInfo.Number, true, true);
216 Asm->EmitInt32((int)0);
217 Asm->EOL("Language Specific Data Area");
219 Asm->EmitULEB128Bytes(0);
220 Asm->EOL("Augmentation size");
223 // Indicate locations of function specific callee saved registers in frame.
224 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
227 // On Darwin the linker honors the alignment of eh_frame, which means it
228 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
229 // get holes which confuse readers of eh_frame.
230 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
232 EmitLabel("eh_frame_end", EHFrameInfo.Number);
234 // If the function is marked used, this table should be also. We cannot
235 // make the mark unconditional in this case, since retaining the table also
236 // retains the function in this case, and there is code around that depends
237 // on unused functions (calling undefined externals) being dead-stripped to
238 // link correctly. Yes, there really is.
239 if (MMI->isUsedFunction(EHFrameInfo.function))
240 if (const char *UsedDirective = MAI->getUsedDirective())
241 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
245 /// SharedTypeIds - How many leading type ids two landing pads have in common.
246 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
247 const LandingPadInfo *R) {
248 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
249 unsigned LSize = LIds.size(), RSize = RIds.size();
250 unsigned MinSize = LSize < RSize ? LSize : RSize;
253 for (; Count != MinSize; ++Count)
254 if (LIds[Count] != RIds[Count])
260 /// PadLT - Order landing pads lexicographically by type id.
261 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
262 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
263 unsigned LSize = LIds.size(), RSize = RIds.size();
264 unsigned MinSize = LSize < RSize ? LSize : RSize;
266 for (unsigned i = 0; i != MinSize; ++i)
267 if (LIds[i] != RIds[i])
268 return LIds[i] < RIds[i];
270 return LSize < RSize;
273 /// ComputeActionsTable - Compute the actions table and gather the first action
274 /// index for each landing pad site.
275 unsigned DwarfException::
276 ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
277 SmallVectorImpl<ActionEntry> &Actions,
278 SmallVectorImpl<unsigned> &FirstActions) {
280 // The action table follows the call-site table in the LSDA. The individual
281 // records are of two types:
284 // * Exception specification
286 // The two record kinds have the same format, with only small differences.
287 // They are distinguished by the "switch value" field: Catch clauses
288 // (TypeInfos) have strictly positive switch values, and exception
289 // specifications (FilterIds) have strictly negative switch values. Value 0
290 // indicates a catch-all clause.
292 // Negative type IDs index into FilterIds. Positive type IDs index into
293 // TypeInfos. The value written for a positive type ID is just the type ID
294 // itself. For a negative type ID, however, the value written is the
295 // (negative) byte offset of the corresponding FilterIds entry. The byte
296 // offset is usually equal to the type ID (because the FilterIds entries are
297 // written using a variable width encoding, which outputs one byte per entry
298 // as long as the value written is not too large) but can differ. This kind
299 // of complication does not occur for positive type IDs because type infos are
300 // output using a fixed width encoding. FilterOffsets[i] holds the byte
301 // offset corresponding to FilterIds[i].
303 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
304 SmallVector<int, 16> FilterOffsets;
305 FilterOffsets.reserve(FilterIds.size());
308 for (std::vector<unsigned>::const_iterator
309 I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
310 FilterOffsets.push_back(Offset);
311 Offset -= MCAsmInfo::getULEB128Size(*I);
314 FirstActions.reserve(LandingPads.size());
317 unsigned SizeActions = 0;
318 const LandingPadInfo *PrevLPI = 0;
320 for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
321 I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
322 const LandingPadInfo *LPI = *I;
323 const std::vector<int> &TypeIds = LPI->TypeIds;
324 const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
325 unsigned SizeSiteActions = 0;
327 if (NumShared < TypeIds.size()) {
328 unsigned SizeAction = 0;
329 ActionEntry *PrevAction = 0;
332 const unsigned SizePrevIds = PrevLPI->TypeIds.size();
333 assert(Actions.size());
334 PrevAction = &Actions.back();
335 SizeAction = MCAsmInfo::getSLEB128Size(PrevAction->NextAction) +
336 MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
338 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
340 MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
341 SizeAction += -PrevAction->NextAction;
342 PrevAction = PrevAction->Previous;
346 // Compute the actions.
347 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
348 int TypeID = TypeIds[J];
349 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
350 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
351 unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
353 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
354 SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
355 SizeSiteActions += SizeAction;
357 ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
358 Actions.push_back(Action);
359 PrevAction = &Actions.back();
362 // Record the first action of the landing pad site.
363 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
364 } // else identical - re-use previous FirstAction
366 // Information used when created the call-site table. The action record
367 // field of the call site record is the offset of the first associated
368 // action record, relative to the start of the actions table. This value is
369 // biased by 1 (1 in dicating the start of the actions table), and 0
370 // indicates that there are no actions.
371 FirstActions.push_back(FirstAction);
373 // Compute this sites contribution to size.
374 SizeActions += SizeSiteActions;
382 /// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
383 /// has a try-range containing the call, a non-zero landing pad, and an
384 /// appropriate action. The entry for an ordinary call has a try-range
385 /// containing the call and zero for the landing pad and the action. Calls
386 /// marked 'nounwind' have no entry and must not be contained in the try-range
387 /// of any entry - they form gaps in the table. Entries must be ordered by
388 /// try-range address.
389 void DwarfException::
390 ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
391 const RangeMapType &PadMap,
392 const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
393 const SmallVectorImpl<unsigned> &FirstActions) {
394 // The end label of the previous invoke or nounwind try-range.
395 unsigned LastLabel = 0;
397 // Whether there is a potentially throwing instruction (currently this means
398 // an ordinary call) between the end of the previous try-range and now.
399 bool SawPotentiallyThrowing = false;
401 // Whether the last CallSite entry was for an invoke.
402 bool PreviousIsInvoke = false;
404 // Visit all instructions in order of address.
405 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
407 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
409 if (!MI->isLabel()) {
410 SawPotentiallyThrowing |= MI->getDesc().isCall();
414 unsigned BeginLabel = MI->getOperand(0).getImm();
415 assert(BeginLabel && "Invalid label!");
417 // End of the previous try-range?
418 if (BeginLabel == LastLabel)
419 SawPotentiallyThrowing = false;
421 // Beginning of a new try-range?
422 RangeMapType::iterator L = PadMap.find(BeginLabel);
423 if (L == PadMap.end())
424 // Nope, it was just some random label.
427 const PadRange &P = L->second;
428 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
429 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
430 "Inconsistent landing pad map!");
432 // For Dwarf exception handling (SjLj handling doesn't use this). If some
433 // instruction between the previous try-range and this one may throw,
434 // create a call-site entry with no landing pad for the region between the
436 if (SawPotentiallyThrowing &&
437 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
438 CallSiteEntry Site = { LastLabel, BeginLabel, 0, 0 };
439 CallSites.push_back(Site);
440 PreviousIsInvoke = false;
443 LastLabel = LandingPad->EndLabels[P.RangeIndex];
444 assert(BeginLabel && LastLabel && "Invalid landing pad!");
446 if (LandingPad->LandingPadLabel) {
447 // This try-range is for an invoke.
448 CallSiteEntry Site = {
451 LandingPad->LandingPadLabel,
452 FirstActions[P.PadIndex]
455 // Try to merge with the previous call-site.
456 if (PreviousIsInvoke) {
457 CallSiteEntry &Prev = CallSites.back();
458 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
459 // Extend the range of the previous entry.
460 Prev.EndLabel = Site.EndLabel;
465 // Otherwise, create a new call-site.
466 CallSites.push_back(Site);
467 PreviousIsInvoke = true;
470 PreviousIsInvoke = false;
475 // If some instruction between the previous try-range and the end of the
476 // function may throw, create a call-site entry with no landing pad for the
477 // region following the try-range.
478 if (SawPotentiallyThrowing &&
479 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
480 CallSiteEntry Site = { LastLabel, 0, 0, 0 };
481 CallSites.push_back(Site);
485 /// EmitExceptionTable - Emit landing pads and actions.
487 /// The general organization of the table is complex, but the basic concepts are
488 /// easy. First there is a header which describes the location and organization
489 /// of the three components that follow.
491 /// 1. The landing pad site information describes the range of code covered by
492 /// the try. In our case it's an accumulation of the ranges covered by the
493 /// invokes in the try. There is also a reference to the landing pad that
494 /// handles the exception once processed. Finally an index into the actions
496 /// 2. The action table, in our case, is composed of pairs of type IDs and next
497 /// action offset. Starting with the action index from the landing pad
498 /// site, each type ID is checked for a match to the current exception. If
499 /// it matches then the exception and type id are passed on to the landing
500 /// pad. Otherwise the next action is looked up. This chain is terminated
501 /// with a next action of zero. If no type id is found the the frame is
502 /// unwound and handling continues.
503 /// 3. Type ID table contains references to all the C++ typeinfo for all
504 /// catches in the function. This tables is reversed indexed base 1.
505 void DwarfException::EmitExceptionTable() {
506 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
507 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
508 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
509 if (PadInfos.empty()) return;
511 // Sort the landing pads in order of their type ids. This is used to fold
512 // duplicate actions.
513 SmallVector<const LandingPadInfo *, 64> LandingPads;
514 LandingPads.reserve(PadInfos.size());
516 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
517 LandingPads.push_back(&PadInfos[i]);
519 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
521 // Compute the actions table and gather the first action index for each
523 SmallVector<ActionEntry, 32> Actions;
524 SmallVector<unsigned, 64> FirstActions;
525 unsigned SizeActions = ComputeActionsTable(LandingPads, Actions, FirstActions);
527 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
528 // by try-range labels when lowered). Ordinary calls do not, so appropriate
529 // try-ranges for them need be deduced when using Dwarf exception handling.
531 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
532 const LandingPadInfo *LandingPad = LandingPads[i];
533 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
534 unsigned BeginLabel = LandingPad->BeginLabels[j];
535 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
536 PadRange P = { i, j };
537 PadMap[BeginLabel] = P;
541 // Compute the call-site table.
542 SmallVector<CallSiteEntry, 64> CallSites;
543 ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
548 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
549 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
550 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
553 bool HaveTTData = (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
554 ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
557 if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
560 SizeSites = CallSites.size() *
561 (SiteStartSize + SiteLengthSize + LandingPadSize);
562 for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
563 SizeSites += MCAsmInfo::getULEB128Size(CallSites[i].Action);
564 if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
565 SizeSites += MCAsmInfo::getULEB128Size(i);
568 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
569 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
571 unsigned TypeOffset = sizeof(int8_t) + // Call site format
572 MCAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
573 SizeSites + SizeActions + SizeTypes;
575 unsigned TotalSize = sizeof(int8_t) + // LPStart format
576 sizeof(int8_t) + // TType format
578 MCAsmInfo::getULEB128Size(TypeOffset) : 0) + // TType base offset
581 unsigned SizeAlign = (4 - TotalSize) & 3;
583 // Begin the exception table.
584 const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
585 Asm->OutStreamer.SwitchSection(LSDASection);
586 Asm->EmitAlignment(2, 0, 0, false);
587 O << "GCC_except_table" << SubprogramCount << ":\n";
589 for (unsigned i = 0; i != SizeAlign; ++i) {
594 EmitLabel("exception", SubprogramCount);
595 if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
596 std::string SjLjName = "_lsda_";
597 SjLjName += MF->getFunction()->getName().str();
598 EmitLabel(SjLjName.c_str(), 0);
602 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
603 Asm->EOL("@LPStart format (DW_EH_PE_omit)");
606 if (TypeInfos.empty() && FilterIds.empty()) {
607 // If there are no typeinfos or filters, there is nothing to emit, optimize
608 // by specifying the "omit" encoding.
609 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
610 Asm->EOL("@TType format (DW_EH_PE_omit)");
612 // Okay, we have actual filters or typeinfos to emit. As such, we need to
613 // pick a type encoding for them. We're about to emit a list of pointers to
614 // typeinfo objects at the end of the LSDA. However, unless we're in static
615 // mode, this reference will require a relocation by the dynamic linker.
617 // Because of this, we have a couple of options:
618 // 1) If we are in -static mode, we can always use an absolute reference
619 // from the LSDA, because the static linker will resolve it.
620 // 2) Otherwise, if the LSDA section is writable, we can output the direct
621 // reference to the typeinfo and allow the dynamic linker to relocate
622 // it. Since it is in a writable section, the dynamic linker won't
624 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
625 // we need to use some form of indirection. For example, on Darwin,
626 // we can output a statically-relocatable reference to a dyld stub. The
627 // offset to the stub is constant, but the contents are in a section
628 // that is updated by the dynamic linker. This is easy enough, but we
629 // need to tell the personality function of the unwinder to indirect
630 // through the dyld stub.
632 // FIXME: When this is actually implemented, we'll have to emit the stubs
633 // somewhere. This predicate should be moved to a shared location that is
634 // in target-independent code.
636 if (LSDASection->isWritable() ||
637 Asm->TM.getRelocationModel() == Reloc::Static) {
638 Asm->EmitInt8(DW_EH_PE_absptr);
639 Asm->EOL("TType format (DW_EH_PE_absptr)");
641 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_indirect | DW_EH_PE_sdata4);
642 Asm->EOL("TType format (DW_EH_PE_pcrel | DW_EH_PE_indirect"
643 " | DW_EH_PE_sdata4)");
645 Asm->EmitULEB128Bytes(TypeOffset);
646 Asm->EOL("TType base offset");
649 // For SjLj exceptions, if there is no TypeInfo, then we just explicitly
650 // say that we're omitting that bit.
651 // FIXME: does this apply to Dwarf also? The above #if 0 implies yes?
653 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
654 Asm->EOL("@TType format (DW_EH_PE_omit)");
656 Asm->EmitInt8(dwarf::DW_EH_PE_absptr);
657 Asm->EOL("@TType format (DW_EH_PE_absptr)");
658 Asm->EmitULEB128Bytes(TypeOffset);
659 Asm->EOL("@TType base offset");
663 // SjLj Exception handilng
664 if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
665 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
666 Asm->EOL("Call site format (DW_EH_PE_udata4)");
667 Asm->EmitULEB128Bytes(SizeSites);
668 Asm->EOL("Call site table length");
670 // Emit the landing pad site information.
672 for (SmallVectorImpl<CallSiteEntry>::const_iterator
673 I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
674 const CallSiteEntry &S = *I;
676 // Offset of the landing pad, counted in 16-byte bundles relative to the
678 Asm->EmitULEB128Bytes(idx);
679 Asm->EOL("Landing pad");
681 // Offset of the first associated action record, relative to the start of
682 // the action table. This value is biased by 1 (1 indicates the start of
683 // the action table), and 0 indicates that there are no actions.
684 Asm->EmitULEB128Bytes(S.Action);
688 // DWARF Exception handling
689 assert(MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
691 // The call-site table is a list of all call sites that may throw an
692 // exception (including C++ 'throw' statements) in the procedure
693 // fragment. It immediately follows the LSDA header. Each entry indicates,
694 // for a given call, the first corresponding action record and corresponding
697 // The table begins with the number of bytes, stored as an LEB128
698 // compressed, unsigned integer. The records immediately follow the record
699 // count. They are sorted in increasing call-site address. Each record
702 // * The position of the call-site.
703 // * The position of the landing pad.
704 // * The first action record for that call site.
706 // A missing entry in the call-site table indicates that a call is not
707 // supposed to throw. Such calls include:
709 // * Calls to destructors within cleanup code. C++ semantics forbids these
711 // * Calls to intrinsic routines in the standard library which are known
712 // not to throw (sin, memcpy, et al).
714 // If the runtime does not find the call-site entry for a given call, it
715 // will call `terminate()'.
717 // Emit the landing pad call site table.
718 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
719 Asm->EOL("Call site format (DW_EH_PE_udata4)");
720 Asm->EmitULEB128Bytes(SizeSites);
721 Asm->EOL("Call site table size");
723 for (SmallVectorImpl<CallSiteEntry>::const_iterator
724 I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
725 const CallSiteEntry &S = *I;
726 const char *BeginTag;
727 unsigned BeginNumber;
730 BeginTag = "eh_func_begin";
731 BeginNumber = SubprogramCount;
734 BeginNumber = S.BeginLabel;
737 // Offset of the call site relative to the previous call site, counted in
738 // number of 16-byte bundles. The first call site is counted relative to
739 // the start of the procedure fragment.
740 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
742 Asm->EOL("Region start");
745 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
748 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
750 Asm->EOL("Region length");
752 // Offset of the landing pad, counted in 16-byte bundles relative to the
757 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
760 Asm->EOL("Landing pad");
762 // Offset of the first associated action record, relative to the start of
763 // the action table. This value is biased by 1 (1 indicates the start of
764 // the action table), and 0 indicates that there are no actions.
765 Asm->EmitULEB128Bytes(S.Action);
770 // Emit the Action Table.
771 for (SmallVectorImpl<ActionEntry>::const_iterator
772 I = Actions.begin(), E = Actions.end(); I != E; ++I) {
773 const ActionEntry &Action = *I;
777 // Used by the runtime to match the type of the thrown exception to the
778 // type of the catch clauses or the types in the exception specification.
780 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
781 Asm->EOL("TypeInfo index");
785 // Self-relative signed displacement in bytes of the next action record,
786 // or 0 if there is no next action record.
788 Asm->EmitSLEB128Bytes(Action.NextAction);
789 Asm->EOL("Next action");
792 // Emit the Catch Clauses. The code for the catch clauses following the same
793 // try is similar to a switch statement. The catch clause action record
794 // informs the runtime about the type of a catch clause and about the
795 // associated switch value.
797 // Action Record Fields:
800 // Positive value, starting at 1. Index in the types table of the
801 // __typeinfo for the catch-clause type. 1 is the first word preceding
802 // TTBase, 2 is the second word, and so on. Used by the runtime to check
803 // if the thrown exception type matches the catch-clause type. Back-end
804 // generated switch statements check against this value.
807 // Signed offset, in bytes from the start of this field, to the next
808 // chained action record, or zero if none.
810 // The order of the action records determined by the next field is the order
811 // of the catch clauses as they appear in the source code, and must be kept in
812 // the same order. As a result, changing the order of the catch clause would
813 // change the semantics of the program.
814 for (std::vector<GlobalVariable *>::const_reverse_iterator
815 I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
816 const GlobalVariable *GV = *I;
821 O << Asm->getGlobalLinkName(GV, GLN);
826 Asm->EOL("TypeInfo");
829 // Emit the Type Table.
830 for (std::vector<unsigned>::const_iterator
831 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
832 unsigned TypeID = *I;
833 Asm->EmitULEB128Bytes(TypeID);
834 Asm->EOL("Filter TypeInfo index");
837 Asm->EmitAlignment(2, 0, 0, false);
840 /// EndModule - Emit all exception information that should come after the
842 void DwarfException::EndModule() {
843 if (MAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
845 if (TimePassesIsEnabled)
846 ExceptionTimer->startTimer();
848 if (shouldEmitMovesModule || shouldEmitTableModule) {
849 const std::vector<Function *> Personalities = MMI->getPersonalities();
850 for (unsigned i = 0; i < Personalities.size(); ++i)
851 EmitCommonInformationEntry(Personalities[i], i);
853 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
854 E = EHFrames.end(); I != E; ++I)
855 EmitFrameDescriptionEntry(*I);
858 if (TimePassesIsEnabled)
859 ExceptionTimer->stopTimer();
862 /// BeginFunction - Gather pre-function exception information. Assumes being
863 /// emitted immediately after the function entry point.
864 void DwarfException::BeginFunction(MachineFunction *MF) {
865 if (TimePassesIsEnabled)
866 ExceptionTimer->startTimer();
869 shouldEmitTable = shouldEmitMoves = false;
871 if (MMI && MAI->doesSupportExceptionHandling()) {
872 // Map all labels and get rid of any dead landing pads.
873 MMI->TidyLandingPads();
875 // If any landing pads survive, we need an EH table.
876 if (MMI->getLandingPads().size())
877 shouldEmitTable = true;
879 // See if we need frame move info.
880 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
881 shouldEmitMoves = true;
883 if (shouldEmitMoves || shouldEmitTable)
884 // Assumes in correct section after the entry point.
885 EmitLabel("eh_func_begin", ++SubprogramCount);
888 shouldEmitTableModule |= shouldEmitTable;
889 shouldEmitMovesModule |= shouldEmitMoves;
891 if (TimePassesIsEnabled)
892 ExceptionTimer->stopTimer();
895 /// EndFunction - Gather and emit post-function exception information.
897 void DwarfException::EndFunction() {
898 if (TimePassesIsEnabled)
899 ExceptionTimer->startTimer();
901 if (shouldEmitMoves || shouldEmitTable) {
902 EmitLabel("eh_func_end", SubprogramCount);
903 EmitExceptionTable();
905 // Save EH frame information
907 FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
909 MMI->getPersonalityIndex(),
910 MF->getFrameInfo()->hasCalls(),
911 !MMI->getLandingPads().empty(),
912 MMI->getFrameMoves(),
916 if (TimePassesIsEnabled)
917 ExceptionTimer->stopTimer();