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/MachineLocation.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/Target/TargetAsmInfo.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetFrameInfo.h"
23 #include "llvm/Target/TargetLoweringObjectFile.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/Timer.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/StringExtras.h"
32 static TimerGroup &getDwarfTimerGroup() {
33 static TimerGroup DwarfTimerGroup("Dwarf Exception");
34 return DwarfTimerGroup;
37 DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A,
38 const TargetAsmInfo *T)
39 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
40 shouldEmitTableModule(false), shouldEmitMovesModule(false),
42 if (TimePassesIsEnabled)
43 ExceptionTimer = new Timer("Dwarf Exception Writer",
44 getDwarfTimerGroup());
47 DwarfException::~DwarfException() {
48 delete ExceptionTimer;
51 void DwarfException::EmitCommonEHFrame(const Function *Personality,
53 // Size and sign of stack growth.
55 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
56 TargetFrameInfo::StackGrowsUp ?
57 TD->getPointerSize() : -TD->getPointerSize();
59 // Begin eh frame section.
60 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
62 if (TAI->is_EHSymbolPrivate())
63 O << TAI->getPrivateGlobalPrefix();
65 O << "EH_frame" << Index << ":\n";
66 EmitLabel("section_eh_frame", Index);
68 // Define base labels.
69 EmitLabel("eh_frame_common", Index);
71 // Define the eh frame length.
72 EmitDifference("eh_frame_common_end", Index,
73 "eh_frame_common_begin", Index, true);
74 Asm->EOL("Length of Common Information Entry");
77 EmitLabel("eh_frame_common_begin", Index);
78 Asm->EmitInt32((int)0);
79 Asm->EOL("CIE Identifier Tag");
80 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
81 Asm->EOL("CIE Version");
83 // The personality presence indicates that language specific information will
84 // show up in the eh frame.
85 Asm->EmitString(Personality ? "zPLR" : "zR");
86 Asm->EOL("CIE Augmentation");
89 Asm->EmitULEB128Bytes(1);
90 Asm->EOL("CIE Code Alignment Factor");
91 Asm->EmitSLEB128Bytes(stackGrowth);
92 Asm->EOL("CIE Data Alignment Factor");
93 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
94 Asm->EOL("CIE Return Address Column");
96 // If there is a personality, we need to indicate the functions location.
98 Asm->EmitULEB128Bytes(7);
99 Asm->EOL("Augmentation Size");
101 if (TAI->getNeedsIndirectEncoding()) {
102 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 |
103 dwarf::DW_EH_PE_indirect);
104 Asm->EOL("Personality (pcrel sdata4 indirect)");
106 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
107 Asm->EOL("Personality (pcrel sdata4)");
110 PrintRelDirective(true);
111 O << TAI->getPersonalityPrefix();
112 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
113 O << TAI->getPersonalitySuffix();
114 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
115 O << "-" << TAI->getPCSymbol();
116 Asm->EOL("Personality");
118 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
119 Asm->EOL("LSDA Encoding (pcrel sdata4)");
121 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
122 Asm->EOL("FDE Encoding (pcrel sdata4)");
124 Asm->EmitULEB128Bytes(1);
125 Asm->EOL("Augmentation Size");
127 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
128 Asm->EOL("FDE Encoding (pcrel sdata4)");
131 // Indicate locations of general callee saved registers in frame.
132 std::vector<MachineMove> Moves;
133 RI->getInitialFrameState(Moves);
134 EmitFrameMoves(NULL, 0, Moves, true);
136 // On Darwin the linker honors the alignment of eh_frame, which means it must
137 // be 8-byte on 64-bit targets to match what gcc does. Otherwise you get
138 // holes which confuse readers of eh_frame.
139 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
141 EmitLabel("eh_frame_common_end", Index);
146 /// EmitEHFrame - Emit function exception frame information.
148 void DwarfException::EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
149 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
150 "Should not emit 'available externally' functions at all");
152 const Function *TheFunc = EHFrameInfo.function;
154 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
156 // Externally visible entry into the functions eh frame info. If the
157 // corresponding function is static, this should not be externally visible.
158 if (!TheFunc->hasLocalLinkage())
159 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
160 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
162 // If corresponding function is weak definition, this should be too.
163 if (TheFunc->isWeakForLinker() && TAI->getWeakDefDirective())
164 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
166 // If there are no calls then you can't unwind. This may mean we can omit the
167 // EH Frame, but some environments do not handle weak absolute symbols. If
168 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
169 // info is to be available for non-EH uses.
170 if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
171 (!TheFunc->isWeakForLinker() ||
172 !TAI->getWeakDefDirective() ||
173 TAI->getSupportsWeakOmittedEHFrame())) {
174 O << EHFrameInfo.FnName << " = 0\n";
175 // This name has no connection to the function, so it might get
176 // dead-stripped when the function is not, erroneously. Prohibit
177 // dead-stripping unconditionally.
178 if (const char *UsedDirective = TAI->getUsedDirective())
179 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
181 O << EHFrameInfo.FnName << ":\n";
184 EmitDifference("eh_frame_end", EHFrameInfo.Number,
185 "eh_frame_begin", EHFrameInfo.Number, true);
186 Asm->EOL("Length of Frame Information Entry");
188 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
190 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
191 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
194 Asm->EOL("FDE CIE offset");
196 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
197 Asm->EOL("FDE initial location");
198 EmitDifference("eh_func_end", EHFrameInfo.Number,
199 "eh_func_begin", EHFrameInfo.Number, true);
200 Asm->EOL("FDE address range");
202 // If there is a personality and landing pads then point to the language
203 // specific data area in the exception table.
204 if (EHFrameInfo.PersonalityIndex) {
205 Asm->EmitULEB128Bytes(4);
206 Asm->EOL("Augmentation size");
208 if (EHFrameInfo.hasLandingPads)
209 EmitReference("exception", EHFrameInfo.Number, true, true);
211 Asm->EmitInt32((int)0);
212 Asm->EOL("Language Specific Data Area");
214 Asm->EmitULEB128Bytes(0);
215 Asm->EOL("Augmentation size");
218 // Indicate locations of function specific callee saved registers in frame.
219 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
222 // On Darwin the linker honors the alignment of eh_frame, which means it
223 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
224 // get holes which confuse readers of eh_frame.
225 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
227 EmitLabel("eh_frame_end", EHFrameInfo.Number);
229 // If the function is marked used, this table should be also. We cannot
230 // make the mark unconditional in this case, since retaining the table also
231 // retains the function in this case, and there is code around that depends
232 // on unused functions (calling undefined externals) being dead-stripped to
233 // link correctly. Yes, there really is.
234 if (MMI->isUsedFunction(EHFrameInfo.function))
235 if (const char *UsedDirective = TAI->getUsedDirective())
236 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
240 /// SharedTypeIds - How many leading type ids two landing pads have in common.
241 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
242 const LandingPadInfo *R) {
243 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
244 unsigned LSize = LIds.size(), RSize = RIds.size();
245 unsigned MinSize = LSize < RSize ? LSize : RSize;
248 for (; Count != MinSize; ++Count)
249 if (LIds[Count] != RIds[Count])
255 /// PadLT - Order landing pads lexicographically by type id.
256 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
257 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
258 unsigned LSize = LIds.size(), RSize = RIds.size();
259 unsigned MinSize = LSize < RSize ? LSize : RSize;
261 for (unsigned i = 0; i != MinSize; ++i)
262 if (LIds[i] != RIds[i])
263 return LIds[i] < RIds[i];
265 return LSize < RSize;
268 /// ComputeActionsTable - Compute the actions table and gather the first action
269 /// index for each landing pad site.
270 unsigned DwarfException::
271 ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
272 SmallVectorImpl<ActionEntry> &Actions,
273 SmallVectorImpl<unsigned> &FirstActions) {
274 // Negative type IDs index into FilterIds. Positive type IDs index into
275 // TypeInfos. The value written for a positive type ID is just the type ID
276 // itself. For a negative type ID, however, the value written is the
277 // (negative) byte offset of the corresponding FilterIds entry. The byte
278 // offset is usually equal to the type ID (because the FilterIds entries are
279 // written using a variable width encoding, which outputs one byte per entry
280 // as long as the value written is not too large) but can differ. This kind
281 // of complication does not occur for positive type IDs because type infos are
282 // output using a fixed width encoding. FilterOffsets[i] holds the byte
283 // offset corresponding to FilterIds[i].
285 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
286 SmallVector<int, 16> FilterOffsets;
287 FilterOffsets.reserve(FilterIds.size());
290 for (std::vector<unsigned>::const_iterator
291 I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
292 FilterOffsets.push_back(Offset);
293 Offset -= TargetAsmInfo::getULEB128Size(*I);
296 FirstActions.reserve(LandingPads.size());
299 unsigned SizeActions = 0;
300 const LandingPadInfo *PrevLPI = 0;
302 for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
303 I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
304 const LandingPadInfo *LPI = *I;
305 const std::vector<int> &TypeIds = LPI->TypeIds;
306 const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
307 unsigned SizeSiteActions = 0;
309 if (NumShared < TypeIds.size()) {
310 unsigned SizeAction = 0;
311 ActionEntry *PrevAction = 0;
314 const unsigned SizePrevIds = PrevLPI->TypeIds.size();
315 assert(Actions.size());
316 PrevAction = &Actions.back();
317 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
318 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
320 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
322 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
323 SizeAction += -PrevAction->NextAction;
324 PrevAction = PrevAction->Previous;
328 // Compute the actions.
329 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
330 int TypeID = TypeIds[J];
331 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
332 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
333 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
335 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
336 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
337 SizeSiteActions += SizeAction;
339 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
340 Actions.push_back(Action);
341 PrevAction = &Actions.back();
344 // Record the first action of the landing pad site.
345 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
346 } // else identical - re-use previous FirstAction
348 FirstActions.push_back(FirstAction);
350 // Compute this sites contribution to size.
351 SizeActions += SizeSiteActions;
359 /// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
360 /// has a try-range containing the call, a non-zero landing pad and an
361 /// appropriate action. The entry for an ordinary call has a try-range
362 /// containing the call and zero for the landing pad and the action. Calls
363 /// marked 'nounwind' have no entry and must not be contained in the try-range
364 /// of any entry - they form gaps in the table. Entries must be ordered by
365 /// try-range address.
366 void DwarfException::
367 ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
368 const RangeMapType &PadMap,
369 const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
370 const SmallVectorImpl<unsigned> &FirstActions) {
371 // The end label of the previous invoke or nounwind try-range.
372 unsigned LastLabel = 0;
374 // Whether there is a potentially throwing instruction (currently this means
375 // an ordinary call) between the end of the previous try-range and now.
376 bool SawPotentiallyThrowing = false;
378 // Whether the last CallSite entry was for an invoke.
379 bool PreviousIsInvoke = false;
381 // Visit all instructions in order of address.
382 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
384 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
386 if (!MI->isLabel()) {
387 SawPotentiallyThrowing |= MI->getDesc().isCall();
391 unsigned BeginLabel = MI->getOperand(0).getImm();
392 assert(BeginLabel && "Invalid label!");
394 // End of the previous try-range?
395 if (BeginLabel == LastLabel)
396 SawPotentiallyThrowing = false;
398 // Beginning of a new try-range?
399 RangeMapType::iterator L = PadMap.find(BeginLabel);
400 if (L == PadMap.end())
401 // Nope, it was just some random label.
404 PadRange P = L->second;
405 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
406 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
407 "Inconsistent landing pad map!");
409 // For Dwarf exception handling (SjLj handling doesn't use this)
410 // If some instruction between the previous try-range and this one may
411 // throw, create a call-site entry with no landing pad for the region
412 // between the try-ranges.
413 if (SawPotentiallyThrowing &&
414 TAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
415 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
416 CallSites.push_back(Site);
417 PreviousIsInvoke = false;
420 LastLabel = LandingPad->EndLabels[P.RangeIndex];
421 assert(BeginLabel && LastLabel && "Invalid landing pad!");
423 if (LandingPad->LandingPadLabel) {
424 // This try-range is for an invoke.
425 CallSiteEntry Site = {BeginLabel, LastLabel,
426 LandingPad->LandingPadLabel,
427 FirstActions[P.PadIndex]};
429 // Try to merge with the previous call-site.
430 if (PreviousIsInvoke) {
431 CallSiteEntry &Prev = CallSites.back();
432 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
433 // Extend the range of the previous entry.
434 Prev.EndLabel = Site.EndLabel;
439 // Otherwise, create a new call-site.
440 CallSites.push_back(Site);
441 PreviousIsInvoke = true;
444 PreviousIsInvoke = false;
449 // If some instruction between the previous try-range and the end of the
450 // function may throw, create a call-site entry with no landing pad for the
451 // region following the try-range.
452 if (SawPotentiallyThrowing &&
453 TAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
454 CallSiteEntry Site = {LastLabel, 0, 0, 0};
455 CallSites.push_back(Site);
459 /// EmitExceptionTable - Emit landing pads and actions.
461 /// The general organization of the table is complex, but the basic concepts are
462 /// easy. First there is a header which describes the location and organization
463 /// of the three components that follow.
465 /// 1. The landing pad site information describes the range of code covered by
466 /// the try. In our case it's an accumulation of the ranges covered by the
467 /// invokes in the try. There is also a reference to the landing pad that
468 /// handles the exception once processed. Finally an index into the actions
470 /// 2. The action table, in our case, is composed of pairs of type ids and next
471 /// action offset. Starting with the action index from the landing pad
472 /// site, each type Id is checked for a match to the current exception. If
473 /// it matches then the exception and type id are passed on to the landing
474 /// pad. Otherwise the next action is looked up. This chain is terminated
475 /// with a next action of zero. If no type id is found the the frame is
476 /// unwound and handling continues.
477 /// 3. Type id table contains references to all the C++ typeinfo for all
478 /// catches in the function. This tables is reversed indexed base 1.
479 void DwarfException::EmitExceptionTable() {
480 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
481 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
482 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
483 if (PadInfos.empty()) return;
485 // Sort the landing pads in order of their type ids. This is used to fold
486 // duplicate actions.
487 SmallVector<const LandingPadInfo *, 64> LandingPads;
488 LandingPads.reserve(PadInfos.size());
490 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
491 LandingPads.push_back(&PadInfos[i]);
493 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
495 // Compute the actions table and gather the first action index for each
497 SmallVector<ActionEntry, 32> Actions;
498 SmallVector<unsigned, 64> FirstActions;
499 unsigned SizeActions = ComputeActionsTable(LandingPads, Actions, FirstActions);
501 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
502 // by try-range labels when lowered). Ordinary calls do not, so appropriate
503 // try-ranges for them need be deduced when using Dwarf exception handling.
505 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
506 const LandingPadInfo *LandingPad = LandingPads[i];
507 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
508 unsigned BeginLabel = LandingPad->BeginLabels[j];
509 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
510 PadRange P = { i, j };
511 PadMap[BeginLabel] = P;
515 // Compute the call-site table.
516 SmallVector<CallSiteEntry, 64> CallSites;
517 ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
522 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
523 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
524 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
527 bool HaveTTData = (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
528 ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
531 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
534 SizeSites = CallSites.size() *
535 (SiteStartSize + SiteLengthSize + LandingPadSize);
536 for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
537 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
538 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
539 SizeSites += TargetAsmInfo::getULEB128Size(i);
542 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
543 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
545 unsigned TypeOffset = sizeof(int8_t) + // Call site format
546 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
547 SizeSites + SizeActions + SizeTypes;
549 unsigned TotalSize = sizeof(int8_t) + // LPStart format
550 sizeof(int8_t) + // TType format
552 TargetAsmInfo::getULEB128Size(TypeOffset) : 0) + // TType base offset
555 unsigned SizeAlign = (4 - TotalSize) & 3;
557 // Begin the exception table.
558 const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
559 Asm->OutStreamer.SwitchSection(LSDASection);
560 Asm->EmitAlignment(2, 0, 0, false);
561 O << "GCC_except_table" << SubprogramCount << ":\n";
563 for (unsigned i = 0; i != SizeAlign; ++i) {
568 EmitLabel("exception", SubprogramCount);
569 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
570 std::string SjLjName = "_lsda_";
571 SjLjName += MF->getFunction()->getName().str();
572 EmitLabel(SjLjName.c_str(), 0);
576 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
577 Asm->EOL("LPStart format (DW_EH_PE_omit)");
580 if (TypeInfos.empty() && FilterIds.empty()) {
581 // If there are no typeinfos or filters, there is nothing to emit, optimize
582 // by specifying the "omit" encoding.
583 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
584 Asm->EOL("TType format (DW_EH_PE_omit)");
586 // Okay, we have actual filters or typeinfos to emit. As such, we need to
587 // pick a type encoding for them. We're about to emit a list of pointers to
588 // typeinfo objects at the end of the LSDA. However, unless we're in static
589 // mode, this reference will require a relocation by the dynamic linker.
591 // Because of this, we have a couple of options:
592 // 1) If we are in -static mode, we can always use an absolute reference
593 // from the LSDA, because the static linker will resolve it.
594 // 2) Otherwise, if the LSDA section is writable, we can output the direct
595 // reference to the typeinfo and allow the dynamic linker to relocate
596 // it. Since it is in a writable section, the dynamic linker won't
598 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
599 // we need to use some form of indirection. For example, on Darwin,
600 // we can output a statically-relocatable reference to a dyld stub. The
601 // offset to the stub is constant, but the contents are in a section
602 // that is updated by the dynamic linker. This is easy enough, but we
603 // need to tell the personality function of the unwinder to indirect
604 // through the dyld stub.
606 // FIXME: When this is actually implemented, we'll have to emit the stubs
607 // somewhere. This predicate should be moved to a shared location that is
608 // in target-independent code.
610 if (LSDASection->isWritable() ||
611 Asm->TM.getRelocationModel() == Reloc::Static) {
612 Asm->EmitInt8(DW_EH_PE_absptr);
613 Asm->EOL("TType format (DW_EH_PE_absptr)");
615 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_indirect | DW_EH_PE_sdata4);
616 Asm->EOL("TType format (DW_EH_PE_pcrel | DW_EH_PE_indirect"
617 " | DW_EH_PE_sdata4)");
619 Asm->EmitULEB128Bytes(TypeOffset);
620 Asm->EOL("TType base offset");
623 // For SjLj exceptions, if there is no TypeInfo, then we just explicitly
624 // say that we're omitting that bit.
625 // FIXME: does this apply to Dwarf also? The above #if 0 implies yes?
627 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
628 Asm->EOL("TType format (DW_EH_PE_omit)");
630 Asm->EmitInt8(dwarf::DW_EH_PE_absptr);
631 Asm->EOL("TType format (DW_EH_PE_absptr)");
632 Asm->EmitULEB128Bytes(TypeOffset);
633 Asm->EOL("TType base offset");
637 // SjLj Exception handilng
638 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
639 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
640 Asm->EOL("Call site format (DW_EH_PE_udata4)");
641 Asm->EmitULEB128Bytes(SizeSites);
642 Asm->EOL("Call-site table length");
644 // Emit the landing pad site information.
646 for (SmallVectorImpl<CallSiteEntry>::const_iterator
647 I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
648 const CallSiteEntry &S = *I;
649 Asm->EmitULEB128Bytes(idx);
650 Asm->EOL("Landing pad");
651 Asm->EmitULEB128Bytes(S.Action);
655 // DWARF Exception handling
656 assert(TAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
658 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
659 Asm->EOL("Call site format (DW_EH_PE_udata4)");
660 Asm->EmitULEB128Bytes(SizeSites);
661 Asm->EOL("Call-site table length");
663 // Emit the landing pad site information.
664 for (SmallVectorImpl<CallSiteEntry>::const_iterator
665 I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
666 const CallSiteEntry &S = *I;
667 const char *BeginTag;
668 unsigned BeginNumber;
671 BeginTag = "eh_func_begin";
672 BeginNumber = SubprogramCount;
675 BeginNumber = S.BeginLabel;
678 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
680 Asm->EOL("Region start");
683 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
686 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
688 Asm->EOL("Region length");
693 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
696 Asm->EOL("Landing pad");
698 Asm->EmitULEB128Bytes(S.Action);
704 for (SmallVectorImpl<ActionEntry>::const_iterator
705 I = Actions.begin(), E = Actions.end(); I != E; ++I) {
706 const ActionEntry &Action = *I;
707 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
708 Asm->EOL("TypeInfo index");
709 Asm->EmitSLEB128Bytes(Action.NextAction);
710 Asm->EOL("Next action");
713 // Emit the type ids.
714 for (std::vector<GlobalVariable *>::const_reverse_iterator
715 I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
716 GlobalVariable *GV = *I;
721 O << Asm->getGlobalLinkName(GV, GLN);
726 Asm->EOL("TypeInfo");
729 // Emit the filter typeids.
730 for (std::vector<unsigned>::const_iterator
731 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
732 unsigned TypeID = *I;
733 Asm->EmitULEB128Bytes(TypeID);
734 Asm->EOL("Filter TypeInfo index");
737 Asm->EmitAlignment(2, 0, 0, false);
740 /// EndModule - Emit all exception information that should come after the
742 void DwarfException::EndModule() {
743 if (TAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
745 if (TimePassesIsEnabled)
746 ExceptionTimer->startTimer();
748 if (shouldEmitMovesModule || shouldEmitTableModule) {
749 const std::vector<Function *> Personalities = MMI->getPersonalities();
750 for (unsigned i = 0; i < Personalities.size(); ++i)
751 EmitCommonEHFrame(Personalities[i], i);
753 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
754 E = EHFrames.end(); I != E; ++I)
758 if (TimePassesIsEnabled)
759 ExceptionTimer->stopTimer();
762 /// BeginFunction - Gather pre-function exception information. Assumes being
763 /// emitted immediately after the function entry point.
764 void DwarfException::BeginFunction(MachineFunction *MF) {
765 if (TimePassesIsEnabled)
766 ExceptionTimer->startTimer();
769 shouldEmitTable = shouldEmitMoves = false;
771 if (MMI && TAI->doesSupportExceptionHandling()) {
772 // Map all labels and get rid of any dead landing pads.
773 MMI->TidyLandingPads();
775 // If any landing pads survive, we need an EH table.
776 if (MMI->getLandingPads().size())
777 shouldEmitTable = true;
779 // See if we need frame move info.
780 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
781 shouldEmitMoves = true;
783 if (shouldEmitMoves || shouldEmitTable)
784 // Assumes in correct section after the entry point.
785 EmitLabel("eh_func_begin", ++SubprogramCount);
788 shouldEmitTableModule |= shouldEmitTable;
789 shouldEmitMovesModule |= shouldEmitMoves;
791 if (TimePassesIsEnabled)
792 ExceptionTimer->stopTimer();
795 /// EndFunction - Gather and emit post-function exception information.
797 void DwarfException::EndFunction() {
798 if (TimePassesIsEnabled)
799 ExceptionTimer->startTimer();
801 if (shouldEmitMoves || shouldEmitTable) {
802 EmitLabel("eh_func_end", SubprogramCount);
803 EmitExceptionTable();
805 // Save EH frame information
807 FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
809 MMI->getPersonalityIndex(),
810 MF->getFrameInfo()->hasCalls(),
811 !MMI->getLandingPads().empty(),
812 MMI->getFrameMoves(),
816 if (TimePassesIsEnabled)
817 ExceptionTimer->stopTimer();