blob: 7ab0bb0975a4622171b3ac1cd86dd21dfb70659b [file] [log] [blame]
Bill Wendlingeb907212009-05-15 01:12:28 +00001//===-- CodeGen/AsmPrinter/DwarfException.cpp - Dwarf Exception Impl ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains support for writing dwarf exception info into asm files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DwarfException.h"
15#include "llvm/Module.h"
16#include "llvm/CodeGen/MachineModuleInfo.h"
17#include "llvm/CodeGen/MachineFrameInfo.h"
18#include "llvm/CodeGen/MachineLocation.h"
19#include "llvm/Support/Dwarf.h"
20#include "llvm/Support/Timer.h"
21#include "llvm/Support/raw_ostream.h"
22#include "llvm/Target/TargetAsmInfo.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000023#include "llvm/Target/TargetData.h"
24#include "llvm/Target/TargetFrameInfo.h"
Chris Lattnerd5bbb072009-08-02 01:34:32 +000025#include "llvm/Target/TargetLoweringObjectFile.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000026#include "llvm/Target/TargetOptions.h"
Chris Lattnerd5bbb072009-08-02 01:34:32 +000027#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000028#include "llvm/ADT/StringExtras.h"
29using namespace llvm;
30
31static TimerGroup &getDwarfTimerGroup() {
32 static TimerGroup DwarfTimerGroup("Dwarf Exception");
33 return DwarfTimerGroup;
34}
35
Bill Wendlingbc0d23a2009-05-15 01:18:50 +000036DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A,
37 const TargetAsmInfo *T)
38 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
39 shouldEmitTableModule(false), shouldEmitMovesModule(false),
40 ExceptionTimer(0) {
41 if (TimePassesIsEnabled)
42 ExceptionTimer = new Timer("Dwarf Exception Writer",
43 getDwarfTimerGroup());
44}
45
46DwarfException::~DwarfException() {
47 delete ExceptionTimer;
48}
49
Bill Wendlingeb907212009-05-15 01:12:28 +000050void DwarfException::EmitCommonEHFrame(const Function *Personality,
51 unsigned Index) {
52 // Size and sign of stack growth.
53 int stackGrowth =
54 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
55 TargetFrameInfo::StackGrowsUp ?
56 TD->getPointerSize() : -TD->getPointerSize();
57
58 // Begin eh frame section.
Chris Lattner6a66e582009-08-18 06:13:03 +000059 // FIXME: THIS IS A HORRIBLE HACK. MingW isn't specifying an EHFrame section.
60 if (const MCSection *EHFrameSec =
61 Asm->getObjFileLowering().getEHFrameSection())
62 Asm->SwitchToSection(EHFrameSec);
Bill Wendlingeb907212009-05-15 01:12:28 +000063
Chris Lattnere2cf37b2009-07-17 20:46:40 +000064 if (TAI->is_EHSymbolPrivate())
65 O << TAI->getPrivateGlobalPrefix();
Bill Wendlingeb907212009-05-15 01:12:28 +000066
67 O << "EH_frame" << Index << ":\n";
68 EmitLabel("section_eh_frame", Index);
69
70 // Define base labels.
71 EmitLabel("eh_frame_common", Index);
72
73 // Define the eh frame length.
74 EmitDifference("eh_frame_common_end", Index,
75 "eh_frame_common_begin", Index, true);
76 Asm->EOL("Length of Common Information Entry");
77
78 // EH frame header.
79 EmitLabel("eh_frame_common_begin", Index);
80 Asm->EmitInt32((int)0);
81 Asm->EOL("CIE Identifier Tag");
82 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
83 Asm->EOL("CIE Version");
84
85 // The personality presence indicates that language specific information will
86 // show up in the eh frame.
87 Asm->EmitString(Personality ? "zPLR" : "zR");
88 Asm->EOL("CIE Augmentation");
89
90 // Round out reader.
91 Asm->EmitULEB128Bytes(1);
92 Asm->EOL("CIE Code Alignment Factor");
93 Asm->EmitSLEB128Bytes(stackGrowth);
94 Asm->EOL("CIE Data Alignment Factor");
95 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
96 Asm->EOL("CIE Return Address Column");
97
98 // If there is a personality, we need to indicate the functions location.
99 if (Personality) {
100 Asm->EmitULEB128Bytes(7);
101 Asm->EOL("Augmentation Size");
102
103 if (TAI->getNeedsIndirectEncoding()) {
104 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 |
105 dwarf::DW_EH_PE_indirect);
106 Asm->EOL("Personality (pcrel sdata4 indirect)");
107 } else {
108 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
109 Asm->EOL("Personality (pcrel sdata4)");
110 }
111
112 PrintRelDirective(true);
113 O << TAI->getPersonalityPrefix();
114 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
115 O << TAI->getPersonalitySuffix();
116 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
117 O << "-" << TAI->getPCSymbol();
118 Asm->EOL("Personality");
119
120 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
121 Asm->EOL("LSDA Encoding (pcrel sdata4)");
122
123 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
124 Asm->EOL("FDE Encoding (pcrel sdata4)");
125 } else {
126 Asm->EmitULEB128Bytes(1);
127 Asm->EOL("Augmentation Size");
128
129 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
130 Asm->EOL("FDE Encoding (pcrel sdata4)");
131 }
132
133 // Indicate locations of general callee saved registers in frame.
134 std::vector<MachineMove> Moves;
135 RI->getInitialFrameState(Moves);
136 EmitFrameMoves(NULL, 0, Moves, true);
137
138 // On Darwin the linker honors the alignment of eh_frame, which means it must
139 // be 8-byte on 64-bit targets to match what gcc does. Otherwise you get
140 // holes which confuse readers of eh_frame.
141 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
142 0, 0, false);
143 EmitLabel("eh_frame_common_end", Index);
144
145 Asm->EOL();
146}
147
148/// EmitEHFrame - Emit function exception frame information.
149///
150void DwarfException::EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
151 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
152 "Should not emit 'available externally' functions at all");
153
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000154 const Function *TheFunc = EHFrameInfo.function;
155
Chris Lattner6a66e582009-08-18 06:13:03 +0000156 // FIXME: THIS IS A HORRIBLE HACK. MingW isn't specifying an EHFrame section.
157 if (const MCSection *EHFrameSec =
158 Asm->getObjFileLowering().getEHFrameSection())
159 Asm->SwitchToSection(EHFrameSec);
160
Bill Wendlingeb907212009-05-15 01:12:28 +0000161 // Externally visible entry into the functions eh frame info. If the
162 // corresponding function is static, this should not be externally visible.
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000163 if (!TheFunc->hasLocalLinkage())
Bill Wendlingeb907212009-05-15 01:12:28 +0000164 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
165 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
Bill Wendlingeb907212009-05-15 01:12:28 +0000166
167 // If corresponding function is weak definition, this should be too.
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000168 if (TheFunc->isWeakForLinker() && TAI->getWeakDefDirective())
Bill Wendlingeb907212009-05-15 01:12:28 +0000169 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
170
171 // If there are no calls then you can't unwind. This may mean we can omit the
172 // EH Frame, but some environments do not handle weak absolute symbols. If
173 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
174 // info is to be available for non-EH uses.
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000175 if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
176 (!TheFunc->isWeakForLinker() ||
Bill Wendlingeb907212009-05-15 01:12:28 +0000177 !TAI->getWeakDefDirective() ||
178 TAI->getSupportsWeakOmittedEHFrame())) {
179 O << EHFrameInfo.FnName << " = 0\n";
180 // This name has no connection to the function, so it might get
181 // dead-stripped when the function is not, erroneously. Prohibit
182 // dead-stripping unconditionally.
183 if (const char *UsedDirective = TAI->getUsedDirective())
184 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
185 } else {
186 O << EHFrameInfo.FnName << ":\n";
187
188 // EH frame header.
189 EmitDifference("eh_frame_end", EHFrameInfo.Number,
190 "eh_frame_begin", EHFrameInfo.Number, true);
191 Asm->EOL("Length of Frame Information Entry");
192
193 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
194
Chris Lattnera4ff5e42009-07-17 20:53:51 +0000195 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
196 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
197 true, true, false);
Bill Wendlingeb907212009-05-15 01:12:28 +0000198
199 Asm->EOL("FDE CIE offset");
200
201 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
202 Asm->EOL("FDE initial location");
203 EmitDifference("eh_func_end", EHFrameInfo.Number,
204 "eh_func_begin", EHFrameInfo.Number, true);
205 Asm->EOL("FDE address range");
206
207 // If there is a personality and landing pads then point to the language
208 // specific data area in the exception table.
209 if (EHFrameInfo.PersonalityIndex) {
210 Asm->EmitULEB128Bytes(4);
211 Asm->EOL("Augmentation size");
212
213 if (EHFrameInfo.hasLandingPads)
214 EmitReference("exception", EHFrameInfo.Number, true, true);
215 else
216 Asm->EmitInt32((int)0);
217 Asm->EOL("Language Specific Data Area");
218 } else {
219 Asm->EmitULEB128Bytes(0);
220 Asm->EOL("Augmentation size");
221 }
222
223 // Indicate locations of function specific callee saved registers in frame.
224 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
225 true);
226
227 // On Darwin the linker honors the alignment of eh_frame, which means it
228 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
229 // get holes which confuse readers of eh_frame.
230 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
231 0, 0, false);
232 EmitLabel("eh_frame_end", EHFrameInfo.Number);
233
234 // If the function is marked used, this table should be also. We cannot
235 // make the mark unconditional in this case, since retaining the table also
236 // retains the function in this case, and there is code around that depends
237 // on unused functions (calling undefined externals) being dead-stripped to
238 // link correctly. Yes, there really is.
Chris Lattner401e10c2009-07-20 06:14:25 +0000239 if (MMI->isUsedFunction(EHFrameInfo.function))
Bill Wendlingeb907212009-05-15 01:12:28 +0000240 if (const char *UsedDirective = TAI->getUsedDirective())
241 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
242 }
243}
244
Bill Wendlingeb907212009-05-15 01:12:28 +0000245/// SharedTypeIds - How many leading type ids two landing pads have in common.
246unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
247 const LandingPadInfo *R) {
248 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
249 unsigned LSize = LIds.size(), RSize = RIds.size();
250 unsigned MinSize = LSize < RSize ? LSize : RSize;
251 unsigned Count = 0;
252
253 for (; Count != MinSize; ++Count)
254 if (LIds[Count] != RIds[Count])
255 return Count;
256
257 return Count;
258}
259
260/// PadLT - Order landing pads lexicographically by type id.
261bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
262 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
263 unsigned LSize = LIds.size(), RSize = RIds.size();
264 unsigned MinSize = LSize < RSize ? LSize : RSize;
265
266 for (unsigned i = 0; i != MinSize; ++i)
267 if (LIds[i] != RIds[i])
268 return LIds[i] < RIds[i];
269
270 return LSize < RSize;
271}
272
Bill Wendlingd4609622009-07-28 23:23:00 +0000273/// ComputeActionsTable - Compute the actions table and gather the first action
274/// index for each landing pad site.
Bill Wendlingade025c2009-07-29 00:31:35 +0000275unsigned DwarfException::
276ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
277 SmallVectorImpl<ActionEntry> &Actions,
278 SmallVectorImpl<unsigned> &FirstActions) {
Bill Wendling5e953dd2009-07-28 23:22:13 +0000279 // Negative type IDs index into FilterIds. Positive type IDs index into
280 // TypeInfos. The value written for a positive type ID is just the type ID
281 // itself. For a negative type ID, however, the value written is the
Bill Wendlingeb907212009-05-15 01:12:28 +0000282 // (negative) byte offset of the corresponding FilterIds entry. The byte
Bill Wendling5e953dd2009-07-28 23:22:13 +0000283 // offset is usually equal to the type ID (because the FilterIds entries are
284 // written using a variable width encoding, which outputs one byte per entry
285 // as long as the value written is not too large) but can differ. This kind
286 // of complication does not occur for positive type IDs because type infos are
Bill Wendlingeb907212009-05-15 01:12:28 +0000287 // output using a fixed width encoding. FilterOffsets[i] holds the byte
288 // offset corresponding to FilterIds[i].
Bill Wendling409914b2009-07-29 21:19:44 +0000289
290 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
Bill Wendlingeb907212009-05-15 01:12:28 +0000291 SmallVector<int, 16> FilterOffsets;
292 FilterOffsets.reserve(FilterIds.size());
293 int Offset = -1;
Bill Wendling409914b2009-07-29 21:19:44 +0000294
295 for (std::vector<unsigned>::const_iterator
296 I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000297 FilterOffsets.push_back(Offset);
298 Offset -= TargetAsmInfo::getULEB128Size(*I);
299 }
300
Bill Wendlingeb907212009-05-15 01:12:28 +0000301 FirstActions.reserve(LandingPads.size());
302
303 int FirstAction = 0;
304 unsigned SizeActions = 0;
Bill Wendling5e953dd2009-07-28 23:22:13 +0000305 const LandingPadInfo *PrevLPI = 0;
Bill Wendling409914b2009-07-29 21:19:44 +0000306
Bill Wendling5cff4872009-07-28 23:44:43 +0000307 for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
Bill Wendling5e953dd2009-07-28 23:22:13 +0000308 I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
309 const LandingPadInfo *LPI = *I;
310 const std::vector<int> &TypeIds = LPI->TypeIds;
311 const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
Bill Wendlingeb907212009-05-15 01:12:28 +0000312 unsigned SizeSiteActions = 0;
313
314 if (NumShared < TypeIds.size()) {
315 unsigned SizeAction = 0;
316 ActionEntry *PrevAction = 0;
317
318 if (NumShared) {
Bill Wendling5e953dd2009-07-28 23:22:13 +0000319 const unsigned SizePrevIds = PrevLPI->TypeIds.size();
Bill Wendlingeb907212009-05-15 01:12:28 +0000320 assert(Actions.size());
321 PrevAction = &Actions.back();
322 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
323 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
324
325 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
326 SizeAction -=
327 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
328 SizeAction += -PrevAction->NextAction;
329 PrevAction = PrevAction->Previous;
330 }
331 }
332
333 // Compute the actions.
Bill Wendling5e953dd2009-07-28 23:22:13 +0000334 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
335 int TypeID = TypeIds[J];
336 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
Bill Wendlingeb907212009-05-15 01:12:28 +0000337 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
338 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
339
340 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
341 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
342 SizeSiteActions += SizeAction;
343
344 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
345 Actions.push_back(Action);
Bill Wendlingeb907212009-05-15 01:12:28 +0000346 PrevAction = &Actions.back();
347 }
348
349 // Record the first action of the landing pad site.
350 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
351 } // else identical - re-use previous FirstAction
352
353 FirstActions.push_back(FirstAction);
354
355 // Compute this sites contribution to size.
356 SizeActions += SizeSiteActions;
Bill Wendling5e953dd2009-07-28 23:22:13 +0000357
358 PrevLPI = LPI;
Bill Wendlingeb907212009-05-15 01:12:28 +0000359 }
360
Bill Wendling5e953dd2009-07-28 23:22:13 +0000361 return SizeActions;
362}
363
Bill Wendlingade025c2009-07-29 00:31:35 +0000364/// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
365/// has a try-range containing the call, a non-zero landing pad and an
366/// appropriate action. The entry for an ordinary call has a try-range
367/// containing the call and zero for the landing pad and the action. Calls
368/// marked 'nounwind' have no entry and must not be contained in the try-range
369/// of any entry - they form gaps in the table. Entries must be ordered by
370/// try-range address.
371void DwarfException::
372ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
373 const RangeMapType &PadMap,
374 const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
375 const SmallVectorImpl<unsigned> &FirstActions) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000376 // The end label of the previous invoke or nounwind try-range.
377 unsigned LastLabel = 0;
378
379 // Whether there is a potentially throwing instruction (currently this means
380 // an ordinary call) between the end of the previous try-range and now.
381 bool SawPotentiallyThrowing = false;
382
Bill Wendling5cff4872009-07-28 23:44:43 +0000383 // Whether the last CallSite entry was for an invoke.
Bill Wendlingeb907212009-05-15 01:12:28 +0000384 bool PreviousIsInvoke = false;
385
386 // Visit all instructions in order of address.
387 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
388 I != E; ++I) {
389 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
390 MI != E; ++MI) {
391 if (!MI->isLabel()) {
392 SawPotentiallyThrowing |= MI->getDesc().isCall();
393 continue;
394 }
395
396 unsigned BeginLabel = MI->getOperand(0).getImm();
397 assert(BeginLabel && "Invalid label!");
398
399 // End of the previous try-range?
400 if (BeginLabel == LastLabel)
401 SawPotentiallyThrowing = false;
402
403 // Beginning of a new try-range?
404 RangeMapType::iterator L = PadMap.find(BeginLabel);
405 if (L == PadMap.end())
406 // Nope, it was just some random label.
407 continue;
408
409 PadRange P = L->second;
410 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
Bill Wendlingeb907212009-05-15 01:12:28 +0000411 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
412 "Inconsistent landing pad map!");
413
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000414 // For Dwarf exception handling (SjLj handling doesn't use this)
Bill Wendlingeb907212009-05-15 01:12:28 +0000415 // If some instruction between the previous try-range and this one may
416 // throw, create a call-site entry with no landing pad for the region
417 // between the try-ranges.
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000418 if (SawPotentiallyThrowing &&
419 TAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000420 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
421 CallSites.push_back(Site);
422 PreviousIsInvoke = false;
423 }
424
425 LastLabel = LandingPad->EndLabels[P.RangeIndex];
426 assert(BeginLabel && LastLabel && "Invalid landing pad!");
427
428 if (LandingPad->LandingPadLabel) {
429 // This try-range is for an invoke.
430 CallSiteEntry Site = {BeginLabel, LastLabel,
431 LandingPad->LandingPadLabel,
432 FirstActions[P.PadIndex]};
433
434 // Try to merge with the previous call-site.
435 if (PreviousIsInvoke) {
436 CallSiteEntry &Prev = CallSites.back();
437 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
438 // Extend the range of the previous entry.
439 Prev.EndLabel = Site.EndLabel;
440 continue;
441 }
442 }
443
444 // Otherwise, create a new call-site.
445 CallSites.push_back(Site);
446 PreviousIsInvoke = true;
447 } else {
448 // Create a gap.
449 PreviousIsInvoke = false;
450 }
451 }
452 }
453
454 // If some instruction between the previous try-range and the end of the
455 // function may throw, create a call-site entry with no landing pad for the
456 // region following the try-range.
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000457 if (SawPotentiallyThrowing &&
458 TAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000459 CallSiteEntry Site = {LastLabel, 0, 0, 0};
460 CallSites.push_back(Site);
461 }
Bill Wendlingade025c2009-07-29 00:31:35 +0000462}
463
Bill Wendling0dafca92009-07-29 00:50:05 +0000464/// EmitExceptionTable - Emit landing pads and actions.
465///
466/// The general organization of the table is complex, but the basic concepts are
467/// easy. First there is a header which describes the location and organization
468/// of the three components that follow.
469///
470/// 1. The landing pad site information describes the range of code covered by
471/// the try. In our case it's an accumulation of the ranges covered by the
472/// invokes in the try. There is also a reference to the landing pad that
473/// handles the exception once processed. Finally an index into the actions
474/// table.
475/// 2. The action table, in our case, is composed of pairs of type ids and next
476/// action offset. Starting with the action index from the landing pad
477/// site, each type Id is checked for a match to the current exception. If
478/// it matches then the exception and type id are passed on to the landing
479/// pad. Otherwise the next action is looked up. This chain is terminated
480/// with a next action of zero. If no type id is found the the frame is
481/// unwound and handling continues.
482/// 3. Type id table contains references to all the C++ typeinfo for all
483/// catches in the function. This tables is reversed indexed base 1.
Bill Wendlingade025c2009-07-29 00:31:35 +0000484void DwarfException::EmitExceptionTable() {
485 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
486 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
487 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
488 if (PadInfos.empty()) return;
489
490 // Sort the landing pads in order of their type ids. This is used to fold
491 // duplicate actions.
492 SmallVector<const LandingPadInfo *, 64> LandingPads;
493 LandingPads.reserve(PadInfos.size());
494
495 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
496 LandingPads.push_back(&PadInfos[i]);
497
498 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
499
500 // Compute the actions table and gather the first action index for each
501 // landing pad site.
502 SmallVector<ActionEntry, 32> Actions;
503 SmallVector<unsigned, 64> FirstActions;
504 unsigned SizeActions = ComputeActionsTable(LandingPads, Actions, FirstActions);
505
506 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
507 // by try-range labels when lowered). Ordinary calls do not, so appropriate
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000508 // try-ranges for them need be deduced when using Dwarf exception handling.
Bill Wendlingade025c2009-07-29 00:31:35 +0000509 RangeMapType PadMap;
510 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
511 const LandingPadInfo *LandingPad = LandingPads[i];
512 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
513 unsigned BeginLabel = LandingPad->BeginLabels[j];
514 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
515 PadRange P = { i, j };
516 PadMap[BeginLabel] = P;
517 }
518 }
519
520 // Compute the call-site table.
521 SmallVector<CallSiteEntry, 64> CallSites;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000522 ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
Bill Wendlingeb907212009-05-15 01:12:28 +0000523
524 // Final tallies.
525
526 // Call sites.
527 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
528 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
529 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000530 unsigned SizeSites;
Jim Grosbachbff39232009-08-12 17:38:44 +0000531
532 bool HaveTTData = (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
533 ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
534
535
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000536 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000537 SizeSites = 0;
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000538 } else
539 SizeSites = CallSites.size() *
540 (SiteStartSize + SiteLengthSize + LandingPadSize);
541 for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000542 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000543 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
544 SizeSites += TargetAsmInfo::getULEB128Size(i);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000545 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000546 // Type infos.
547 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
548 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
549
550 unsigned TypeOffset = sizeof(int8_t) + // Call site format
551 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
552 SizeSites + SizeActions + SizeTypes;
553
554 unsigned TotalSize = sizeof(int8_t) + // LPStart format
555 sizeof(int8_t) + // TType format
Jim Grosbachbff39232009-08-12 17:38:44 +0000556 (HaveTTData ?
557 TargetAsmInfo::getULEB128Size(TypeOffset) : 0) + // TType base offset
Bill Wendlingeb907212009-05-15 01:12:28 +0000558 TypeOffset;
559
560 unsigned SizeAlign = (4 - TotalSize) & 3;
561
562 // Begin the exception table.
Chris Lattnerd5bbb072009-08-02 01:34:32 +0000563 const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
564 Asm->SwitchToSection(LSDASection);
Bill Wendlingeb907212009-05-15 01:12:28 +0000565 Asm->EmitAlignment(2, 0, 0, false);
566 O << "GCC_except_table" << SubprogramCount << ":\n";
567
568 for (unsigned i = 0; i != SizeAlign; ++i) {
569 Asm->EmitInt8(0);
570 Asm->EOL("Padding");
Bill Wendlingc5800a82009-07-28 21:54:03 +0000571 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000572
573 EmitLabel("exception", SubprogramCount);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000574 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
575 std::string SjLjName = "_lsda_";
576 SjLjName += MF->getFunction()->getName().str();
577 EmitLabel(SjLjName.c_str(), 0);
578 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000579
580 // Emit the header.
581 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
582 Asm->EOL("LPStart format (DW_EH_PE_omit)");
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000583
Bill Wendlingade025c2009-07-29 00:31:35 +0000584#if 0
Chris Lattner81c9a062009-07-31 22:03:47 +0000585 if (TypeInfos.empty() && FilterIds.empty()) {
Chris Lattnerad88bc42009-08-02 03:59:56 +0000586 // If there are no typeinfos or filters, there is nothing to emit, optimize
587 // by specifying the "omit" encoding.
Chris Lattner81c9a062009-07-31 22:03:47 +0000588 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
589 Asm->EOL("TType format (DW_EH_PE_omit)");
590 } else {
Chris Lattnerad88bc42009-08-02 03:59:56 +0000591 // Okay, we have actual filters or typeinfos to emit. As such, we need to
592 // pick a type encoding for them. We're about to emit a list of pointers to
593 // typeinfo objects at the end of the LSDA. However, unless we're in static
594 // mode, this reference will require a relocation by the dynamic linker.
Chris Lattner46b754c2009-07-31 22:18:14 +0000595 //
Chris Lattnerad88bc42009-08-02 03:59:56 +0000596 // Because of this, we have a couple of options:
597 // 1) If we are in -static mode, we can always use an absolute reference
598 // from the LSDA, because the static linker will resolve it.
599 // 2) Otherwise, if the LSDA section is writable, we can output the direct
600 // reference to the typeinfo and allow the dynamic linker to relocate
601 // it. Since it is in a writable section, the dynamic linker won't
602 // have a problem.
603 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
604 // we need to use some form of indirection. For example, on Darwin,
605 // we can output a statically-relocatable reference to a dyld stub. The
606 // offset to the stub is constant, but the contents are in a section
607 // that is updated by the dynamic linker. This is easy enough, but we
608 // need to tell the personality function of the unwinder to indirect
609 // through the dyld stub.
610 //
611 // FIXME: When this is actually implemented, we'll have to emit the stubs
612 // somewhere. This predicate should be moved to a shared location that is
613 // in target-independent code.
614 //
615 if (LSDASection->isWritable() ||
616 Asm->TM.getRelocationModel() == Reloc::Static) {
617 Asm->EmitInt8(DW_EH_PE_absptr);
618 Asm->EOL("TType format (DW_EH_PE_absptr)");
619 } else {
620 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_indirect | DW_EH_PE_sdata4);
621 Asm->EOL("TType format (DW_EH_PE_pcrel | DW_EH_PE_indirect"
622 " | DW_EH_PE_sdata4)");
623 }
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000624 Asm->EmitULEB128Bytes(TypeOffset);
625 Asm->EOL("TType base offset");
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000626 }
Bill Wendlingade025c2009-07-29 00:31:35 +0000627#else
Jim Grosbachbff39232009-08-12 17:38:44 +0000628 // For SjLj exceptions, if there is no TypeInfo, then we just explicitly
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000629 // say that we're omitting that bit.
630 // FIXME: does this apply to Dwarf also? The above #if 0 implies yes?
Jim Grosbachbff39232009-08-12 17:38:44 +0000631 if (!HaveTTData) {
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000632 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
633 Asm->EOL("TType format (DW_EH_PE_omit)");
634 } else {
635 Asm->EmitInt8(dwarf::DW_EH_PE_absptr);
636 Asm->EOL("TType format (DW_EH_PE_absptr)");
637 Asm->EmitULEB128Bytes(TypeOffset);
638 Asm->EOL("TType base offset");
639 }
Bill Wendlingade025c2009-07-29 00:31:35 +0000640#endif
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000641
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000642 // SjLj Exception handilng
643 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
644 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
645 Asm->EOL("Call site format (DW_EH_PE_udata4)");
646 Asm->EmitULEB128Bytes(SizeSites);
647 Asm->EOL("Call-site table length");
Bill Wendlingeb907212009-05-15 01:12:28 +0000648
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000649 // Emit the landing pad site information.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000650 unsigned idx = 0;
651 for (SmallVectorImpl<CallSiteEntry>::const_iterator
652 I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
653 const CallSiteEntry &S = *I;
654 Asm->EmitULEB128Bytes(idx);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000655 Asm->EOL("Landing pad");
656 Asm->EmitULEB128Bytes(S.Action);
657 Asm->EOL("Action");
Bill Wendlingeb907212009-05-15 01:12:28 +0000658 }
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000659 } else {
660 // DWARF Exception handling
661 assert(TAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
Bill Wendlingeb907212009-05-15 01:12:28 +0000662
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000663 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
664 Asm->EOL("Call site format (DW_EH_PE_udata4)");
665 Asm->EmitULEB128Bytes(SizeSites);
666 Asm->EOL("Call-site table length");
Bill Wendlingeb907212009-05-15 01:12:28 +0000667
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000668 // Emit the landing pad site information.
669 for (SmallVectorImpl<CallSiteEntry>::const_iterator
670 I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
671 const CallSiteEntry &S = *I;
672 const char *BeginTag;
673 unsigned BeginNumber;
Bill Wendlingeb907212009-05-15 01:12:28 +0000674
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000675 if (!S.BeginLabel) {
676 BeginTag = "eh_func_begin";
677 BeginNumber = SubprogramCount;
678 } else {
679 BeginTag = "label";
680 BeginNumber = S.BeginLabel;
681 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000682
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000683 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
Bill Wendlingeb907212009-05-15 01:12:28 +0000684 true, true);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000685 Asm->EOL("Region start");
Bill Wendlingeb907212009-05-15 01:12:28 +0000686
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000687 if (!S.EndLabel)
688 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
689 true);
690 else
691 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
Bill Wendlingeb907212009-05-15 01:12:28 +0000692
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000693 Asm->EOL("Region length");
694
695 if (!S.PadLabel)
696 Asm->EmitInt32(0);
697 else
698 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
699 true, true);
700
701 Asm->EOL("Landing pad");
702
703 Asm->EmitULEB128Bytes(S.Action);
704 Asm->EOL("Action");
705 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000706 }
707
708 // Emit the actions.
Bill Wendling5cff4872009-07-28 23:44:43 +0000709 for (SmallVectorImpl<ActionEntry>::const_iterator
710 I = Actions.begin(), E = Actions.end(); I != E; ++I) {
711 const ActionEntry &Action = *I;
Bill Wendlingeb907212009-05-15 01:12:28 +0000712 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
713 Asm->EOL("TypeInfo index");
714 Asm->EmitSLEB128Bytes(Action.NextAction);
715 Asm->EOL("Next action");
716 }
717
718 // Emit the type ids.
Bill Wendling5cff4872009-07-28 23:44:43 +0000719 for (std::vector<GlobalVariable *>::const_reverse_iterator
720 I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
721 GlobalVariable *GV = *I;
Bill Wendlingeb907212009-05-15 01:12:28 +0000722 PrintRelDirective();
723
724 if (GV) {
725 std::string GLN;
726 O << Asm->getGlobalLinkName(GV, GLN);
727 } else {
728 O << "0";
729 }
730
731 Asm->EOL("TypeInfo");
732 }
733
734 // Emit the filter typeids.
Bill Wendling5cff4872009-07-28 23:44:43 +0000735 for (std::vector<unsigned>::const_iterator
736 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
737 unsigned TypeID = *I;
Bill Wendlingeb907212009-05-15 01:12:28 +0000738 Asm->EmitULEB128Bytes(TypeID);
739 Asm->EOL("Filter TypeInfo index");
740 }
741
742 Asm->EmitAlignment(2, 0, 0, false);
743}
744
Bill Wendlingeb907212009-05-15 01:12:28 +0000745/// EndModule - Emit all exception information that should come after the
746/// content.
747void DwarfException::EndModule() {
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000748 if (TAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
749 return;
Bill Wendlingeb907212009-05-15 01:12:28 +0000750 if (TimePassesIsEnabled)
751 ExceptionTimer->startTimer();
752
753 if (shouldEmitMovesModule || shouldEmitTableModule) {
754 const std::vector<Function *> Personalities = MMI->getPersonalities();
755 for (unsigned i = 0; i < Personalities.size(); ++i)
756 EmitCommonEHFrame(Personalities[i], i);
757
758 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
759 E = EHFrames.end(); I != E; ++I)
760 EmitEHFrame(*I);
761 }
762
763 if (TimePassesIsEnabled)
764 ExceptionTimer->stopTimer();
765}
766
767/// BeginFunction - Gather pre-function exception information. Assumes being
768/// emitted immediately after the function entry point.
769void DwarfException::BeginFunction(MachineFunction *MF) {
770 if (TimePassesIsEnabled)
771 ExceptionTimer->startTimer();
772
773 this->MF = MF;
774 shouldEmitTable = shouldEmitMoves = false;
775
776 if (MMI && TAI->doesSupportExceptionHandling()) {
777 // Map all labels and get rid of any dead landing pads.
778 MMI->TidyLandingPads();
779
780 // If any landing pads survive, we need an EH table.
781 if (MMI->getLandingPads().size())
782 shouldEmitTable = true;
783
784 // See if we need frame move info.
785 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
786 shouldEmitMoves = true;
787
788 if (shouldEmitMoves || shouldEmitTable)
789 // Assumes in correct section after the entry point.
790 EmitLabel("eh_func_begin", ++SubprogramCount);
791 }
792
793 shouldEmitTableModule |= shouldEmitTable;
794 shouldEmitMovesModule |= shouldEmitMoves;
795
796 if (TimePassesIsEnabled)
797 ExceptionTimer->stopTimer();
798}
799
800/// EndFunction - Gather and emit post-function exception information.
801///
802void DwarfException::EndFunction() {
803 if (TimePassesIsEnabled)
804 ExceptionTimer->startTimer();
805
806 if (shouldEmitMoves || shouldEmitTable) {
807 EmitLabel("eh_func_end", SubprogramCount);
808 EmitExceptionTable();
809
810 // Save EH frame information
Bill Wendlingeb907212009-05-15 01:12:28 +0000811 EHFrames.push_back(
Chris Lattnere2cf37b2009-07-17 20:46:40 +0000812 FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
Bill Wendlingeb907212009-05-15 01:12:28 +0000813 SubprogramCount,
814 MMI->getPersonalityIndex(),
815 MF->getFrameInfo()->hasCalls(),
816 !MMI->getLandingPads().empty(),
817 MMI->getFrameMoves(),
818 MF->getFunction()));
819 }
820
821 if (TimePassesIsEnabled)
822 ExceptionTimer->stopTimer();
823}