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/MCAsmInfo.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCSection.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/Target/Mangler.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetFrameInfo.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Timer.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/Twine.h"
40 DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A,
42 : DwarfPrinter(OS, A, T, "eh"), shouldEmitTable(false),shouldEmitMoves(false),
43 shouldEmitTableModule(false), shouldEmitMovesModule(false),
45 if (TimePassesIsEnabled)
46 ExceptionTimer = new Timer("DWARF Exception Writer");
49 DwarfException::~DwarfException() {
50 delete ExceptionTimer;
53 /// CreateLabelDiff - Emit a label and subtract it from the expression we
54 /// already have. This is equivalent to emitting "foo - .", but we have to emit
55 /// the label for "." directly.
56 const MCExpr *DwarfException::CreateLabelDiff(const MCExpr *ExprRef,
57 const char *LabelName,
60 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix()
61 << LabelName << Asm->getFunctionNumber()
63 MCSymbol *DotSym = Asm->OutContext.GetOrCreateSymbol(Name.str());
64 Asm->OutStreamer.EmitLabel(DotSym);
66 return MCBinaryExpr::CreateSub(ExprRef,
67 MCSymbolRefExpr::Create(DotSym,
72 /// EmitCIE - Emit a Common Information Entry (CIE). This holds information that
73 /// is shared among many Frame Description Entries. There is at least one CIE
74 /// in every non-empty .debug_frame section.
75 void DwarfException::EmitCIE(const Function *PersonalityFn, unsigned Index) {
76 // Size and sign of stack growth.
78 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
79 TargetFrameInfo::StackGrowsUp ?
80 TD->getPointerSize() : -TD->getPointerSize();
82 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
84 // Begin eh frame section.
85 Asm->OutStreamer.SwitchSection(TLOF.getEHFrameSection());
87 if (MAI->is_EHSymbolPrivate())
88 O << MAI->getPrivateGlobalPrefix();
89 O << "EH_frame" << Index << ":\n";
91 EmitLabel("section_eh_frame", Index);
93 // Define base labels.
94 EmitLabel("eh_frame_common", Index);
96 // Define the eh frame length.
97 EmitDifference("eh_frame_common_end", Index,
98 "eh_frame_common_begin", Index, true);
99 EOL("Length of Common Information Entry");
102 EmitLabel("eh_frame_common_begin", Index);
103 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("CIE Identifier Tag");
104 Asm->OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
105 if (Asm->VerboseAsm) Asm->OutStreamer.AddComment("DW_CIE_VERSION");
106 Asm->OutStreamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1/*size*/, 0/*addr*/);
108 // The personality presence indicates that language specific information will
109 // show up in the eh frame. Find out how we are supposed to lower the
110 // personality function reference:
112 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
113 unsigned FDEEncoding = TLOF.getFDEEncoding();
114 unsigned PerEncoding = TLOF.getPersonalityEncoding();
116 char Augmentation[6] = { 0 };
117 unsigned AugmentationSize = 0;
118 char *APtr = Augmentation + 1;
121 // There is a personality function.
123 AugmentationSize += 1 + SizeOfEncodedValue(PerEncoding);
126 if (UsesLSDA[Index]) {
127 // An LSDA pointer is in the FDE augmentation.
132 if (FDEEncoding != dwarf::DW_EH_PE_absptr) {
133 // A non-default pointer encoding for the FDE.
138 if (APtr != Augmentation + 1)
139 Augmentation[0] = 'z';
141 Asm->OutStreamer.EmitBytes(StringRef(Augmentation, strlen(Augmentation)+1),0);
142 EOL("CIE Augmentation");
145 EmitULEB128(1, "CIE Code Alignment Factor");
146 EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
147 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
148 EOL("CIE Return Address Column");
150 EmitULEB128(AugmentationSize, "Augmentation Size");
152 // If there is a personality, we need to indicate the function's location.
154 EmitEncodingByte(PerEncoding, "Personality");
155 EmitReference(PersonalityFn, PerEncoding);
158 EmitEncodingByte(LSDAEncoding, "LSDA");
159 if (FDEEncoding != dwarf::DW_EH_PE_absptr)
160 EmitEncodingByte(FDEEncoding, "FDE");
163 // Indicate locations of general callee saved registers in frame.
164 std::vector<MachineMove> Moves;
165 RI->getInitialFrameState(Moves);
166 EmitFrameMoves(NULL, 0, Moves, true);
168 // On Darwin the linker honors the alignment of eh_frame, which means it must
169 // be 8-byte on 64-bit targets to match what gcc does. Otherwise you get
170 // holes which confuse readers of eh_frame.
171 Asm->EmitAlignment(TD->getPointerSize() == 4 ? 2 : 3, 0, 0, false);
172 EmitLabel("eh_frame_common_end", Index);
176 /// EmitFDE - Emit the Frame Description Entry (FDE) for the function.
177 void DwarfException::EmitFDE(const FunctionEHFrameInfo &EHFrameInfo) {
178 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
179 "Should not emit 'available externally' functions at all");
181 const Function *TheFunc = EHFrameInfo.function;
182 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
184 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
185 unsigned FDEEncoding = TLOF.getFDEEncoding();
187 Asm->OutStreamer.SwitchSection(TLOF.getEHFrameSection());
189 // Externally visible entry into the functions eh frame info. If the
190 // corresponding function is static, this should not be externally visible.
191 if (!TheFunc->hasLocalLinkage())
192 if (const char *GlobalEHDirective = MAI->getGlobalEHDirective())
193 O << GlobalEHDirective << *EHFrameInfo.FunctionEHSym << '\n';
195 // If corresponding function is weak definition, this should be too.
196 if (TheFunc->isWeakForLinker() && MAI->getWeakDefDirective())
197 O << MAI->getWeakDefDirective() << *EHFrameInfo.FunctionEHSym << '\n';
199 // If corresponding function is hidden, this should be too.
200 if (TheFunc->hasHiddenVisibility())
201 if (MCSymbolAttr HiddenAttr = MAI->getHiddenVisibilityAttr())
202 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
205 // If there are no calls then you can't unwind. This may mean we can omit the
206 // EH Frame, but some environments do not handle weak absolute symbols. If
207 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
208 // info is to be available for non-EH uses.
209 if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
210 (!TheFunc->isWeakForLinker() ||
211 !MAI->getWeakDefDirective() ||
212 MAI->getSupportsWeakOmittedEHFrame())) {
213 O << *EHFrameInfo.FunctionEHSym << " = 0\n";
214 // This name has no connection to the function, so it might get
215 // dead-stripped when the function is not, erroneously. Prohibit
216 // dead-stripping unconditionally.
217 if (MAI->hasNoDeadStrip())
218 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
221 O << *EHFrameInfo.FunctionEHSym << ":\n";
224 EmitDifference("eh_frame_end", EHFrameInfo.Number,
225 "eh_frame_begin", EHFrameInfo.Number,
227 EOL("Length of Frame Information Entry");
229 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
231 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
232 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
235 EOL("FDE CIE offset");
237 EmitReference("eh_func_begin", EHFrameInfo.Number, FDEEncoding);
238 EOL("FDE initial location");
239 EmitDifference("eh_func_end", EHFrameInfo.Number,
240 "eh_func_begin", EHFrameInfo.Number,
241 SizeOfEncodedValue(FDEEncoding) == 4);
242 EOL("FDE address range");
244 // If there is a personality and landing pads then point to the language
245 // specific data area in the exception table.
246 if (MMI->getPersonalities()[0] != NULL) {
247 unsigned Size = SizeOfEncodedValue(LSDAEncoding);
249 EmitULEB128(Size, "Augmentation size");
250 if (EHFrameInfo.hasLandingPads)
251 EmitReference("exception", EHFrameInfo.Number, LSDAEncoding);
253 Asm->OutStreamer.EmitIntValue(0, Size/*size*/, 0/*addrspace*/);
255 EOL("Language Specific Data Area");
257 EmitULEB128(0, "Augmentation size");
260 // Indicate locations of function specific callee saved registers in frame.
261 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
264 // On Darwin the linker honors the alignment of eh_frame, which means it
265 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
266 // get holes which confuse readers of eh_frame.
267 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
269 EmitLabel("eh_frame_end", EHFrameInfo.Number);
271 // If the function is marked used, this table should be also. We cannot
272 // make the mark unconditional in this case, since retaining the table also
273 // retains the function in this case, and there is code around that depends
274 // on unused functions (calling undefined externals) being dead-stripped to
275 // link correctly. Yes, there really is.
276 if (MMI->isUsedFunction(EHFrameInfo.function))
277 if (MAI->hasNoDeadStrip())
278 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
284 /// SharedTypeIds - How many leading type ids two landing pads have in common.
285 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
286 const LandingPadInfo *R) {
287 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
288 unsigned LSize = LIds.size(), RSize = RIds.size();
289 unsigned MinSize = LSize < RSize ? LSize : RSize;
292 for (; Count != MinSize; ++Count)
293 if (LIds[Count] != RIds[Count])
299 /// PadLT - Order landing pads lexicographically by type id.
300 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
301 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
302 unsigned LSize = LIds.size(), RSize = RIds.size();
303 unsigned MinSize = LSize < RSize ? LSize : RSize;
305 for (unsigned i = 0; i != MinSize; ++i)
306 if (LIds[i] != RIds[i])
307 return LIds[i] < RIds[i];
309 return LSize < RSize;
312 /// ComputeActionsTable - Compute the actions table and gather the first action
313 /// index for each landing pad site.
314 unsigned DwarfException::
315 ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
316 SmallVectorImpl<ActionEntry> &Actions,
317 SmallVectorImpl<unsigned> &FirstActions) {
319 // The action table follows the call-site table in the LSDA. The individual
320 // records are of two types:
323 // * Exception specification
325 // The two record kinds have the same format, with only small differences.
326 // They are distinguished by the "switch value" field: Catch clauses
327 // (TypeInfos) have strictly positive switch values, and exception
328 // specifications (FilterIds) have strictly negative switch values. Value 0
329 // indicates a catch-all clause.
331 // Negative type IDs index into FilterIds. Positive type IDs index into
332 // TypeInfos. The value written for a positive type ID is just the type ID
333 // itself. For a negative type ID, however, the value written is the
334 // (negative) byte offset of the corresponding FilterIds entry. The byte
335 // offset is usually equal to the type ID (because the FilterIds entries are
336 // written using a variable width encoding, which outputs one byte per entry
337 // as long as the value written is not too large) but can differ. This kind
338 // of complication does not occur for positive type IDs because type infos are
339 // output using a fixed width encoding. FilterOffsets[i] holds the byte
340 // offset corresponding to FilterIds[i].
342 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
343 SmallVector<int, 16> FilterOffsets;
344 FilterOffsets.reserve(FilterIds.size());
347 for (std::vector<unsigned>::const_iterator
348 I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
349 FilterOffsets.push_back(Offset);
350 Offset -= MCAsmInfo::getULEB128Size(*I);
353 FirstActions.reserve(LandingPads.size());
356 unsigned SizeActions = 0;
357 const LandingPadInfo *PrevLPI = 0;
359 for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
360 I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
361 const LandingPadInfo *LPI = *I;
362 const std::vector<int> &TypeIds = LPI->TypeIds;
363 const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
364 unsigned SizeSiteActions = 0;
366 if (NumShared < TypeIds.size()) {
367 unsigned SizeAction = 0;
368 unsigned PrevAction = (unsigned)-1;
371 const unsigned SizePrevIds = PrevLPI->TypeIds.size();
372 assert(Actions.size());
373 PrevAction = Actions.size() - 1;
375 MCAsmInfo::getSLEB128Size(Actions[PrevAction].NextAction) +
376 MCAsmInfo::getSLEB128Size(Actions[PrevAction].ValueForTypeID);
378 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
379 assert(PrevAction != (unsigned)-1 && "PrevAction is invalid!");
381 MCAsmInfo::getSLEB128Size(Actions[PrevAction].ValueForTypeID);
382 SizeAction += -Actions[PrevAction].NextAction;
383 PrevAction = Actions[PrevAction].Previous;
387 // Compute the actions.
388 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
389 int TypeID = TypeIds[J];
390 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
391 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
392 unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
394 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
395 SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
396 SizeSiteActions += SizeAction;
398 ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
399 Actions.push_back(Action);
400 PrevAction = Actions.size() - 1;
403 // Record the first action of the landing pad site.
404 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
405 } // else identical - re-use previous FirstAction
407 // Information used when created the call-site table. The action record
408 // field of the call site record is the offset of the first associated
409 // action record, relative to the start of the actions table. This value is
410 // biased by 1 (1 indicating the start of the actions table), and 0
411 // indicates that there are no actions.
412 FirstActions.push_back(FirstAction);
414 // Compute this sites contribution to size.
415 SizeActions += SizeSiteActions;
423 /// CallToNoUnwindFunction - Return `true' if this is a call to a function
424 /// marked `nounwind'. Return `false' otherwise.
425 bool DwarfException::CallToNoUnwindFunction(const MachineInstr *MI) {
426 assert(MI->getDesc().isCall() && "This should be a call instruction!");
428 bool MarkedNoUnwind = false;
429 bool SawFunc = false;
431 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
432 const MachineOperand &MO = MI->getOperand(I);
435 if (Function *F = dyn_cast<Function>(MO.getGlobal())) {
437 // Be conservative. If we have more than one function operand for this
438 // call, then we can't make the assumption that it's the callee and
439 // not a parameter to the call.
441 // FIXME: Determine if there's a way to say that `F' is the callee or
443 MarkedNoUnwind = false;
447 MarkedNoUnwind = F->doesNotThrow();
453 return MarkedNoUnwind;
456 /// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
457 /// has a try-range containing the call, a non-zero landing pad, and an
458 /// appropriate action. The entry for an ordinary call has a try-range
459 /// containing the call and zero for the landing pad and the action. Calls
460 /// marked 'nounwind' have no entry and must not be contained in the try-range
461 /// of any entry - they form gaps in the table. Entries must be ordered by
462 /// try-range address.
463 void DwarfException::
464 ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
465 const RangeMapType &PadMap,
466 const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
467 const SmallVectorImpl<unsigned> &FirstActions) {
468 // The end label of the previous invoke or nounwind try-range.
469 unsigned LastLabel = 0;
471 // Whether there is a potentially throwing instruction (currently this means
472 // an ordinary call) between the end of the previous try-range and now.
473 bool SawPotentiallyThrowing = false;
475 // Whether the last CallSite entry was for an invoke.
476 bool PreviousIsInvoke = false;
478 // Visit all instructions in order of address.
479 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
481 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
483 if (!MI->isLabel()) {
484 if (MI->getDesc().isCall())
485 SawPotentiallyThrowing |= !CallToNoUnwindFunction(MI);
490 unsigned BeginLabel = MI->getOperand(0).getImm();
491 assert(BeginLabel && "Invalid label!");
493 // End of the previous try-range?
494 if (BeginLabel == LastLabel)
495 SawPotentiallyThrowing = false;
497 // Beginning of a new try-range?
498 RangeMapType::const_iterator L = PadMap.find(BeginLabel);
499 if (L == PadMap.end())
500 // Nope, it was just some random label.
503 const PadRange &P = L->second;
504 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
505 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
506 "Inconsistent landing pad map!");
508 // For Dwarf exception handling (SjLj handling doesn't use this). If some
509 // instruction between the previous try-range and this one may throw,
510 // create a call-site entry with no landing pad for the region between the
512 if (SawPotentiallyThrowing &&
513 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
514 CallSiteEntry Site = { LastLabel, BeginLabel, 0, 0 };
515 CallSites.push_back(Site);
516 PreviousIsInvoke = false;
519 LastLabel = LandingPad->EndLabels[P.RangeIndex];
520 assert(BeginLabel && LastLabel && "Invalid landing pad!");
522 if (LandingPad->LandingPadLabel) {
523 // This try-range is for an invoke.
524 CallSiteEntry Site = {
527 LandingPad->LandingPadLabel,
528 FirstActions[P.PadIndex]
531 // Try to merge with the previous call-site. SJLJ doesn't do this
532 if (PreviousIsInvoke &&
533 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
534 CallSiteEntry &Prev = CallSites.back();
535 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
536 // Extend the range of the previous entry.
537 Prev.EndLabel = Site.EndLabel;
542 // Otherwise, create a new call-site.
543 if (MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf)
544 CallSites.push_back(Site);
546 // SjLj EH must maintain the call sites in the order assigned
547 // to them by the SjLjPrepare pass.
548 unsigned SiteNo = MMI->getCallSiteBeginLabel(BeginLabel);
549 if (CallSites.size() < SiteNo)
550 CallSites.resize(SiteNo);
551 CallSites[SiteNo - 1] = Site;
553 PreviousIsInvoke = true;
556 PreviousIsInvoke = false;
561 // If some instruction between the previous try-range and the end of the
562 // function may throw, create a call-site entry with no landing pad for the
563 // region following the try-range.
564 if (SawPotentiallyThrowing &&
565 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
566 CallSiteEntry Site = { LastLabel, 0, 0, 0 };
567 CallSites.push_back(Site);
571 /// EmitExceptionTable - Emit landing pads and actions.
573 /// The general organization of the table is complex, but the basic concepts are
574 /// easy. First there is a header which describes the location and organization
575 /// of the three components that follow.
577 /// 1. The landing pad site information describes the range of code covered by
578 /// the try. In our case it's an accumulation of the ranges covered by the
579 /// invokes in the try. There is also a reference to the landing pad that
580 /// handles the exception once processed. Finally an index into the actions
582 /// 2. The action table, in our case, is composed of pairs of type IDs and next
583 /// action offset. Starting with the action index from the landing pad
584 /// site, each type ID is checked for a match to the current exception. If
585 /// it matches then the exception and type id are passed on to the landing
586 /// pad. Otherwise the next action is looked up. This chain is terminated
587 /// with a next action of zero. If no type id is found then the frame is
588 /// unwound and handling continues.
589 /// 3. Type ID table contains references to all the C++ typeinfo for all
590 /// catches in the function. This tables is reverse indexed base 1.
591 void DwarfException::EmitExceptionTable() {
592 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
593 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
594 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
595 if (PadInfos.empty()) return;
597 // Sort the landing pads in order of their type ids. This is used to fold
598 // duplicate actions.
599 SmallVector<const LandingPadInfo *, 64> LandingPads;
600 LandingPads.reserve(PadInfos.size());
602 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
603 LandingPads.push_back(&PadInfos[i]);
605 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
607 // Compute the actions table and gather the first action index for each
609 SmallVector<ActionEntry, 32> Actions;
610 SmallVector<unsigned, 64> FirstActions;
611 unsigned SizeActions=ComputeActionsTable(LandingPads, Actions, FirstActions);
613 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
614 // by try-range labels when lowered). Ordinary calls do not, so appropriate
615 // try-ranges for them need be deduced when using DWARF exception handling.
617 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
618 const LandingPadInfo *LandingPad = LandingPads[i];
619 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
620 unsigned BeginLabel = LandingPad->BeginLabels[j];
621 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
622 PadRange P = { i, j };
623 PadMap[BeginLabel] = P;
627 // Compute the call-site table.
628 SmallVector<CallSiteEntry, 64> CallSites;
629 ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
634 const unsigned SiteStartSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
635 const unsigned SiteLengthSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
636 const unsigned LandingPadSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
637 bool IsSJLJ = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
638 bool HaveTTData = IsSJLJ ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
644 SizeSites = CallSites.size() *
645 (SiteStartSize + SiteLengthSize + LandingPadSize);
647 for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
648 SizeSites += MCAsmInfo::getULEB128Size(CallSites[i].Action);
650 SizeSites += MCAsmInfo::getULEB128Size(i);
654 const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
655 unsigned TTypeEncoding;
656 unsigned TypeFormatSize;
659 // For SjLj exceptions, if there is no TypeInfo, then we just explicitly say
660 // that we're omitting that bit.
661 TTypeEncoding = dwarf::DW_EH_PE_omit;
662 TypeFormatSize = SizeOfEncodedValue(dwarf::DW_EH_PE_absptr);
664 // Okay, we have actual filters or typeinfos to emit. As such, we need to
665 // pick a type encoding for them. We're about to emit a list of pointers to
666 // typeinfo objects at the end of the LSDA. However, unless we're in static
667 // mode, this reference will require a relocation by the dynamic linker.
669 // Because of this, we have a couple of options:
671 // 1) If we are in -static mode, we can always use an absolute reference
672 // from the LSDA, because the static linker will resolve it.
674 // 2) Otherwise, if the LSDA section is writable, we can output the direct
675 // reference to the typeinfo and allow the dynamic linker to relocate
676 // it. Since it is in a writable section, the dynamic linker won't
679 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
680 // we need to use some form of indirection. For example, on Darwin,
681 // we can output a statically-relocatable reference to a dyld stub. The
682 // offset to the stub is constant, but the contents are in a section
683 // that is updated by the dynamic linker. This is easy enough, but we
684 // need to tell the personality function of the unwinder to indirect
685 // through the dyld stub.
687 // FIXME: When (3) is actually implemented, we'll have to emit the stubs
688 // somewhere. This predicate should be moved to a shared location that is
689 // in target-independent code.
691 TTypeEncoding = Asm->getObjFileLowering().getTTypeEncoding();
692 TypeFormatSize = SizeOfEncodedValue(TTypeEncoding);
695 // Begin the exception table.
696 Asm->OutStreamer.SwitchSection(LSDASection);
697 Asm->EmitAlignment(2, 0, 0, false);
699 O << "GCC_except_table" << SubprogramCount << ":\n";
701 // The type infos need to be aligned. GCC does this by inserting padding just
702 // before the type infos. However, this changes the size of the exception
703 // table, so you need to take this into account when you output the exception
704 // table size. However, the size is output using a variable length encoding.
705 // So by increasing the size by inserting padding, you may increase the number
706 // of bytes used for writing the size. If it increases, say by one byte, then
707 // you now need to output one less byte of padding to get the type infos
708 // aligned. However this decreases the size of the exception table. This
709 // changes the value you have to output for the exception table size. Due to
710 // the variable length encoding, the number of bytes used for writing the
711 // length may decrease. If so, you then have to increase the amount of
712 // padding. And so on. If you look carefully at the GCC code you will see that
713 // it indeed does this in a loop, going on and on until the values stabilize.
714 // We chose another solution: don't output padding inside the table like GCC
715 // does, instead output it before the table.
716 unsigned SizeTypes = TypeInfos.size() * TypeFormatSize;
717 unsigned TyOffset = sizeof(int8_t) + // Call site format
718 MCAsmInfo::getULEB128Size(SizeSites) + // Call site table length
719 SizeSites + SizeActions + SizeTypes;
720 unsigned TotalSize = sizeof(int8_t) + // LPStart format
721 sizeof(int8_t) + // TType format
723 MCAsmInfo::getULEB128Size(TyOffset) : 0) + // TType base offset
725 unsigned SizeAlign = (4 - TotalSize) & 3;
727 for (unsigned i = 0; i != SizeAlign; ++i) {
732 EmitLabel("exception", SubprogramCount);
735 SmallString<16> LSDAName;
736 raw_svector_ostream(LSDAName) << MAI->getPrivateGlobalPrefix() <<
737 "_LSDA_" << Asm->getFunctionNumber();
738 O << LSDAName.str() << ":\n";
742 EmitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
743 EmitEncodingByte(TTypeEncoding, "@TType");
746 EmitULEB128(TyOffset, "@TType base offset");
748 // SjLj Exception handling
750 EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
751 EmitULEB128(SizeSites, "Call site table length");
753 // Emit the landing pad site information.
755 for (SmallVectorImpl<CallSiteEntry>::const_iterator
756 I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
757 const CallSiteEntry &S = *I;
759 // Offset of the landing pad, counted in 16-byte bundles relative to the
761 EmitULEB128(idx, "Landing pad");
763 // Offset of the first associated action record, relative to the start of
764 // the action table. This value is biased by 1 (1 indicates the start of
765 // the action table), and 0 indicates that there are no actions.
766 EmitULEB128(S.Action, "Action");
769 // DWARF Exception handling
770 assert(MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
772 // The call-site table is a list of all call sites that may throw an
773 // exception (including C++ 'throw' statements) in the procedure
774 // fragment. It immediately follows the LSDA header. Each entry indicates,
775 // for a given call, the first corresponding action record and corresponding
778 // The table begins with the number of bytes, stored as an LEB128
779 // compressed, unsigned integer. The records immediately follow the record
780 // count. They are sorted in increasing call-site address. Each record
783 // * The position of the call-site.
784 // * The position of the landing pad.
785 // * The first action record for that call site.
787 // A missing entry in the call-site table indicates that a call is not
788 // supposed to throw.
790 // Emit the landing pad call site table.
791 EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
792 EmitULEB128(SizeSites, "Call site table length");
794 for (SmallVectorImpl<CallSiteEntry>::const_iterator
795 I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
796 const CallSiteEntry &S = *I;
797 const char *BeginTag;
798 unsigned BeginNumber;
801 BeginTag = "eh_func_begin";
802 BeginNumber = SubprogramCount;
805 BeginNumber = S.BeginLabel;
808 // Offset of the call site relative to the previous call site, counted in
809 // number of 16-byte bundles. The first call site is counted relative to
810 // the start of the procedure fragment.
811 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
816 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
819 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
821 EOL("Region length");
823 // Offset of the landing pad, counted in 16-byte bundles relative to the
826 Asm->OutStreamer.AddComment("Landing pad");
827 Asm->OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
829 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
834 // Offset of the first associated action record, relative to the start of
835 // the action table. This value is biased by 1 (1 indicates the start of
836 // the action table), and 0 indicates that there are no actions.
837 EmitULEB128(S.Action, "Action");
841 // Emit the Action Table.
842 if (Actions.size() != 0) EOL("-- Action Record Table --");
843 for (SmallVectorImpl<ActionEntry>::const_iterator
844 I = Actions.begin(), E = Actions.end(); I != E; ++I) {
845 const ActionEntry &Action = *I;
846 EOL("Action Record:");
850 // Used by the runtime to match the type of the thrown exception to the
851 // type of the catch clauses or the types in the exception specification.
852 EmitSLEB128(Action.ValueForTypeID, " TypeInfo index");
856 // Self-relative signed displacement in bytes of the next action record,
857 // or 0 if there is no next action record.
858 EmitSLEB128(Action.NextAction, " Next action");
861 // Emit the Catch TypeInfos.
862 if (!TypeInfos.empty()) EOL("-- Catch TypeInfos --");
863 for (std::vector<GlobalVariable *>::const_reverse_iterator
864 I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
865 const GlobalVariable *GV = *I;
868 EmitReference(GV, TTypeEncoding);
877 // Emit the Exception Specifications.
878 if (!FilterIds.empty()) EOL("-- Filter IDs --");
879 for (std::vector<unsigned>::const_iterator
880 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
881 unsigned TypeID = *I;
882 EmitULEB128(TypeID, TypeID != 0 ? "Exception specification" : 0);
885 Asm->EmitAlignment(2, 0, 0, false);
888 /// EndModule - Emit all exception information that should come after the
890 void DwarfException::EndModule() {
891 if (MAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
894 if (!shouldEmitMovesModule && !shouldEmitTableModule)
897 if (TimePassesIsEnabled)
898 ExceptionTimer->startTimer();
900 const std::vector<Function *> Personalities = MMI->getPersonalities();
902 for (unsigned I = 0, E = Personalities.size(); I < E; ++I)
903 EmitCIE(Personalities[I], I);
905 for (std::vector<FunctionEHFrameInfo>::iterator
906 I = EHFrames.begin(), E = EHFrames.end(); I != E; ++I)
909 if (TimePassesIsEnabled)
910 ExceptionTimer->stopTimer();
913 /// BeginFunction - Gather pre-function exception information. Assumes it's
914 /// being emitted immediately after the function entry point.
915 void DwarfException::BeginFunction(const MachineFunction *MF) {
916 if (!MMI || !MAI->doesSupportExceptionHandling()) return;
918 if (TimePassesIsEnabled)
919 ExceptionTimer->startTimer();
922 shouldEmitTable = shouldEmitMoves = false;
924 // Map all labels and get rid of any dead landing pads.
925 MMI->TidyLandingPads();
927 // If any landing pads survive, we need an EH table.
928 if (!MMI->getLandingPads().empty())
929 shouldEmitTable = true;
931 // See if we need frame move info.
932 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
933 shouldEmitMoves = true;
935 if (shouldEmitMoves || shouldEmitTable)
936 // Assumes in correct section after the entry point.
937 EmitLabel("eh_func_begin", ++SubprogramCount);
939 shouldEmitTableModule |= shouldEmitTable;
940 shouldEmitMovesModule |= shouldEmitMoves;
942 if (TimePassesIsEnabled)
943 ExceptionTimer->stopTimer();
946 /// EndFunction - Gather and emit post-function exception information.
948 void DwarfException::EndFunction() {
949 if (!shouldEmitMoves && !shouldEmitTable) return;
951 if (TimePassesIsEnabled)
952 ExceptionTimer->startTimer();
954 EmitLabel("eh_func_end", SubprogramCount);
955 EmitExceptionTable();
957 MCSymbol *FunctionEHSym =
958 Asm->GetSymbolWithGlobalValueBase(MF->getFunction(), ".eh",
959 Asm->MAI->is_EHSymbolPrivate());
961 // Save EH frame information
962 EHFrames.push_back(FunctionEHFrameInfo(FunctionEHSym, SubprogramCount,
963 MMI->getPersonalityIndex(),
964 MF->getFrameInfo()->hasCalls(),
965 !MMI->getLandingPads().empty(),
966 MMI->getFrameMoves(),
969 // Record if this personality index uses a landing pad.
970 UsesLSDA[MMI->getPersonalityIndex()] |= !MMI->getLandingPads().empty();
972 if (TimePassesIsEnabled)
973 ExceptionTimer->stopTimer();