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 /// EmitCIE - Emit a Common Information Entry (CIE). This holds information that
53 /// is shared among many Frame Description Entries. There is at least one CIE
54 /// in every non-empty .debug_frame section.
55 void DwarfException::EmitCIE(const Function *Personality, unsigned Index) {
56 // Size and sign of stack growth.
58 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
59 TargetFrameInfo::StackGrowsUp ?
60 TD->getPointerSize() : -TD->getPointerSize();
62 // Begin eh frame section.
63 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
65 if (MAI->is_EHSymbolPrivate())
66 O << MAI->getPrivateGlobalPrefix();
68 O << "EH_frame" << Index << ":\n";
69 EmitLabel("section_eh_frame", Index);
71 // Define base labels.
72 EmitLabel("eh_frame_common", Index);
74 // Define the eh frame length.
75 EmitDifference("eh_frame_common_end", Index,
76 "eh_frame_common_begin", Index, true);
77 Asm->EOL("Length of Common Information Entry");
80 EmitLabel("eh_frame_common_begin", Index);
81 Asm->EmitInt32((int)0);
82 Asm->EOL("CIE Identifier Tag");
83 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
84 Asm->EOL("CIE Version");
86 // The personality presence indicates that language specific information will
87 // show up in the eh frame.
88 Asm->EmitString(Personality ? "zPLR" : "zR");
89 Asm->EOL("CIE Augmentation");
92 Asm->EmitULEB128Bytes(1);
93 Asm->EOL("CIE Code Alignment Factor");
94 Asm->EmitSLEB128Bytes(stackGrowth);
95 Asm->EOL("CIE Data Alignment Factor");
96 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
97 Asm->EOL("CIE Return Address Column");
99 // If there is a personality, we need to indicate the function's location.
101 Asm->EmitULEB128Bytes(7);
102 Asm->EOL("Augmentation Size");
104 if (MAI->getNeedsIndirectEncoding()) {
105 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 |
106 dwarf::DW_EH_PE_indirect);
107 Asm->EOL("Personality (pcrel sdata4 indirect)");
109 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
110 Asm->EOL("Personality (pcrel sdata4)");
113 PrintRelDirective(true);
114 O << MAI->getPersonalityPrefix();
115 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
116 O << MAI->getPersonalitySuffix();
117 if (strcmp(MAI->getPersonalitySuffix(), "+4@GOTPCREL"))
118 O << "-" << MAI->getPCSymbol();
119 Asm->EOL("Personality");
121 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
122 Asm->EOL("LSDA Encoding (pcrel sdata4)");
124 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
125 Asm->EOL("FDE Encoding (pcrel sdata4)");
127 Asm->EmitULEB128Bytes(1);
128 Asm->EOL("Augmentation Size");
130 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
131 Asm->EOL("FDE Encoding (pcrel sdata4)");
134 // Indicate locations of general callee saved registers in frame.
135 std::vector<MachineMove> Moves;
136 RI->getInitialFrameState(Moves);
137 EmitFrameMoves(NULL, 0, Moves, true);
139 // On Darwin the linker honors the alignment of eh_frame, which means it must
140 // be 8-byte on 64-bit targets to match what gcc does. Otherwise you get
141 // holes which confuse readers of eh_frame.
142 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
144 EmitLabel("eh_frame_common_end", Index);
149 /// EmitFDE - Emit the Frame Description Entry (FDE) for the function.
150 void DwarfException::EmitFDE(const FunctionEHFrameInfo &EHFrameInfo) {
151 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
152 "Should not emit 'available externally' functions at all");
154 const Function *TheFunc = EHFrameInfo.function;
156 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
158 // Externally visible entry into the functions eh frame info. If the
159 // corresponding function is static, this should not be externally visible.
160 if (!TheFunc->hasLocalLinkage())
161 if (const char *GlobalEHDirective = MAI->getGlobalEHDirective())
162 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
164 // If corresponding function is weak definition, this should be too.
165 if (TheFunc->isWeakForLinker() && MAI->getWeakDefDirective())
166 O << MAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
168 // If there are no calls then you can't unwind. This may mean we can omit the
169 // EH Frame, but some environments do not handle weak absolute symbols. If
170 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
171 // info is to be available for non-EH uses.
172 if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
173 (!TheFunc->isWeakForLinker() ||
174 !MAI->getWeakDefDirective() ||
175 MAI->getSupportsWeakOmittedEHFrame())) {
176 O << EHFrameInfo.FnName << " = 0\n";
177 // This name has no connection to the function, so it might get
178 // dead-stripped when the function is not, erroneously. Prohibit
179 // dead-stripping unconditionally.
180 if (const char *UsedDirective = MAI->getUsedDirective())
181 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
183 O << EHFrameInfo.FnName << ":\n";
186 EmitDifference("eh_frame_end", EHFrameInfo.Number,
187 "eh_frame_begin", EHFrameInfo.Number, true);
188 Asm->EOL("Length of Frame Information Entry");
190 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
192 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
193 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
196 Asm->EOL("FDE CIE offset");
198 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
199 Asm->EOL("FDE initial location");
200 EmitDifference("eh_func_end", EHFrameInfo.Number,
201 "eh_func_begin", EHFrameInfo.Number, true);
202 Asm->EOL("FDE address range");
204 // If there is a personality and landing pads then point to the language
205 // specific data area in the exception table.
206 if (MMI->getPersonalities()[0] != NULL) {
207 bool is4Byte = TD->getPointerSize() == sizeof(int32_t);
209 Asm->EmitULEB128Bytes(is4Byte ? 4 : 8);
210 Asm->EOL("Augmentation size");
212 if (EHFrameInfo.hasLandingPads)
213 EmitReference("exception", EHFrameInfo.Number, true, false);
216 Asm->EmitInt32((int)0);
218 Asm->EmitInt64((int)0);
220 Asm->EOL("Language Specific Data Area");
222 Asm->EmitULEB128Bytes(0);
223 Asm->EOL("Augmentation size");
226 // Indicate locations of function specific callee saved registers in frame.
227 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
230 // On Darwin the linker honors the alignment of eh_frame, which means it
231 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
232 // get holes which confuse readers of eh_frame.
233 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
235 EmitLabel("eh_frame_end", EHFrameInfo.Number);
237 // If the function is marked used, this table should be also. We cannot
238 // make the mark unconditional in this case, since retaining the table also
239 // retains the function in this case, and there is code around that depends
240 // on unused functions (calling undefined externals) being dead-stripped to
241 // link correctly. Yes, there really is.
242 if (MMI->isUsedFunction(EHFrameInfo.function))
243 if (const char *UsedDirective = MAI->getUsedDirective())
244 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
250 /// SharedTypeIds - How many leading type ids two landing pads have in common.
251 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
252 const LandingPadInfo *R) {
253 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
254 unsigned LSize = LIds.size(), RSize = RIds.size();
255 unsigned MinSize = LSize < RSize ? LSize : RSize;
258 for (; Count != MinSize; ++Count)
259 if (LIds[Count] != RIds[Count])
265 /// PadLT - Order landing pads lexicographically by type id.
266 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
267 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
268 unsigned LSize = LIds.size(), RSize = RIds.size();
269 unsigned MinSize = LSize < RSize ? LSize : RSize;
271 for (unsigned i = 0; i != MinSize; ++i)
272 if (LIds[i] != RIds[i])
273 return LIds[i] < RIds[i];
275 return LSize < RSize;
278 /// ComputeActionsTable - Compute the actions table and gather the first action
279 /// index for each landing pad site.
280 unsigned DwarfException::
281 ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
282 SmallVectorImpl<ActionEntry> &Actions,
283 SmallVectorImpl<unsigned> &FirstActions) {
285 // The action table follows the call-site table in the LSDA. The individual
286 // records are of two types:
289 // * Exception specification
291 // The two record kinds have the same format, with only small differences.
292 // They are distinguished by the "switch value" field: Catch clauses
293 // (TypeInfos) have strictly positive switch values, and exception
294 // specifications (FilterIds) have strictly negative switch values. Value 0
295 // indicates a catch-all clause.
297 // Negative type IDs index into FilterIds. Positive type IDs index into
298 // TypeInfos. The value written for a positive type ID is just the type ID
299 // itself. For a negative type ID, however, the value written is the
300 // (negative) byte offset of the corresponding FilterIds entry. The byte
301 // offset is usually equal to the type ID (because the FilterIds entries are
302 // written using a variable width encoding, which outputs one byte per entry
303 // as long as the value written is not too large) but can differ. This kind
304 // of complication does not occur for positive type IDs because type infos are
305 // output using a fixed width encoding. FilterOffsets[i] holds the byte
306 // offset corresponding to FilterIds[i].
308 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
309 SmallVector<int, 16> FilterOffsets;
310 FilterOffsets.reserve(FilterIds.size());
313 for (std::vector<unsigned>::const_iterator
314 I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
315 FilterOffsets.push_back(Offset);
316 Offset -= MCAsmInfo::getULEB128Size(*I);
319 FirstActions.reserve(LandingPads.size());
322 unsigned SizeActions = 0;
323 const LandingPadInfo *PrevLPI = 0;
325 for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
326 I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
327 const LandingPadInfo *LPI = *I;
328 const std::vector<int> &TypeIds = LPI->TypeIds;
329 const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
330 unsigned SizeSiteActions = 0;
332 if (NumShared < TypeIds.size()) {
333 unsigned SizeAction = 0;
334 ActionEntry *PrevAction = 0;
337 const unsigned SizePrevIds = PrevLPI->TypeIds.size();
338 assert(Actions.size());
339 PrevAction = &Actions.back();
340 SizeAction = MCAsmInfo::getSLEB128Size(PrevAction->NextAction) +
341 MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
343 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
345 MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
346 SizeAction += -PrevAction->NextAction;
347 PrevAction = PrevAction->Previous;
351 // Compute the actions.
352 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
353 int TypeID = TypeIds[J];
354 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
355 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
356 unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
358 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
359 SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
360 SizeSiteActions += SizeAction;
362 ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
363 Actions.push_back(Action);
364 PrevAction = &Actions.back();
367 // Record the first action of the landing pad site.
368 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
369 } // else identical - re-use previous FirstAction
371 // Information used when created the call-site table. The action record
372 // field of the call site record is the offset of the first associated
373 // action record, relative to the start of the actions table. This value is
374 // biased by 1 (1 in dicating the start of the actions table), and 0
375 // indicates that there are no actions.
376 FirstActions.push_back(FirstAction);
378 // Compute this sites contribution to size.
379 SizeActions += SizeSiteActions;
387 /// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
388 /// has a try-range containing the call, a non-zero landing pad, and an
389 /// appropriate action. The entry for an ordinary call has a try-range
390 /// containing the call and zero for the landing pad and the action. Calls
391 /// marked 'nounwind' have no entry and must not be contained in the try-range
392 /// of any entry - they form gaps in the table. Entries must be ordered by
393 /// try-range address.
394 void DwarfException::
395 ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
396 const RangeMapType &PadMap,
397 const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
398 const SmallVectorImpl<unsigned> &FirstActions) {
399 // The end label of the previous invoke or nounwind try-range.
400 unsigned LastLabel = 0;
402 // Whether there is a potentially throwing instruction (currently this means
403 // an ordinary call) between the end of the previous try-range and now.
404 bool SawPotentiallyThrowing = false;
406 // Whether the last CallSite entry was for an invoke.
407 bool PreviousIsInvoke = false;
409 // Visit all instructions in order of address.
410 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
412 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
414 if (!MI->isLabel()) {
415 SawPotentiallyThrowing |= MI->getDesc().isCall();
419 unsigned BeginLabel = MI->getOperand(0).getImm();
420 assert(BeginLabel && "Invalid label!");
422 // End of the previous try-range?
423 if (BeginLabel == LastLabel)
424 SawPotentiallyThrowing = false;
426 // Beginning of a new try-range?
427 RangeMapType::iterator L = PadMap.find(BeginLabel);
428 if (L == PadMap.end())
429 // Nope, it was just some random label.
432 const PadRange &P = L->second;
433 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
434 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
435 "Inconsistent landing pad map!");
437 // For Dwarf exception handling (SjLj handling doesn't use this). If some
438 // instruction between the previous try-range and this one may throw,
439 // create a call-site entry with no landing pad for the region between the
441 if (SawPotentiallyThrowing &&
442 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
443 CallSiteEntry Site = { LastLabel, BeginLabel, 0, 0 };
444 CallSites.push_back(Site);
445 PreviousIsInvoke = false;
448 LastLabel = LandingPad->EndLabels[P.RangeIndex];
449 assert(BeginLabel && LastLabel && "Invalid landing pad!");
451 if (LandingPad->LandingPadLabel) {
452 // This try-range is for an invoke.
453 CallSiteEntry Site = {
456 LandingPad->LandingPadLabel,
457 FirstActions[P.PadIndex]
460 // Try to merge with the previous call-site. SJLJ doesn't do this
461 if (PreviousIsInvoke &&
462 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
463 CallSiteEntry &Prev = CallSites.back();
464 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
465 // Extend the range of the previous entry.
466 Prev.EndLabel = Site.EndLabel;
471 // Otherwise, create a new call-site.
472 CallSites.push_back(Site);
473 PreviousIsInvoke = true;
476 PreviousIsInvoke = false;
481 // If some instruction between the previous try-range and the end of the
482 // function may throw, create a call-site entry with no landing pad for the
483 // region following the try-range.
484 if (SawPotentiallyThrowing &&
485 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
486 CallSiteEntry Site = { LastLabel, 0, 0, 0 };
487 CallSites.push_back(Site);
491 /// EmitExceptionTable - Emit landing pads and actions.
493 /// The general organization of the table is complex, but the basic concepts are
494 /// easy. First there is a header which describes the location and organization
495 /// of the three components that follow.
497 /// 1. The landing pad site information describes the range of code covered by
498 /// the try. In our case it's an accumulation of the ranges covered by the
499 /// invokes in the try. There is also a reference to the landing pad that
500 /// handles the exception once processed. Finally an index into the actions
502 /// 2. The action table, in our case, is composed of pairs of type IDs and next
503 /// action offset. Starting with the action index from the landing pad
504 /// site, each type ID is checked for a match to the current exception. If
505 /// it matches then the exception and type id are passed on to the landing
506 /// pad. Otherwise the next action is looked up. This chain is terminated
507 /// with a next action of zero. If no type id is found the the frame is
508 /// unwound and handling continues.
509 /// 3. Type ID table contains references to all the C++ typeinfo for all
510 /// catches in the function. This tables is reversed indexed base 1.
511 void DwarfException::EmitExceptionTable() {
512 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
513 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
514 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
515 if (PadInfos.empty()) return;
517 // Sort the landing pads in order of their type ids. This is used to fold
518 // duplicate actions.
519 SmallVector<const LandingPadInfo *, 64> LandingPads;
520 LandingPads.reserve(PadInfos.size());
522 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
523 LandingPads.push_back(&PadInfos[i]);
525 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
527 // Compute the actions table and gather the first action index for each
529 SmallVector<ActionEntry, 32> Actions;
530 SmallVector<unsigned, 64> FirstActions;
531 unsigned SizeActions = ComputeActionsTable(LandingPads, Actions, FirstActions);
533 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
534 // by try-range labels when lowered). Ordinary calls do not, so appropriate
535 // try-ranges for them need be deduced when using Dwarf exception handling.
537 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
538 const LandingPadInfo *LandingPad = LandingPads[i];
539 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
540 unsigned BeginLabel = LandingPad->BeginLabels[j];
541 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
542 PadRange P = { i, j };
543 PadMap[BeginLabel] = P;
547 // Compute the call-site table.
548 SmallVector<CallSiteEntry, 64> CallSites;
549 ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
554 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
555 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
556 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
559 bool HaveTTData = (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
560 ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
563 if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
566 SizeSites = CallSites.size() *
567 (SiteStartSize + SiteLengthSize + LandingPadSize);
568 for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
569 SizeSites += MCAsmInfo::getULEB128Size(CallSites[i].Action);
570 if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
571 SizeSites += MCAsmInfo::getULEB128Size(i);
574 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
575 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
577 unsigned TypeOffset = sizeof(int8_t) + // Call site format
578 MCAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
579 SizeSites + SizeActions + SizeTypes;
581 unsigned TotalSize = sizeof(int8_t) + // LPStart format
582 sizeof(int8_t) + // TType format
584 MCAsmInfo::getULEB128Size(TypeOffset) : 0) + // TType base offset
587 unsigned SizeAlign = (4 - TotalSize) & 3;
589 // Begin the exception table.
590 const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
591 Asm->OutStreamer.SwitchSection(LSDASection);
592 Asm->EmitAlignment(2, 0, 0, false);
593 O << "GCC_except_table" << SubprogramCount << ":\n";
595 for (unsigned i = 0; i != SizeAlign; ++i) {
600 EmitLabel("exception", SubprogramCount);
601 if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
602 std::string SjLjName = "_lsda_";
603 SjLjName += MF->getFunction()->getName().str();
604 EmitLabel(SjLjName.c_str(), 0);
608 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
609 Asm->EOL("@LPStart format (DW_EH_PE_omit)");
612 if (TypeInfos.empty() && FilterIds.empty()) {
613 // If there are no typeinfos or filters, there is nothing to emit, optimize
614 // by specifying the "omit" encoding.
615 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
616 Asm->EOL("@TType format (DW_EH_PE_omit)");
618 // Okay, we have actual filters or typeinfos to emit. As such, we need to
619 // pick a type encoding for them. We're about to emit a list of pointers to
620 // typeinfo objects at the end of the LSDA. However, unless we're in static
621 // mode, this reference will require a relocation by the dynamic linker.
623 // Because of this, we have a couple of options:
624 // 1) If we are in -static mode, we can always use an absolute reference
625 // from the LSDA, because the static linker will resolve it.
626 // 2) Otherwise, if the LSDA section is writable, we can output the direct
627 // reference to the typeinfo and allow the dynamic linker to relocate
628 // it. Since it is in a writable section, the dynamic linker won't
630 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
631 // we need to use some form of indirection. For example, on Darwin,
632 // we can output a statically-relocatable reference to a dyld stub. The
633 // offset to the stub is constant, but the contents are in a section
634 // that is updated by the dynamic linker. This is easy enough, but we
635 // need to tell the personality function of the unwinder to indirect
636 // through the dyld stub.
638 // FIXME: When this is actually implemented, we'll have to emit the stubs
639 // somewhere. This predicate should be moved to a shared location that is
640 // in target-independent code.
642 if (LSDASection->isWritable() ||
643 Asm->TM.getRelocationModel() == Reloc::Static) {
644 Asm->EmitInt8(DW_EH_PE_absptr);
645 Asm->EOL("TType format (DW_EH_PE_absptr)");
647 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_indirect | DW_EH_PE_sdata4);
648 Asm->EOL("TType format (DW_EH_PE_pcrel | DW_EH_PE_indirect"
649 " | DW_EH_PE_sdata4)");
651 Asm->EmitULEB128Bytes(TypeOffset);
652 Asm->EOL("TType base offset");
655 // For SjLj exceptions, if there is no TypeInfo, then we just explicitly
656 // say that we're omitting that bit.
657 // FIXME: does this apply to Dwarf also? The above #if 0 implies yes?
659 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
660 Asm->EOL("@TType format (DW_EH_PE_omit)");
662 Asm->EmitInt8(dwarf::DW_EH_PE_absptr);
663 Asm->EOL("@TType format (DW_EH_PE_absptr)");
664 Asm->EmitULEB128Bytes(TypeOffset);
665 Asm->EOL("@TType base offset");
669 // SjLj Exception handilng
670 if (MAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
671 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
672 Asm->EOL("Call site format (DW_EH_PE_udata4)");
673 Asm->EmitULEB128Bytes(SizeSites);
674 Asm->EOL("Call site table length");
676 // Emit the landing pad site information.
678 for (SmallVectorImpl<CallSiteEntry>::const_iterator
679 I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
680 const CallSiteEntry &S = *I;
682 // Offset of the landing pad, counted in 16-byte bundles relative to the
684 Asm->EmitULEB128Bytes(idx);
685 Asm->EOL("Landing pad");
687 // Offset of the first associated action record, relative to the start of
688 // the action table. This value is biased by 1 (1 indicates the start of
689 // the action table), and 0 indicates that there are no actions.
690 Asm->EmitULEB128Bytes(S.Action);
694 // DWARF Exception handling
695 assert(MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
697 // The call-site table is a list of all call sites that may throw an
698 // exception (including C++ 'throw' statements) in the procedure
699 // fragment. It immediately follows the LSDA header. Each entry indicates,
700 // for a given call, the first corresponding action record and corresponding
703 // The table begins with the number of bytes, stored as an LEB128
704 // compressed, unsigned integer. The records immediately follow the record
705 // count. They are sorted in increasing call-site address. Each record
708 // * The position of the call-site.
709 // * The position of the landing pad.
710 // * The first action record for that call site.
712 // A missing entry in the call-site table indicates that a call is not
713 // supposed to throw. Such calls include:
715 // * Calls to destructors within cleanup code. C++ semantics forbids these
717 // * Calls to intrinsic routines in the standard library which are known
718 // not to throw (sin, memcpy, et al).
720 // If the runtime does not find the call-site entry for a given call, it
721 // will call `terminate()'.
723 // Emit the landing pad call site table.
724 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
725 Asm->EOL("Call site format (DW_EH_PE_udata4)");
726 Asm->EmitULEB128Bytes(SizeSites);
727 Asm->EOL("Call site table size");
729 for (SmallVectorImpl<CallSiteEntry>::const_iterator
730 I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
731 const CallSiteEntry &S = *I;
732 const char *BeginTag;
733 unsigned BeginNumber;
736 BeginTag = "eh_func_begin";
737 BeginNumber = SubprogramCount;
740 BeginNumber = S.BeginLabel;
743 // Offset of the call site relative to the previous call site, counted in
744 // number of 16-byte bundles. The first call site is counted relative to
745 // the start of the procedure fragment.
746 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
748 Asm->EOL("Region start");
751 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
754 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
756 Asm->EOL("Region length");
758 // Offset of the landing pad, counted in 16-byte bundles relative to the
763 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
766 Asm->EOL("Landing pad");
768 // Offset of the first associated action record, relative to the start of
769 // the action table. This value is biased by 1 (1 indicates the start of
770 // the action table), and 0 indicates that there are no actions.
771 Asm->EmitULEB128Bytes(S.Action);
776 // Emit the Action Table.
777 for (SmallVectorImpl<ActionEntry>::const_iterator
778 I = Actions.begin(), E = Actions.end(); I != E; ++I) {
779 const ActionEntry &Action = *I;
783 // Used by the runtime to match the type of the thrown exception to the
784 // type of the catch clauses or the types in the exception specification.
786 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
787 Asm->EOL("TypeInfo index");
791 // Self-relative signed displacement in bytes of the next action record,
792 // or 0 if there is no next action record.
794 Asm->EmitSLEB128Bytes(Action.NextAction);
795 Asm->EOL("Next action");
798 // Emit the Catch Clauses. The code for the catch clauses following the same
799 // try is similar to a switch statement. The catch clause action record
800 // informs the runtime about the type of a catch clause and about the
801 // associated switch value.
803 // Action Record Fields:
806 // Positive value, starting at 1. Index in the types table of the
807 // __typeinfo for the catch-clause type. 1 is the first word preceding
808 // TTBase, 2 is the second word, and so on. Used by the runtime to check
809 // if the thrown exception type matches the catch-clause type. Back-end
810 // generated switch statements check against this value.
813 // Signed offset, in bytes from the start of this field, to the next
814 // chained action record, or zero if none.
816 // The order of the action records determined by the next field is the order
817 // of the catch clauses as they appear in the source code, and must be kept in
818 // the same order. As a result, changing the order of the catch clause would
819 // change the semantics of the program.
820 for (std::vector<GlobalVariable *>::const_reverse_iterator
821 I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
822 const GlobalVariable *GV = *I;
827 O << Asm->getGlobalLinkName(GV, GLN);
832 Asm->EOL("TypeInfo");
835 // Emit the Type Table.
836 for (std::vector<unsigned>::const_iterator
837 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
838 unsigned TypeID = *I;
839 Asm->EmitULEB128Bytes(TypeID);
840 Asm->EOL("Filter TypeInfo index");
843 Asm->EmitAlignment(2, 0, 0, false);
846 /// EndModule - Emit all exception information that should come after the
848 void DwarfException::EndModule() {
849 if (MAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
851 if (TimePassesIsEnabled)
852 ExceptionTimer->startTimer();
854 if (shouldEmitMovesModule || shouldEmitTableModule) {
855 const std::vector<Function *> Personalities = MMI->getPersonalities();
856 for (unsigned i = 0; i < Personalities.size(); ++i)
857 EmitCIE(Personalities[i], i);
859 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
860 E = EHFrames.end(); I != E; ++I)
864 if (TimePassesIsEnabled)
865 ExceptionTimer->stopTimer();
868 /// BeginFunction - Gather pre-function exception information. Assumes being
869 /// emitted immediately after the function entry point.
870 void DwarfException::BeginFunction(MachineFunction *MF) {
871 if (TimePassesIsEnabled)
872 ExceptionTimer->startTimer();
875 shouldEmitTable = shouldEmitMoves = false;
877 if (MMI && MAI->doesSupportExceptionHandling()) {
878 // Map all labels and get rid of any dead landing pads.
879 MMI->TidyLandingPads();
881 // If any landing pads survive, we need an EH table.
882 if (MMI->getLandingPads().size())
883 shouldEmitTable = true;
885 // See if we need frame move info.
886 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
887 shouldEmitMoves = true;
889 if (shouldEmitMoves || shouldEmitTable)
890 // Assumes in correct section after the entry point.
891 EmitLabel("eh_func_begin", ++SubprogramCount);
894 shouldEmitTableModule |= shouldEmitTable;
895 shouldEmitMovesModule |= shouldEmitMoves;
897 if (TimePassesIsEnabled)
898 ExceptionTimer->stopTimer();
901 /// EndFunction - Gather and emit post-function exception information.
903 void DwarfException::EndFunction() {
904 if (TimePassesIsEnabled)
905 ExceptionTimer->startTimer();
907 if (shouldEmitMoves || shouldEmitTable) {
908 EmitLabel("eh_func_end", SubprogramCount);
909 EmitExceptionTable();
911 // Save EH frame information
913 FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
915 MMI->getPersonalityIndex(),
916 MF->getFrameInfo()->hasCalls(),
917 !MMI->getLandingPads().empty(),
918 MMI->getFrameMoves(),
922 if (TimePassesIsEnabled)
923 ExceptionTimer->stopTimer();