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/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Support/Dwarf.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/Timer.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/Twine.h"
41 DwarfException::DwarfException(AsmPrinter *A)
42 : DwarfPrinter(A), 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 /// EmitCIE - Emit a Common Information Entry (CIE). This holds information that
54 /// is shared among many Frame Description Entries. There is at least one CIE
55 /// in every non-empty .debug_frame section.
56 void DwarfException::EmitCIE(const Function *PersonalityFn, unsigned Index) {
57 // Size and sign of stack growth.
59 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
60 TargetFrameInfo::StackGrowsUp ?
61 TD->getPointerSize() : -TD->getPointerSize();
63 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
65 // Begin eh frame section.
66 Asm->OutStreamer.SwitchSection(TLOF.getEHFrameSection());
69 if (TLOF.isFunctionEHFrameSymbolPrivate())
70 EHFrameSym = Asm->GetTempSymbol("EH_frame", Index);
72 EHFrameSym = Asm->OutContext.GetOrCreateSymbol(Twine("EH_frame") +
74 Asm->OutStreamer.EmitLabel(EHFrameSym);
76 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_eh_frame", Index));
78 // Define base labels.
79 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_frame_common", Index));
81 // Define the eh frame length.
82 Asm->OutStreamer.AddComment("Length of Common Information Entry");
83 Asm->EmitLabelDifference(Asm->GetTempSymbol("eh_frame_common_end", Index),
84 Asm->GetTempSymbol("eh_frame_common_begin", Index),
88 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_frame_common_begin",Index));
89 Asm->OutStreamer.AddComment("CIE Identifier Tag");
90 Asm->OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
91 Asm->OutStreamer.AddComment("DW_CIE_VERSION");
92 Asm->OutStreamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1/*size*/, 0/*addr*/);
94 // The personality presence indicates that language specific information will
95 // show up in the eh frame. Find out how we are supposed to lower the
96 // personality function reference:
98 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
99 unsigned FDEEncoding = TLOF.getFDEEncoding();
100 unsigned PerEncoding = TLOF.getPersonalityEncoding();
102 char Augmentation[6] = { 0 };
103 unsigned AugmentationSize = 0;
104 char *APtr = Augmentation + 1;
107 // There is a personality function.
109 AugmentationSize += 1 + SizeOfEncodedValue(PerEncoding);
112 if (UsesLSDA[Index]) {
113 // An LSDA pointer is in the FDE augmentation.
118 if (FDEEncoding != dwarf::DW_EH_PE_absptr) {
119 // A non-default pointer encoding for the FDE.
124 if (APtr != Augmentation + 1)
125 Augmentation[0] = 'z';
127 Asm->OutStreamer.AddComment("CIE Augmentation");
128 Asm->OutStreamer.EmitBytes(StringRef(Augmentation, strlen(Augmentation)+1),0);
131 Asm->EmitULEB128(1, "CIE Code Alignment Factor");
132 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
133 Asm->OutStreamer.AddComment("CIE Return Address Column");
134 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
136 if (Augmentation[0]) {
137 Asm->EmitULEB128(AugmentationSize, "Augmentation Size");
139 // If there is a personality, we need to indicate the function's location.
141 Asm->EmitEncodingByte(PerEncoding, "Personality");
142 Asm->OutStreamer.AddComment("Personality");
143 EmitReference(PersonalityFn, PerEncoding);
146 Asm->EmitEncodingByte(LSDAEncoding, "LSDA");
147 if (FDEEncoding != dwarf::DW_EH_PE_absptr)
148 Asm->EmitEncodingByte(FDEEncoding, "FDE");
151 // Indicate locations of general callee saved registers in frame.
152 std::vector<MachineMove> Moves;
153 RI->getInitialFrameState(Moves);
154 EmitFrameMoves(0, Moves, true);
156 // On Darwin the linker honors the alignment of eh_frame, which means it must
157 // be 8-byte on 64-bit targets to match what gcc does. Otherwise you get
158 // holes which confuse readers of eh_frame.
159 Asm->EmitAlignment(TD->getPointerSize() == 4 ? 2 : 3, 0, 0, false);
160 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_frame_common_end", Index));
163 /// EmitFDE - Emit the Frame Description Entry (FDE) for the function.
164 void DwarfException::EmitFDE(const FunctionEHFrameInfo &EHFrameInfo) {
165 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
166 "Should not emit 'available externally' functions at all");
168 const Function *TheFunc = EHFrameInfo.function;
169 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
171 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
172 unsigned FDEEncoding = TLOF.getFDEEncoding();
174 Asm->OutStreamer.SwitchSection(TLOF.getEHFrameSection());
176 // Externally visible entry into the functions eh frame info. If the
177 // corresponding function is static, this should not be externally visible.
178 if (!TheFunc->hasLocalLinkage() && TLOF.isFunctionEHSymbolGlobal())
179 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,MCSA_Global);
181 // If corresponding function is weak definition, this should be too.
182 if (TheFunc->isWeakForLinker() && MAI->getWeakDefDirective())
183 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
184 MCSA_WeakDefinition);
186 // If corresponding function is hidden, this should be too.
187 if (TheFunc->hasHiddenVisibility())
188 if (MCSymbolAttr HiddenAttr = MAI->getHiddenVisibilityAttr())
189 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
192 // If there are no calls then you can't unwind. This may mean we can omit the
193 // EH Frame, but some environments do not handle weak absolute symbols. If
194 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
195 // info is to be available for non-EH uses.
196 if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
197 (!TheFunc->isWeakForLinker() ||
198 !MAI->getWeakDefDirective() ||
199 TLOF.getSupportsWeakOmittedEHFrame())) {
200 Asm->OutStreamer.EmitAssignment(EHFrameInfo.FunctionEHSym,
201 MCConstantExpr::Create(0, Asm->OutContext));
202 // This name has no connection to the function, so it might get
203 // dead-stripped when the function is not, erroneously. Prohibit
204 // dead-stripping unconditionally.
205 if (MAI->hasNoDeadStrip())
206 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
209 Asm->OutStreamer.EmitLabel(EHFrameInfo.FunctionEHSym);
212 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
213 Asm->EmitLabelDifference(
214 Asm->GetTempSymbol("eh_frame_end", EHFrameInfo.Number),
215 Asm->GetTempSymbol("eh_frame_begin", EHFrameInfo.Number), 4);
217 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_frame_begin",
218 EHFrameInfo.Number));
220 Asm->OutStreamer.AddComment("FDE CIE offset");
221 EmitSectionOffset(Asm->GetTempSymbol("eh_frame_begin", EHFrameInfo.Number),
222 Asm->GetTempSymbol("eh_frame_common",
223 EHFrameInfo.PersonalityIndex),
226 MCSymbol *EHFuncBeginSym =
227 Asm->GetTempSymbol("eh_func_begin", EHFrameInfo.Number);
229 Asm->OutStreamer.AddComment("FDE initial location");
230 EmitReference(EHFuncBeginSym, FDEEncoding);
232 Asm->OutStreamer.AddComment("FDE address range");
233 Asm->EmitLabelDifference(Asm->GetTempSymbol("eh_func_end",
235 EHFuncBeginSym, SizeOfEncodedValue(FDEEncoding));
237 // If there is a personality and landing pads then point to the language
238 // specific data area in the exception table.
239 if (MMI->getPersonalities()[0] != NULL) {
240 unsigned Size = SizeOfEncodedValue(LSDAEncoding);
242 Asm->EmitULEB128(Size, "Augmentation size");
243 Asm->OutStreamer.AddComment("Language Specific Data Area");
244 if (EHFrameInfo.hasLandingPads)
245 EmitReference(Asm->GetTempSymbol("exception", EHFrameInfo.Number),
248 Asm->OutStreamer.EmitIntValue(0, Size/*size*/, 0/*addrspace*/);
251 Asm->EmitULEB128(0, "Augmentation size");
254 // Indicate locations of function specific callee saved registers in frame.
255 EmitFrameMoves(EHFuncBeginSym, EHFrameInfo.Moves, true);
257 // On Darwin the linker honors the alignment of eh_frame, which means it
258 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
259 // get holes which confuse readers of eh_frame.
260 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
262 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_frame_end",
263 EHFrameInfo.Number));
265 // If the function is marked used, this table should be also. We cannot
266 // make the mark unconditional in this case, since retaining the table also
267 // retains the function in this case, and there is code around that depends
268 // on unused functions (calling undefined externals) being dead-stripped to
269 // link correctly. Yes, there really is.
270 if (MMI->isUsedFunction(EHFrameInfo.function))
271 if (MAI->hasNoDeadStrip())
272 Asm->OutStreamer.EmitSymbolAttribute(EHFrameInfo.FunctionEHSym,
275 Asm->OutStreamer.AddBlankLine();
278 /// SharedTypeIds - How many leading type ids two landing pads have in common.
279 unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
280 const LandingPadInfo *R) {
281 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
282 unsigned LSize = LIds.size(), RSize = RIds.size();
283 unsigned MinSize = LSize < RSize ? LSize : RSize;
286 for (; Count != MinSize; ++Count)
287 if (LIds[Count] != RIds[Count])
293 /// PadLT - Order landing pads lexicographically by type id.
294 bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
295 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
296 unsigned LSize = LIds.size(), RSize = RIds.size();
297 unsigned MinSize = LSize < RSize ? LSize : RSize;
299 for (unsigned i = 0; i != MinSize; ++i)
300 if (LIds[i] != RIds[i])
301 return LIds[i] < RIds[i];
303 return LSize < RSize;
306 /// ComputeActionsTable - Compute the actions table and gather the first action
307 /// index for each landing pad site.
308 unsigned DwarfException::
309 ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
310 SmallVectorImpl<ActionEntry> &Actions,
311 SmallVectorImpl<unsigned> &FirstActions) {
313 // The action table follows the call-site table in the LSDA. The individual
314 // records are of two types:
317 // * Exception specification
319 // The two record kinds have the same format, with only small differences.
320 // They are distinguished by the "switch value" field: Catch clauses
321 // (TypeInfos) have strictly positive switch values, and exception
322 // specifications (FilterIds) have strictly negative switch values. Value 0
323 // indicates a catch-all clause.
325 // Negative type IDs index into FilterIds. Positive type IDs index into
326 // TypeInfos. The value written for a positive type ID is just the type ID
327 // itself. For a negative type ID, however, the value written is the
328 // (negative) byte offset of the corresponding FilterIds entry. The byte
329 // offset is usually equal to the type ID (because the FilterIds entries are
330 // written using a variable width encoding, which outputs one byte per entry
331 // as long as the value written is not too large) but can differ. This kind
332 // of complication does not occur for positive type IDs because type infos are
333 // output using a fixed width encoding. FilterOffsets[i] holds the byte
334 // offset corresponding to FilterIds[i].
336 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
337 SmallVector<int, 16> FilterOffsets;
338 FilterOffsets.reserve(FilterIds.size());
341 for (std::vector<unsigned>::const_iterator
342 I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
343 FilterOffsets.push_back(Offset);
344 Offset -= MCAsmInfo::getULEB128Size(*I);
347 FirstActions.reserve(LandingPads.size());
350 unsigned SizeActions = 0;
351 const LandingPadInfo *PrevLPI = 0;
353 for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
354 I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
355 const LandingPadInfo *LPI = *I;
356 const std::vector<int> &TypeIds = LPI->TypeIds;
357 const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
358 unsigned SizeSiteActions = 0;
360 if (NumShared < TypeIds.size()) {
361 unsigned SizeAction = 0;
362 unsigned PrevAction = (unsigned)-1;
365 const unsigned SizePrevIds = PrevLPI->TypeIds.size();
366 assert(Actions.size());
367 PrevAction = Actions.size() - 1;
369 MCAsmInfo::getSLEB128Size(Actions[PrevAction].NextAction) +
370 MCAsmInfo::getSLEB128Size(Actions[PrevAction].ValueForTypeID);
372 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
373 assert(PrevAction != (unsigned)-1 && "PrevAction is invalid!");
375 MCAsmInfo::getSLEB128Size(Actions[PrevAction].ValueForTypeID);
376 SizeAction += -Actions[PrevAction].NextAction;
377 PrevAction = Actions[PrevAction].Previous;
381 // Compute the actions.
382 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
383 int TypeID = TypeIds[J];
384 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
385 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
386 unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
388 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
389 SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
390 SizeSiteActions += SizeAction;
392 ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
393 Actions.push_back(Action);
394 PrevAction = Actions.size() - 1;
397 // Record the first action of the landing pad site.
398 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
399 } // else identical - re-use previous FirstAction
401 // Information used when created the call-site table. The action record
402 // field of the call site record is the offset of the first associated
403 // action record, relative to the start of the actions table. This value is
404 // biased by 1 (1 indicating the start of the actions table), and 0
405 // indicates that there are no actions.
406 FirstActions.push_back(FirstAction);
408 // Compute this sites contribution to size.
409 SizeActions += SizeSiteActions;
417 /// CallToNoUnwindFunction - Return `true' if this is a call to a function
418 /// marked `nounwind'. Return `false' otherwise.
419 bool DwarfException::CallToNoUnwindFunction(const MachineInstr *MI) {
420 assert(MI->getDesc().isCall() && "This should be a call instruction!");
422 bool MarkedNoUnwind = false;
423 bool SawFunc = false;
425 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
426 const MachineOperand &MO = MI->getOperand(I);
428 if (!MO.isGlobal()) continue;
430 Function *F = dyn_cast<Function>(MO.getGlobal());
431 if (F == 0) continue;
434 // Be conservative. If we have more than one function operand for this
435 // call, then we can't make the assumption that it's the callee and
436 // not a parameter to the call.
438 // FIXME: Determine if there's a way to say that `F' is the callee or
440 MarkedNoUnwind = false;
444 MarkedNoUnwind = F->doesNotThrow();
448 return MarkedNoUnwind;
451 /// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
452 /// has a try-range containing the call, a non-zero landing pad, and an
453 /// appropriate action. The entry for an ordinary call has a try-range
454 /// containing the call and zero for the landing pad and the action. Calls
455 /// marked 'nounwind' have no entry and must not be contained in the try-range
456 /// of any entry - they form gaps in the table. Entries must be ordered by
457 /// try-range address.
458 void DwarfException::
459 ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
460 const RangeMapType &PadMap,
461 const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
462 const SmallVectorImpl<unsigned> &FirstActions) {
463 // The end label of the previous invoke or nounwind try-range.
464 MCSymbol *LastLabel = 0;
466 // Whether there is a potentially throwing instruction (currently this means
467 // an ordinary call) between the end of the previous try-range and now.
468 bool SawPotentiallyThrowing = false;
470 // Whether the last CallSite entry was for an invoke.
471 bool PreviousIsInvoke = false;
473 // Visit all instructions in order of address.
474 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
476 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
478 if (!MI->isLabel()) {
479 if (MI->getDesc().isCall())
480 SawPotentiallyThrowing |= !CallToNoUnwindFunction(MI);
484 // End of the previous try-range?
485 MCSymbol *BeginLabel = MI->getOperand(0).getMCSymbol();
486 if (BeginLabel == LastLabel)
487 SawPotentiallyThrowing = false;
489 // Beginning of a new try-range?
490 RangeMapType::const_iterator L = PadMap.find(BeginLabel);
491 if (L == PadMap.end())
492 // Nope, it was just some random label.
495 const PadRange &P = L->second;
496 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
497 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
498 "Inconsistent landing pad map!");
500 // For Dwarf exception handling (SjLj handling doesn't use this). If some
501 // instruction between the previous try-range and this one may throw,
502 // create a call-site entry with no landing pad for the region between the
504 if (SawPotentiallyThrowing &&
505 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
506 CallSiteEntry Site = { LastLabel, BeginLabel, 0, 0 };
507 CallSites.push_back(Site);
508 PreviousIsInvoke = false;
511 LastLabel = LandingPad->EndLabels[P.RangeIndex];
512 assert(BeginLabel && LastLabel && "Invalid landing pad!");
514 if (!LandingPad->LandingPadLabel) {
516 PreviousIsInvoke = false;
518 // This try-range is for an invoke.
519 CallSiteEntry Site = {
522 LandingPad->LandingPadLabel,
523 FirstActions[P.PadIndex]
526 // Try to merge with the previous call-site. SJLJ doesn't do this
527 if (PreviousIsInvoke &&
528 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
529 CallSiteEntry &Prev = CallSites.back();
530 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
531 // Extend the range of the previous entry.
532 Prev.EndLabel = Site.EndLabel;
537 // Otherwise, create a new call-site.
538 if (MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf)
539 CallSites.push_back(Site);
541 // SjLj EH must maintain the call sites in the order assigned
542 // to them by the SjLjPrepare pass.
543 unsigned SiteNo = MMI->getCallSiteBeginLabel(BeginLabel);
544 if (CallSites.size() < SiteNo)
545 CallSites.resize(SiteNo);
546 CallSites[SiteNo - 1] = Site;
548 PreviousIsInvoke = true;
553 // If some instruction between the previous try-range and the end of the
554 // function may throw, create a call-site entry with no landing pad for the
555 // region following the try-range.
556 if (SawPotentiallyThrowing &&
557 MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
558 CallSiteEntry Site = { LastLabel, 0, 0, 0 };
559 CallSites.push_back(Site);
563 /// EmitExceptionTable - Emit landing pads and actions.
565 /// The general organization of the table is complex, but the basic concepts are
566 /// easy. First there is a header which describes the location and organization
567 /// of the three components that follow.
569 /// 1. The landing pad site information describes the range of code covered by
570 /// the try. In our case it's an accumulation of the ranges covered by the
571 /// invokes in the try. There is also a reference to the landing pad that
572 /// handles the exception once processed. Finally an index into the actions
574 /// 2. The action table, in our case, is composed of pairs of type IDs and next
575 /// action offset. Starting with the action index from the landing pad
576 /// site, each type ID is checked for a match to the current exception. If
577 /// it matches then the exception and type id are passed on to the landing
578 /// pad. Otherwise the next action is looked up. This chain is terminated
579 /// with a next action of zero. If no type id is found then the frame is
580 /// unwound and handling continues.
581 /// 3. Type ID table contains references to all the C++ typeinfo for all
582 /// catches in the function. This tables is reverse indexed base 1.
583 void DwarfException::EmitExceptionTable() {
584 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
585 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
586 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
588 // Sort the landing pads in order of their type ids. This is used to fold
589 // duplicate actions.
590 SmallVector<const LandingPadInfo *, 64> LandingPads;
591 LandingPads.reserve(PadInfos.size());
593 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
594 LandingPads.push_back(&PadInfos[i]);
596 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
598 // Compute the actions table and gather the first action index for each
600 SmallVector<ActionEntry, 32> Actions;
601 SmallVector<unsigned, 64> FirstActions;
602 unsigned SizeActions=ComputeActionsTable(LandingPads, Actions, FirstActions);
604 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
605 // by try-range labels when lowered). Ordinary calls do not, so appropriate
606 // try-ranges for them need be deduced when using DWARF exception handling.
608 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
609 const LandingPadInfo *LandingPad = LandingPads[i];
610 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
611 MCSymbol *BeginLabel = LandingPad->BeginLabels[j];
612 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
613 PadRange P = { i, j };
614 PadMap[BeginLabel] = P;
618 // Compute the call-site table.
619 SmallVector<CallSiteEntry, 64> CallSites;
620 ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
625 const unsigned SiteStartSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
626 const unsigned SiteLengthSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
627 const unsigned LandingPadSize = SizeOfEncodedValue(dwarf::DW_EH_PE_udata4);
628 bool IsSJLJ = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
629 bool HaveTTData = IsSJLJ ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
630 unsigned CallSiteTableLength;
633 CallSiteTableLength = 0;
635 CallSiteTableLength = CallSites.size() *
636 (SiteStartSize + SiteLengthSize + LandingPadSize);
638 for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
639 CallSiteTableLength += MCAsmInfo::getULEB128Size(CallSites[i].Action);
641 CallSiteTableLength += MCAsmInfo::getULEB128Size(i);
645 const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
646 unsigned TTypeEncoding;
647 unsigned TypeFormatSize;
650 // For SjLj exceptions, if there is no TypeInfo, then we just explicitly say
651 // that we're omitting that bit.
652 TTypeEncoding = dwarf::DW_EH_PE_omit;
653 TypeFormatSize = SizeOfEncodedValue(dwarf::DW_EH_PE_absptr);
655 // Okay, we have actual filters or typeinfos to emit. As such, we need to
656 // pick a type encoding for them. We're about to emit a list of pointers to
657 // typeinfo objects at the end of the LSDA. However, unless we're in static
658 // mode, this reference will require a relocation by the dynamic linker.
660 // Because of this, we have a couple of options:
662 // 1) If we are in -static mode, we can always use an absolute reference
663 // from the LSDA, because the static linker will resolve it.
665 // 2) Otherwise, if the LSDA section is writable, we can output the direct
666 // reference to the typeinfo and allow the dynamic linker to relocate
667 // it. Since it is in a writable section, the dynamic linker won't
670 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
671 // we need to use some form of indirection. For example, on Darwin,
672 // we can output a statically-relocatable reference to a dyld stub. The
673 // offset to the stub is constant, but the contents are in a section
674 // that is updated by the dynamic linker. This is easy enough, but we
675 // need to tell the personality function of the unwinder to indirect
676 // through the dyld stub.
678 // FIXME: When (3) is actually implemented, we'll have to emit the stubs
679 // somewhere. This predicate should be moved to a shared location that is
680 // in target-independent code.
682 TTypeEncoding = Asm->getObjFileLowering().getTTypeEncoding();
683 TypeFormatSize = SizeOfEncodedValue(TTypeEncoding);
686 // Begin the exception table.
687 Asm->OutStreamer.SwitchSection(LSDASection);
688 Asm->EmitAlignment(2, 0, 0, false);
692 Asm->OutContext.GetOrCreateSymbol(Twine("GCC_except_table")+
693 Twine(SubprogramCount));
694 Asm->OutStreamer.EmitLabel(GCCETSym);
695 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("exception", SubprogramCount));
698 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("_LSDA_",
699 Asm->getFunctionNumber()));
701 // Emit the LSDA header.
702 Asm->EmitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
703 Asm->EmitEncodingByte(TTypeEncoding, "@TType");
705 // The type infos need to be aligned. GCC does this by inserting padding just
706 // before the type infos. However, this changes the size of the exception
707 // table, so you need to take this into account when you output the exception
708 // table size. However, the size is output using a variable length encoding.
709 // So by increasing the size by inserting padding, you may increase the number
710 // of bytes used for writing the size. If it increases, say by one byte, then
711 // you now need to output one less byte of padding to get the type infos
712 // aligned. However this decreases the size of the exception table. This
713 // changes the value you have to output for the exception table size. Due to
714 // the variable length encoding, the number of bytes used for writing the
715 // length may decrease. If so, you then have to increase the amount of
716 // padding. And so on. If you look carefully at the GCC code you will see that
717 // it indeed does this in a loop, going on and on until the values stabilize.
718 // We chose another solution: don't output padding inside the table like GCC
719 // does, instead output it before the table.
720 unsigned SizeTypes = TypeInfos.size() * TypeFormatSize;
721 unsigned CallSiteTableLengthSize =
722 MCAsmInfo::getULEB128Size(CallSiteTableLength);
723 unsigned TTypeBaseOffset =
724 sizeof(int8_t) + // Call site format
725 CallSiteTableLengthSize + // Call site table length size
726 CallSiteTableLength + // Call site table length
727 SizeActions + // Actions size
729 unsigned TTypeBaseOffsetSize = MCAsmInfo::getULEB128Size(TTypeBaseOffset);
731 sizeof(int8_t) + // LPStart format
732 sizeof(int8_t) + // TType format
733 (HaveTTData ? TTypeBaseOffsetSize : 0) + // TType base offset size
734 TTypeBaseOffset; // TType base offset
735 unsigned SizeAlign = (4 - TotalSize) & 3;
738 // Account for any extra padding that will be added to the call site table
740 Asm->EmitULEB128(TTypeBaseOffset, "@TType base offset", SizeAlign);
744 // SjLj Exception handling
746 Asm->EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
748 // Add extra padding if it wasn't added to the TType base offset.
749 Asm->EmitULEB128(CallSiteTableLength, "Call site table length", SizeAlign);
751 // Emit the landing pad site information.
753 for (SmallVectorImpl<CallSiteEntry>::const_iterator
754 I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
755 const CallSiteEntry &S = *I;
757 // Offset of the landing pad, counted in 16-byte bundles relative to the
759 Asm->EmitULEB128(idx, "Landing pad");
761 // Offset of the first associated action record, relative to the start of
762 // the action table. This value is biased by 1 (1 indicates the start of
763 // the action table), and 0 indicates that there are no actions.
764 Asm->EmitULEB128(S.Action, "Action");
767 // DWARF Exception handling
768 assert(MAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
770 // The call-site table is a list of all call sites that may throw an
771 // exception (including C++ 'throw' statements) in the procedure
772 // fragment. It immediately follows the LSDA header. Each entry indicates,
773 // for a given call, the first corresponding action record and corresponding
776 // The table begins with the number of bytes, stored as an LEB128
777 // compressed, unsigned integer. The records immediately follow the record
778 // count. They are sorted in increasing call-site address. Each record
781 // * The position of the call-site.
782 // * The position of the landing pad.
783 // * The first action record for that call site.
785 // A missing entry in the call-site table indicates that a call is not
786 // supposed to throw.
788 // Emit the landing pad call site table.
789 Asm->EmitEncodingByte(dwarf::DW_EH_PE_udata4, "Call site");
791 // Add extra padding if it wasn't added to the TType base offset.
792 Asm->EmitULEB128(CallSiteTableLength, "Call site table length", SizeAlign);
794 for (SmallVectorImpl<CallSiteEntry>::const_iterator
795 I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
796 const CallSiteEntry &S = *I;
798 MCSymbol *EHFuncBeginSym =
799 Asm->GetTempSymbol("eh_func_begin", SubprogramCount);
801 MCSymbol *BeginLabel = S.BeginLabel;
803 BeginLabel = EHFuncBeginSym;
804 MCSymbol *EndLabel = S.EndLabel;
806 EndLabel = Asm->GetTempSymbol("eh_func_end", SubprogramCount);
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 Asm->OutStreamer.AddComment("Region start");
812 EmitSectionOffset(BeginLabel, EHFuncBeginSym, true, true);
814 Asm->OutStreamer.AddComment("Region length");
815 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
818 // Offset of the landing pad, counted in 16-byte bundles relative to the
820 Asm->OutStreamer.AddComment("Landing pad");
822 Asm->OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
824 EmitSectionOffset(S.PadLabel, EHFuncBeginSym, true, true);
826 // Offset of the first associated action record, relative to the start of
827 // the action table. This value is biased by 1 (1 indicates the start of
828 // the action table), and 0 indicates that there are no actions.
829 Asm->EmitULEB128(S.Action, "Action");
833 // Emit the Action Table.
834 if (Actions.size() != 0) {
835 Asm->OutStreamer.AddComment("-- Action Record Table --");
836 Asm->OutStreamer.AddBlankLine();
839 for (SmallVectorImpl<ActionEntry>::const_iterator
840 I = Actions.begin(), E = Actions.end(); I != E; ++I) {
841 const ActionEntry &Action = *I;
842 Asm->OutStreamer.AddComment("Action Record");
843 Asm->OutStreamer.AddBlankLine();
847 // Used by the runtime to match the type of the thrown exception to the
848 // type of the catch clauses or the types in the exception specification.
849 Asm->EmitSLEB128(Action.ValueForTypeID, " TypeInfo index");
853 // Self-relative signed displacement in bytes of the next action record,
854 // or 0 if there is no next action record.
855 Asm->EmitSLEB128(Action.NextAction, " Next action");
858 // Emit the Catch TypeInfos.
859 if (!TypeInfos.empty()) {
860 Asm->OutStreamer.AddComment("-- Catch TypeInfos --");
861 Asm->OutStreamer.AddBlankLine();
863 for (std::vector<GlobalVariable *>::const_reverse_iterator
864 I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
865 const GlobalVariable *GV = *I;
867 Asm->OutStreamer.AddComment("TypeInfo");
869 EmitReference(GV, TTypeEncoding);
871 Asm->OutStreamer.EmitIntValue(0, SizeOfEncodedValue(TTypeEncoding), 0);
874 // Emit the Exception Specifications.
875 if (!FilterIds.empty()) {
876 Asm->OutStreamer.AddComment("-- Filter IDs --");
877 Asm->OutStreamer.AddBlankLine();
879 for (std::vector<unsigned>::const_iterator
880 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
881 unsigned TypeID = *I;
882 Asm->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 TimeRegion Timer(ExceptionTimer);
899 const std::vector<Function *> Personalities = MMI->getPersonalities();
901 for (unsigned I = 0, E = Personalities.size(); I < E; ++I)
902 EmitCIE(Personalities[I], I);
904 for (std::vector<FunctionEHFrameInfo>::iterator
905 I = EHFrames.begin(), E = EHFrames.end(); I != E; ++I)
909 /// BeginFunction - Gather pre-function exception information. Assumes it's
910 /// being emitted immediately after the function entry point.
911 void DwarfException::BeginFunction(const MachineFunction *MF) {
912 if (!MMI || !MAI->doesSupportExceptionHandling()) return;
914 TimeRegion Timer(ExceptionTimer);
916 shouldEmitTable = shouldEmitMoves = false;
918 // If any landing pads survive, we need an EH table.
919 shouldEmitTable = !MMI->getLandingPads().empty();
921 // See if we need frame move info.
922 shouldEmitMoves = !MF->getFunction()->doesNotThrow() || UnwindTablesMandatory;
924 if (shouldEmitMoves || shouldEmitTable)
925 // Assumes in correct section after the entry point.
926 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_begin",
929 shouldEmitTableModule |= shouldEmitTable;
930 shouldEmitMovesModule |= shouldEmitMoves;
933 /// EndFunction - Gather and emit post-function exception information.
935 void DwarfException::EndFunction() {
936 if (!shouldEmitMoves && !shouldEmitTable) return;
938 TimeRegion Timer(ExceptionTimer);
939 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_end",SubprogramCount));
941 // Record if this personality index uses a landing pad.
942 bool HasLandingPad = !MMI->getLandingPads().empty();
943 UsesLSDA[MMI->getPersonalityIndex()] |= HasLandingPad;
945 // Map all labels and get rid of any dead landing pads.
946 MMI->TidyLandingPads();
949 EmitExceptionTable();
951 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
952 MCSymbol *FunctionEHSym =
953 Asm->GetSymbolWithGlobalValueBase(MF->getFunction(), ".eh",
954 TLOF.isFunctionEHFrameSymbolPrivate());
956 // Save EH frame information
957 EHFrames.push_back(FunctionEHFrameInfo(FunctionEHSym, SubprogramCount,
958 MMI->getPersonalityIndex(),
959 MF->getFrameInfo()->hasCalls(),
960 !MMI->getLandingPads().empty(),
961 MMI->getFrameMoves(),