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/MCSection.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetFrameInfo.h"
25 #include "llvm/Target/TargetLoweringObjectFile.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/Mangler.h"
30 #include "llvm/Support/Timer.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/StringExtras.h"
36 static TimerGroup
&getDwarfTimerGroup() {
37 static TimerGroup
DwarfTimerGroup("DWARF Exception");
38 return DwarfTimerGroup
;
41 DwarfException::DwarfException(raw_ostream
&OS
, AsmPrinter
*A
,
43 : Dwarf(OS
, A
, T
, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
44 shouldEmitTableModule(false), shouldEmitMovesModule(false),
46 if (TimePassesIsEnabled
)
47 ExceptionTimer
= new Timer("DWARF Exception Writer",
48 getDwarfTimerGroup());
51 DwarfException::~DwarfException() {
52 delete ExceptionTimer
;
55 /// SizeOfEncodedValue - Return the size of the encoding in bytes.
56 unsigned DwarfException::SizeOfEncodedValue(unsigned Encoding
) {
57 if (Encoding
== dwarf::DW_EH_PE_omit
)
60 switch (Encoding
& 0x07) {
61 case dwarf::DW_EH_PE_absptr
:
62 return TD
->getPointerSize();
63 case dwarf::DW_EH_PE_udata2
:
65 case dwarf::DW_EH_PE_udata4
:
67 case dwarf::DW_EH_PE_udata8
:
71 assert(0 && "Invalid encoded value.");
75 /// EmitCIE - Emit a Common Information Entry (CIE). This holds information that
76 /// is shared among many Frame Description Entries. There is at least one CIE
77 /// in every non-empty .debug_frame section.
78 void DwarfException::EmitCIE(const Function
*Personality
, unsigned Index
) {
79 // Size and sign of stack growth.
81 Asm
->TM
.getFrameInfo()->getStackGrowthDirection() ==
82 TargetFrameInfo::StackGrowsUp
?
83 TD
->getPointerSize() : -TD
->getPointerSize();
85 // Begin eh frame section.
86 Asm
->OutStreamer
.SwitchSection(Asm
->getObjFileLowering().getEHFrameSection());
88 if (MAI
->is_EHSymbolPrivate())
89 O
<< MAI
->getPrivateGlobalPrefix();
91 O
<< "EH_frame" << Index
<< ":\n";
92 EmitLabel("section_eh_frame", Index
);
94 // Define base labels.
95 EmitLabel("eh_frame_common", Index
);
97 // Define the eh frame length.
98 EmitDifference("eh_frame_common_end", Index
,
99 "eh_frame_common_begin", Index
, true);
100 Asm
->EOL("Length of Common Information Entry");
103 EmitLabel("eh_frame_common_begin", Index
);
104 Asm
->EmitInt32((int)0);
105 Asm
->EOL("CIE Identifier Tag");
106 Asm
->EmitInt8(dwarf::DW_CIE_VERSION
);
107 Asm
->EOL("CIE Version");
109 // The personality presence indicates that language specific information will
110 // show up in the eh frame.
112 // FIXME: Don't hardcode these encodings.
113 unsigned PerEncoding
= dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata4
;
114 if (Personality
&& MAI
->getNeedsIndirectEncoding())
115 PerEncoding
|= dwarf::DW_EH_PE_indirect
;
116 unsigned LSDAEncoding
= dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata4
;
117 unsigned FDEEncoding
= dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata4
;
119 char Augmentation
[5] = { 0 };
120 unsigned AugmentationSize
= 0;
121 char *APtr
= Augmentation
+ 1;
124 // There is a personality function.
126 AugmentationSize
+= 1 + SizeOfEncodedValue(PerEncoding
);
129 if (UsesLSDA
[Index
]) {
130 // An LSDA pointer is in the FDE augmentation.
135 if (FDEEncoding
!= dwarf::DW_EH_PE_absptr
) {
136 // A non-default pointer encoding for the FDE.
141 if (APtr
!= Augmentation
+ 1)
142 Augmentation
[0] = 'z';
144 Asm
->EmitString(Augmentation
);
145 Asm
->EOL("CIE Augmentation");
148 Asm
->EmitULEB128Bytes(1);
149 Asm
->EOL("CIE Code Alignment Factor");
150 Asm
->EmitSLEB128Bytes(stackGrowth
);
151 Asm
->EOL("CIE Data Alignment Factor");
152 Asm
->EmitInt8(RI
->getDwarfRegNum(RI
->getRARegister(), true));
153 Asm
->EOL("CIE Return Address Column");
155 Asm
->EmitULEB128Bytes(AugmentationSize
);
156 Asm
->EOL("Augmentation Size");
158 Asm
->EmitInt8(PerEncoding
);
159 Asm
->EOL("Personality", PerEncoding
);
161 // If there is a personality, we need to indicate the function's location.
163 PrintRelDirective(true);
164 O
<< MAI
->getPersonalityPrefix();
165 Asm
->EmitExternalGlobal((const GlobalVariable
*)(Personality
));
166 O
<< MAI
->getPersonalitySuffix();
167 if (strcmp(MAI
->getPersonalitySuffix(), "+4@GOTPCREL"))
168 O
<< "-" << MAI
->getPCSymbol();
169 Asm
->EOL("Personality");
171 Asm
->EmitInt8(LSDAEncoding
);
172 Asm
->EOL("LSDA Encoding", LSDAEncoding
);
174 Asm
->EmitInt8(FDEEncoding
);
175 Asm
->EOL("FDE Encoding", FDEEncoding
);
178 // Indicate locations of general callee saved registers in frame.
179 std::vector
<MachineMove
> Moves
;
180 RI
->getInitialFrameState(Moves
);
181 EmitFrameMoves(NULL
, 0, Moves
, true);
183 // On Darwin the linker honors the alignment of eh_frame, which means it must
184 // be 8-byte on 64-bit targets to match what gcc does. Otherwise you get
185 // holes which confuse readers of eh_frame.
186 Asm
->EmitAlignment(TD
->getPointerSize() == sizeof(int32_t) ? 2 : 3,
188 EmitLabel("eh_frame_common_end", Index
);
193 /// EmitFDE - Emit the Frame Description Entry (FDE) for the function.
194 void DwarfException::EmitFDE(const FunctionEHFrameInfo
&EHFrameInfo
) {
195 assert(!EHFrameInfo
.function
->hasAvailableExternallyLinkage() &&
196 "Should not emit 'available externally' functions at all");
198 const Function
*TheFunc
= EHFrameInfo
.function
;
200 Asm
->OutStreamer
.SwitchSection(Asm
->getObjFileLowering().getEHFrameSection());
202 // Externally visible entry into the functions eh frame info. If the
203 // corresponding function is static, this should not be externally visible.
204 if (!TheFunc
->hasLocalLinkage())
205 if (const char *GlobalEHDirective
= MAI
->getGlobalEHDirective())
206 O
<< GlobalEHDirective
<< EHFrameInfo
.FnName
<< "\n";
208 // If corresponding function is weak definition, this should be too.
209 if (TheFunc
->isWeakForLinker() && MAI
->getWeakDefDirective())
210 O
<< MAI
->getWeakDefDirective() << EHFrameInfo
.FnName
<< "\n";
212 // If there are no calls then you can't unwind. This may mean we can omit the
213 // EH Frame, but some environments do not handle weak absolute symbols. If
214 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
215 // info is to be available for non-EH uses.
216 if (!EHFrameInfo
.hasCalls
&& !UnwindTablesMandatory
&&
217 (!TheFunc
->isWeakForLinker() ||
218 !MAI
->getWeakDefDirective() ||
219 MAI
->getSupportsWeakOmittedEHFrame())) {
220 O
<< EHFrameInfo
.FnName
<< " = 0\n";
221 // This name has no connection to the function, so it might get
222 // dead-stripped when the function is not, erroneously. Prohibit
223 // dead-stripping unconditionally.
224 if (const char *UsedDirective
= MAI
->getUsedDirective())
225 O
<< UsedDirective
<< EHFrameInfo
.FnName
<< "\n\n";
227 O
<< EHFrameInfo
.FnName
<< ":\n";
230 EmitDifference("eh_frame_end", EHFrameInfo
.Number
,
231 "eh_frame_begin", EHFrameInfo
.Number
, true);
232 Asm
->EOL("Length of Frame Information Entry");
234 EmitLabel("eh_frame_begin", EHFrameInfo
.Number
);
236 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
237 EHFrameInfo
.Number
, EHFrameInfo
.PersonalityIndex
,
240 Asm
->EOL("FDE CIE offset");
242 EmitReference("eh_func_begin", EHFrameInfo
.Number
, true, true);
243 Asm
->EOL("FDE initial location");
244 EmitDifference("eh_func_end", EHFrameInfo
.Number
,
245 "eh_func_begin", EHFrameInfo
.Number
, true);
246 Asm
->EOL("FDE address range");
248 // If there is a personality and landing pads then point to the language
249 // specific data area in the exception table.
250 if (MMI
->getPersonalities()[0] != NULL
) {
251 bool is4Byte
= TD
->getPointerSize() == sizeof(int32_t);
253 Asm
->EmitULEB128Bytes(is4Byte
? 4 : 8);
254 Asm
->EOL("Augmentation size");
256 if (EHFrameInfo
.hasLandingPads
)
257 EmitReference("exception", EHFrameInfo
.Number
, true, false);
260 Asm
->EmitInt32((int)0);
262 Asm
->EmitInt64((int)0);
264 Asm
->EOL("Language Specific Data Area");
266 Asm
->EmitULEB128Bytes(0);
267 Asm
->EOL("Augmentation size");
270 // Indicate locations of function specific callee saved registers in frame.
271 EmitFrameMoves("eh_func_begin", EHFrameInfo
.Number
, EHFrameInfo
.Moves
,
274 // On Darwin the linker honors the alignment of eh_frame, which means it
275 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
276 // get holes which confuse readers of eh_frame.
277 Asm
->EmitAlignment(TD
->getPointerSize() == sizeof(int32_t) ? 2 : 3,
279 EmitLabel("eh_frame_end", EHFrameInfo
.Number
);
281 // If the function is marked used, this table should be also. We cannot
282 // make the mark unconditional in this case, since retaining the table also
283 // retains the function in this case, and there is code around that depends
284 // on unused functions (calling undefined externals) being dead-stripped to
285 // link correctly. Yes, there really is.
286 if (MMI
->isUsedFunction(EHFrameInfo
.function
))
287 if (const char *UsedDirective
= MAI
->getUsedDirective())
288 O
<< UsedDirective
<< EHFrameInfo
.FnName
<< "\n\n";
294 /// SharedTypeIds - How many leading type ids two landing pads have in common.
295 unsigned DwarfException::SharedTypeIds(const LandingPadInfo
*L
,
296 const LandingPadInfo
*R
) {
297 const std::vector
<int> &LIds
= L
->TypeIds
, &RIds
= R
->TypeIds
;
298 unsigned LSize
= LIds
.size(), RSize
= RIds
.size();
299 unsigned MinSize
= LSize
< RSize
? LSize
: RSize
;
302 for (; Count
!= MinSize
; ++Count
)
303 if (LIds
[Count
] != RIds
[Count
])
309 /// PadLT - Order landing pads lexicographically by type id.
310 bool DwarfException::PadLT(const LandingPadInfo
*L
, const LandingPadInfo
*R
) {
311 const std::vector
<int> &LIds
= L
->TypeIds
, &RIds
= R
->TypeIds
;
312 unsigned LSize
= LIds
.size(), RSize
= RIds
.size();
313 unsigned MinSize
= LSize
< RSize
? LSize
: RSize
;
315 for (unsigned i
= 0; i
!= MinSize
; ++i
)
316 if (LIds
[i
] != RIds
[i
])
317 return LIds
[i
] < RIds
[i
];
319 return LSize
< RSize
;
322 /// ComputeActionsTable - Compute the actions table and gather the first action
323 /// index for each landing pad site.
324 unsigned DwarfException::
325 ComputeActionsTable(const SmallVectorImpl
<const LandingPadInfo
*> &LandingPads
,
326 SmallVectorImpl
<ActionEntry
> &Actions
,
327 SmallVectorImpl
<unsigned> &FirstActions
) {
329 // The action table follows the call-site table in the LSDA. The individual
330 // records are of two types:
333 // * Exception specification
335 // The two record kinds have the same format, with only small differences.
336 // They are distinguished by the "switch value" field: Catch clauses
337 // (TypeInfos) have strictly positive switch values, and exception
338 // specifications (FilterIds) have strictly negative switch values. Value 0
339 // indicates a catch-all clause.
341 // Negative type IDs index into FilterIds. Positive type IDs index into
342 // TypeInfos. The value written for a positive type ID is just the type ID
343 // itself. For a negative type ID, however, the value written is the
344 // (negative) byte offset of the corresponding FilterIds entry. The byte
345 // offset is usually equal to the type ID (because the FilterIds entries are
346 // written using a variable width encoding, which outputs one byte per entry
347 // as long as the value written is not too large) but can differ. This kind
348 // of complication does not occur for positive type IDs because type infos are
349 // output using a fixed width encoding. FilterOffsets[i] holds the byte
350 // offset corresponding to FilterIds[i].
352 const std::vector
<unsigned> &FilterIds
= MMI
->getFilterIds();
353 SmallVector
<int, 16> FilterOffsets
;
354 FilterOffsets
.reserve(FilterIds
.size());
357 for (std::vector
<unsigned>::const_iterator
358 I
= FilterIds
.begin(), E
= FilterIds
.end(); I
!= E
; ++I
) {
359 FilterOffsets
.push_back(Offset
);
360 Offset
-= MCAsmInfo::getULEB128Size(*I
);
363 FirstActions
.reserve(LandingPads
.size());
366 unsigned SizeActions
= 0;
367 const LandingPadInfo
*PrevLPI
= 0;
369 for (SmallVectorImpl
<const LandingPadInfo
*>::const_iterator
370 I
= LandingPads
.begin(), E
= LandingPads
.end(); I
!= E
; ++I
) {
371 const LandingPadInfo
*LPI
= *I
;
372 const std::vector
<int> &TypeIds
= LPI
->TypeIds
;
373 const unsigned NumShared
= PrevLPI
? SharedTypeIds(LPI
, PrevLPI
) : 0;
374 unsigned SizeSiteActions
= 0;
376 if (NumShared
< TypeIds
.size()) {
377 unsigned SizeAction
= 0;
378 ActionEntry
*PrevAction
= 0;
381 const unsigned SizePrevIds
= PrevLPI
->TypeIds
.size();
382 assert(Actions
.size());
383 PrevAction
= &Actions
.back();
384 SizeAction
= MCAsmInfo::getSLEB128Size(PrevAction
->NextAction
) +
385 MCAsmInfo::getSLEB128Size(PrevAction
->ValueForTypeID
);
387 for (unsigned j
= NumShared
; j
!= SizePrevIds
; ++j
) {
389 MCAsmInfo::getSLEB128Size(PrevAction
->ValueForTypeID
);
390 SizeAction
+= -PrevAction
->NextAction
;
391 PrevAction
= PrevAction
->Previous
;
395 // Compute the actions.
396 for (unsigned J
= NumShared
, M
= TypeIds
.size(); J
!= M
; ++J
) {
397 int TypeID
= TypeIds
[J
];
398 assert(-1 - TypeID
< (int)FilterOffsets
.size() && "Unknown filter id!");
399 int ValueForTypeID
= TypeID
< 0 ? FilterOffsets
[-1 - TypeID
] : TypeID
;
400 unsigned SizeTypeID
= MCAsmInfo::getSLEB128Size(ValueForTypeID
);
402 int NextAction
= SizeAction
? -(SizeAction
+ SizeTypeID
) : 0;
403 SizeAction
= SizeTypeID
+ MCAsmInfo::getSLEB128Size(NextAction
);
404 SizeSiteActions
+= SizeAction
;
406 ActionEntry Action
= { ValueForTypeID
, NextAction
, PrevAction
};
407 Actions
.push_back(Action
);
408 PrevAction
= &Actions
.back();
411 // Record the first action of the landing pad site.
412 FirstAction
= SizeActions
+ SizeSiteActions
- SizeAction
+ 1;
413 } // else identical - re-use previous FirstAction
415 // Information used when created the call-site table. The action record
416 // field of the call site record is the offset of the first associated
417 // action record, relative to the start of the actions table. This value is
418 // biased by 1 (1 in dicating the start of the actions table), and 0
419 // indicates that there are no actions.
420 FirstActions
.push_back(FirstAction
);
422 // Compute this sites contribution to size.
423 SizeActions
+= SizeSiteActions
;
431 /// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
432 /// has a try-range containing the call, a non-zero landing pad, and an
433 /// appropriate action. The entry for an ordinary call has a try-range
434 /// containing the call and zero for the landing pad and the action. Calls
435 /// marked 'nounwind' have no entry and must not be contained in the try-range
436 /// of any entry - they form gaps in the table. Entries must be ordered by
437 /// try-range address.
438 void DwarfException::
439 ComputeCallSiteTable(SmallVectorImpl
<CallSiteEntry
> &CallSites
,
440 const RangeMapType
&PadMap
,
441 const SmallVectorImpl
<const LandingPadInfo
*> &LandingPads
,
442 const SmallVectorImpl
<unsigned> &FirstActions
) {
443 // The end label of the previous invoke or nounwind try-range.
444 unsigned LastLabel
= 0;
446 // Whether there is a potentially throwing instruction (currently this means
447 // an ordinary call) between the end of the previous try-range and now.
448 bool SawPotentiallyThrowing
= false;
450 // Whether the last CallSite entry was for an invoke.
451 bool PreviousIsInvoke
= false;
453 // Visit all instructions in order of address.
454 for (MachineFunction::const_iterator I
= MF
->begin(), E
= MF
->end();
456 for (MachineBasicBlock::const_iterator MI
= I
->begin(), E
= I
->end();
458 if (!MI
->isLabel()) {
459 SawPotentiallyThrowing
|= MI
->getDesc().isCall();
463 unsigned BeginLabel
= MI
->getOperand(0).getImm();
464 assert(BeginLabel
&& "Invalid label!");
466 // End of the previous try-range?
467 if (BeginLabel
== LastLabel
)
468 SawPotentiallyThrowing
= false;
470 // Beginning of a new try-range?
471 RangeMapType::iterator L
= PadMap
.find(BeginLabel
);
472 if (L
== PadMap
.end())
473 // Nope, it was just some random label.
476 const PadRange
&P
= L
->second
;
477 const LandingPadInfo
*LandingPad
= LandingPads
[P
.PadIndex
];
478 assert(BeginLabel
== LandingPad
->BeginLabels
[P
.RangeIndex
] &&
479 "Inconsistent landing pad map!");
481 // For Dwarf exception handling (SjLj handling doesn't use this). If some
482 // instruction between the previous try-range and this one may throw,
483 // create a call-site entry with no landing pad for the region between the
485 if (SawPotentiallyThrowing
&&
486 MAI
->getExceptionHandlingType() == ExceptionHandling::Dwarf
) {
487 CallSiteEntry Site
= { LastLabel
, BeginLabel
, 0, 0 };
488 CallSites
.push_back(Site
);
489 PreviousIsInvoke
= false;
492 LastLabel
= LandingPad
->EndLabels
[P
.RangeIndex
];
493 assert(BeginLabel
&& LastLabel
&& "Invalid landing pad!");
495 if (LandingPad
->LandingPadLabel
) {
496 // This try-range is for an invoke.
497 CallSiteEntry Site
= {
500 LandingPad
->LandingPadLabel
,
501 FirstActions
[P
.PadIndex
]
504 // Try to merge with the previous call-site. SJLJ doesn't do this
505 if (PreviousIsInvoke
&&
506 MAI
->getExceptionHandlingType() == ExceptionHandling::Dwarf
) {
507 CallSiteEntry
&Prev
= CallSites
.back();
508 if (Site
.PadLabel
== Prev
.PadLabel
&& Site
.Action
== Prev
.Action
) {
509 // Extend the range of the previous entry.
510 Prev
.EndLabel
= Site
.EndLabel
;
515 // Otherwise, create a new call-site.
516 CallSites
.push_back(Site
);
517 PreviousIsInvoke
= true;
520 PreviousIsInvoke
= false;
525 // If some instruction between the previous try-range and the end of the
526 // function may throw, create a call-site entry with no landing pad for the
527 // region following the try-range.
528 if (SawPotentiallyThrowing
&&
529 MAI
->getExceptionHandlingType() == ExceptionHandling::Dwarf
) {
530 CallSiteEntry Site
= { LastLabel
, 0, 0, 0 };
531 CallSites
.push_back(Site
);
535 /// EmitExceptionTable - Emit landing pads and actions.
537 /// The general organization of the table is complex, but the basic concepts are
538 /// easy. First there is a header which describes the location and organization
539 /// of the three components that follow.
541 /// 1. The landing pad site information describes the range of code covered by
542 /// the try. In our case it's an accumulation of the ranges covered by the
543 /// invokes in the try. There is also a reference to the landing pad that
544 /// handles the exception once processed. Finally an index into the actions
546 /// 2. The action table, in our case, is composed of pairs of type IDs and next
547 /// action offset. Starting with the action index from the landing pad
548 /// site, each type ID is checked for a match to the current exception. If
549 /// it matches then the exception and type id are passed on to the landing
550 /// pad. Otherwise the next action is looked up. This chain is terminated
551 /// with a next action of zero. If no type id is found then the frame is
552 /// unwound and handling continues.
553 /// 3. Type ID table contains references to all the C++ typeinfo for all
554 /// catches in the function. This tables is reverse indexed base 1.
555 void DwarfException::EmitExceptionTable() {
556 const std::vector
<GlobalVariable
*> &TypeInfos
= MMI
->getTypeInfos();
557 const std::vector
<unsigned> &FilterIds
= MMI
->getFilterIds();
558 const std::vector
<LandingPadInfo
> &PadInfos
= MMI
->getLandingPads();
559 if (PadInfos
.empty()) return;
561 // Sort the landing pads in order of their type ids. This is used to fold
562 // duplicate actions.
563 SmallVector
<const LandingPadInfo
*, 64> LandingPads
;
564 LandingPads
.reserve(PadInfos
.size());
566 for (unsigned i
= 0, N
= PadInfos
.size(); i
!= N
; ++i
)
567 LandingPads
.push_back(&PadInfos
[i
]);
569 std::sort(LandingPads
.begin(), LandingPads
.end(), PadLT
);
571 // Compute the actions table and gather the first action index for each
573 SmallVector
<ActionEntry
, 32> Actions
;
574 SmallVector
<unsigned, 64> FirstActions
;
575 unsigned SizeActions
= ComputeActionsTable(LandingPads
, Actions
,
578 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
579 // by try-range labels when lowered). Ordinary calls do not, so appropriate
580 // try-ranges for them need be deduced when using DWARF exception handling.
582 for (unsigned i
= 0, N
= LandingPads
.size(); i
!= N
; ++i
) {
583 const LandingPadInfo
*LandingPad
= LandingPads
[i
];
584 for (unsigned j
= 0, E
= LandingPad
->BeginLabels
.size(); j
!= E
; ++j
) {
585 unsigned BeginLabel
= LandingPad
->BeginLabels
[j
];
586 assert(!PadMap
.count(BeginLabel
) && "Duplicate landing pad labels!");
587 PadRange P
= { i
, j
};
588 PadMap
[BeginLabel
] = P
;
592 // Compute the call-site table.
593 SmallVector
<CallSiteEntry
, 64> CallSites
;
594 ComputeCallSiteTable(CallSites
, PadMap
, LandingPads
, FirstActions
);
599 const unsigned SiteStartSize
= SizeOfEncodedValue(dwarf::DW_EH_PE_udata4
);
600 const unsigned SiteLengthSize
= SizeOfEncodedValue(dwarf::DW_EH_PE_udata4
);
601 const unsigned LandingPadSize
= SizeOfEncodedValue(dwarf::DW_EH_PE_udata4
);
602 bool IsSJLJ
= MAI
->getExceptionHandlingType() == ExceptionHandling::SjLj
;
603 bool HaveTTData
= IsSJLJ
? (!TypeInfos
.empty() || !FilterIds
.empty()) : true;
609 SizeSites
= CallSites
.size() *
610 (SiteStartSize
+ SiteLengthSize
+ LandingPadSize
);
612 for (unsigned i
= 0, e
= CallSites
.size(); i
< e
; ++i
) {
613 SizeSites
+= MCAsmInfo::getULEB128Size(CallSites
[i
].Action
);
615 SizeSites
+= MCAsmInfo::getULEB128Size(i
);
619 const MCSection
*LSDASection
= Asm
->getObjFileLowering().getLSDASection();
620 unsigned TTypeFormat
;
621 unsigned TypeFormatSize
;
624 // For SjLj exceptions, if there is no TypeInfo, then we just explicitly say
625 // that we're omitting that bit.
626 TTypeFormat
= dwarf::DW_EH_PE_omit
;
627 TypeFormatSize
= SizeOfEncodedValue(dwarf::DW_EH_PE_absptr
);
629 // Okay, we have actual filters or typeinfos to emit. As such, we need to
630 // pick a type encoding for them. We're about to emit a list of pointers to
631 // typeinfo objects at the end of the LSDA. However, unless we're in static
632 // mode, this reference will require a relocation by the dynamic linker.
634 // Because of this, we have a couple of options:
636 // 1) If we are in -static mode, we can always use an absolute reference
637 // from the LSDA, because the static linker will resolve it.
639 // 2) Otherwise, if the LSDA section is writable, we can output the direct
640 // reference to the typeinfo and allow the dynamic linker to relocate
641 // it. Since it is in a writable section, the dynamic linker won't
644 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
645 // we need to use some form of indirection. For example, on Darwin,
646 // we can output a statically-relocatable reference to a dyld stub. The
647 // offset to the stub is constant, but the contents are in a section
648 // that is updated by the dynamic linker. This is easy enough, but we
649 // need to tell the personality function of the unwinder to indirect
650 // through the dyld stub.
652 // FIXME: When (3) is actually implemented, we'll have to emit the stubs
653 // somewhere. This predicate should be moved to a shared location that is
654 // in target-independent code.
656 if (LSDASection
->getKind().isWriteable() ||
657 Asm
->TM
.getRelocationModel() == Reloc::Static
)
658 TTypeFormat
= dwarf::DW_EH_PE_absptr
;
660 TTypeFormat
= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
661 dwarf::DW_EH_PE_sdata4
;
663 TypeFormatSize
= SizeOfEncodedValue(TTypeFormat
);
666 // Begin the exception table.
667 Asm
->OutStreamer
.SwitchSection(LSDASection
);
668 Asm
->EmitAlignment(2, 0, 0, false);
670 O
<< "GCC_except_table" << SubprogramCount
<< ":\n";
672 // The type infos need to be aligned. GCC does this by inserting padding just
673 // before the type infos. However, this changes the size of the exception
674 // table, so you need to take this into account when you output the exception
675 // table size. However, the size is output using a variable length encoding.
676 // So by increasing the size by inserting padding, you may increase the number
677 // of bytes used for writing the size. If it increases, say by one byte, then
678 // you now need to output one less byte of padding to get the type infos
679 // aligned. However this decreases the size of the exception table. This
680 // changes the value you have to output for the exception table size. Due to
681 // the variable length encoding, the number of bytes used for writing the
682 // length may decrease. If so, you then have to increase the amount of
683 // padding. And so on. If you look carefully at the GCC code you will see that
684 // it indeed does this in a loop, going on and on until the values stabilize.
685 // We chose another solution: don't output padding inside the table like GCC
686 // does, instead output it before the table.
687 unsigned SizeTypes
= TypeInfos
.size() * TypeFormatSize
;
688 unsigned TyOffset
= sizeof(int8_t) + // Call site format
689 MCAsmInfo::getULEB128Size(SizeSites
) + // Call-site table length
690 SizeSites
+ SizeActions
+ SizeTypes
;
691 unsigned TotalSize
= sizeof(int8_t) + // LPStart format
692 sizeof(int8_t) + // TType format
694 MCAsmInfo::getULEB128Size(TyOffset
) : 0) + // TType base offset
696 unsigned SizeAlign
= (4 - TotalSize
) & 3;
698 for (unsigned i
= 0; i
!= SizeAlign
; ++i
) {
703 EmitLabel("exception", SubprogramCount
);
706 SmallString
<16> LSDAName
;
707 raw_svector_ostream(LSDAName
) << MAI
->getPrivateGlobalPrefix() <<
708 "_LSDA_" << Asm
->getFunctionNumber();
709 O
<< LSDAName
.str() << ":\n";
713 Asm
->EmitInt8(dwarf::DW_EH_PE_omit
);
714 Asm
->EOL("@LPStart format", dwarf::DW_EH_PE_omit
);
716 Asm
->EmitInt8(TTypeFormat
);
717 Asm
->EOL("@TType format", TTypeFormat
);
720 Asm
->EmitULEB128Bytes(TyOffset
);
721 Asm
->EOL("@TType base offset");
724 // SjLj Exception handling
726 Asm
->EmitInt8(dwarf::DW_EH_PE_udata4
);
727 Asm
->EOL("Call site format", dwarf::DW_EH_PE_udata4
);
728 Asm
->EmitULEB128Bytes(SizeSites
);
729 Asm
->EOL("Call site table length");
731 // Emit the landing pad site information.
733 for (SmallVectorImpl
<CallSiteEntry
>::const_iterator
734 I
= CallSites
.begin(), E
= CallSites
.end(); I
!= E
; ++I
, ++idx
) {
735 const CallSiteEntry
&S
= *I
;
737 // Offset of the landing pad, counted in 16-byte bundles relative to the
739 Asm
->EmitULEB128Bytes(idx
);
740 Asm
->EOL("Landing pad");
742 // Offset of the first associated action record, relative to the start of
743 // the action table. This value is biased by 1 (1 indicates the start of
744 // the action table), and 0 indicates that there are no actions.
745 Asm
->EmitULEB128Bytes(S
.Action
);
749 // DWARF Exception handling
750 assert(MAI
->getExceptionHandlingType() == ExceptionHandling::Dwarf
);
752 // The call-site table is a list of all call sites that may throw an
753 // exception (including C++ 'throw' statements) in the procedure
754 // fragment. It immediately follows the LSDA header. Each entry indicates,
755 // for a given call, the first corresponding action record and corresponding
758 // The table begins with the number of bytes, stored as an LEB128
759 // compressed, unsigned integer. The records immediately follow the record
760 // count. They are sorted in increasing call-site address. Each record
763 // * The position of the call-site.
764 // * The position of the landing pad.
765 // * The first action record for that call site.
767 // A missing entry in the call-site table indicates that a call is not
768 // supposed to throw.
770 // Emit the landing pad call site table.
771 Asm
->EmitInt8(dwarf::DW_EH_PE_udata4
);
772 Asm
->EOL("Call site format", dwarf::DW_EH_PE_udata4
);
773 Asm
->EmitULEB128Bytes(SizeSites
);
774 Asm
->EOL("Call site table size");
776 for (SmallVectorImpl
<CallSiteEntry
>::const_iterator
777 I
= CallSites
.begin(), E
= CallSites
.end(); I
!= E
; ++I
) {
778 const CallSiteEntry
&S
= *I
;
779 const char *BeginTag
;
780 unsigned BeginNumber
;
783 BeginTag
= "eh_func_begin";
784 BeginNumber
= SubprogramCount
;
787 BeginNumber
= S
.BeginLabel
;
790 // Offset of the call site relative to the previous call site, counted in
791 // number of 16-byte bundles. The first call site is counted relative to
792 // the start of the procedure fragment.
793 EmitSectionOffset(BeginTag
, "eh_func_begin", BeginNumber
, SubprogramCount
,
795 Asm
->EOL("Region start");
798 EmitDifference("eh_func_end", SubprogramCount
, BeginTag
, BeginNumber
,
801 EmitDifference("label", S
.EndLabel
, BeginTag
, BeginNumber
, true);
803 Asm
->EOL("Region length");
805 // Offset of the landing pad, counted in 16-byte bundles relative to the
810 EmitSectionOffset("label", "eh_func_begin", S
.PadLabel
, SubprogramCount
,
813 Asm
->EOL("Landing pad");
815 // Offset of the first associated action record, relative to the start of
816 // the action table. This value is biased by 1 (1 indicates the start of
817 // the action table), and 0 indicates that there are no actions.
818 Asm
->EmitULEB128Bytes(S
.Action
);
823 // Emit the Action Table.
824 for (SmallVectorImpl
<ActionEntry
>::const_iterator
825 I
= Actions
.begin(), E
= Actions
.end(); I
!= E
; ++I
) {
826 const ActionEntry
&Action
= *I
;
830 // Used by the runtime to match the type of the thrown exception to the
831 // type of the catch clauses or the types in the exception specification.
833 Asm
->EmitSLEB128Bytes(Action
.ValueForTypeID
);
834 Asm
->EOL("TypeInfo index");
838 // Self-relative signed displacement in bytes of the next action record,
839 // or 0 if there is no next action record.
841 Asm
->EmitSLEB128Bytes(Action
.NextAction
);
842 Asm
->EOL("Next action");
845 // Emit the Catch Clauses. The code for the catch clauses following the same
846 // try is similar to a switch statement. The catch clause action record
847 // informs the runtime about the type of a catch clause and about the
848 // associated switch value.
850 // Action Record Fields:
853 // Positive value, starting at 1. Index in the types table of the
854 // __typeinfo for the catch-clause type. 1 is the first word preceding
855 // TTBase, 2 is the second word, and so on. Used by the runtime to check
856 // if the thrown exception type matches the catch-clause type. Back-end
857 // generated switch statements check against this value.
860 // Signed offset, in bytes from the start of this field, to the next
861 // chained action record, or zero if none.
863 // The order of the action records determined by the next field is the order
864 // of the catch clauses as they appear in the source code, and must be kept in
865 // the same order. As a result, changing the order of the catch clause would
866 // change the semantics of the program.
867 for (std::vector
<GlobalVariable
*>::const_reverse_iterator
868 I
= TypeInfos
.rbegin(), E
= TypeInfos
.rend(); I
!= E
; ++I
) {
869 const GlobalVariable
*GV
= *I
;
874 O
<< Asm
->getGlobalLinkName(GV
, GLN
);
879 Asm
->EOL("TypeInfo");
882 // Emit the Type Table.
883 for (std::vector
<unsigned>::const_iterator
884 I
= FilterIds
.begin(), E
= FilterIds
.end(); I
< E
; ++I
) {
885 unsigned TypeID
= *I
;
886 Asm
->EmitULEB128Bytes(TypeID
);
887 Asm
->EOL("Filter TypeInfo index");
890 Asm
->EmitAlignment(2, 0, 0, false);
893 /// EndModule - Emit all exception information that should come after the
895 void DwarfException::EndModule() {
896 if (MAI
->getExceptionHandlingType() != ExceptionHandling::Dwarf
)
899 if (!shouldEmitMovesModule
&& !shouldEmitTableModule
)
902 if (TimePassesIsEnabled
)
903 ExceptionTimer
->startTimer();
905 const std::vector
<Function
*> Personalities
= MMI
->getPersonalities();
907 for (unsigned I
= 0, E
= Personalities
.size(); I
< E
; ++I
)
908 EmitCIE(Personalities
[I
], I
);
910 for (std::vector
<FunctionEHFrameInfo
>::iterator
911 I
= EHFrames
.begin(), E
= EHFrames
.end(); I
!= E
; ++I
)
914 if (TimePassesIsEnabled
)
915 ExceptionTimer
->stopTimer();
918 /// BeginFunction - Gather pre-function exception information. Assumes it's
919 /// being emitted immediately after the function entry point.
920 void DwarfException::BeginFunction(MachineFunction
*MF
) {
921 if (!MMI
|| !MAI
->doesSupportExceptionHandling()) return;
923 if (TimePassesIsEnabled
)
924 ExceptionTimer
->startTimer();
927 shouldEmitTable
= shouldEmitMoves
= false;
929 // Map all labels and get rid of any dead landing pads.
930 MMI
->TidyLandingPads();
932 // If any landing pads survive, we need an EH table.
933 if (!MMI
->getLandingPads().empty())
934 shouldEmitTable
= true;
936 // See if we need frame move info.
937 if (!MF
->getFunction()->doesNotThrow() || UnwindTablesMandatory
)
938 shouldEmitMoves
= true;
940 if (shouldEmitMoves
|| shouldEmitTable
)
941 // Assumes in correct section after the entry point.
942 EmitLabel("eh_func_begin", ++SubprogramCount
);
944 shouldEmitTableModule
|= shouldEmitTable
;
945 shouldEmitMovesModule
|= shouldEmitMoves
;
947 if (TimePassesIsEnabled
)
948 ExceptionTimer
->stopTimer();
951 /// EndFunction - Gather and emit post-function exception information.
953 void DwarfException::EndFunction() {
954 if (!shouldEmitMoves
&& !shouldEmitTable
) return;
956 if (TimePassesIsEnabled
)
957 ExceptionTimer
->startTimer();
959 EmitLabel("eh_func_end", SubprogramCount
);
960 EmitExceptionTable();
962 // Save EH frame information
963 EHFrames
.push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF
),
965 MMI
->getPersonalityIndex(),
966 MF
->getFrameInfo()->hasCalls(),
967 !MMI
->getLandingPads().empty(),
968 MMI
->getFrameMoves(),
971 // Record if this personality index uses a landing pad.
972 UsesLSDA
[MMI
->getPersonalityIndex()] |= !MMI
->getLandingPads().empty();
974 if (TimePassesIsEnabled
)
975 ExceptionTimer
->stopTimer();