blob: 829879bc2b32085813d2b42d505281d8e64158e9 [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"
David Greenefc4da0c2009-08-19 21:55:33 +000018#include "llvm/CodeGen/MachineFunction.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000019#include "llvm/CodeGen/MachineLocation.h"
Chris Lattner6c2f9e12009-08-19 05:49:37 +000020#include "llvm/MC/MCStreamer.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000021#include "llvm/Target/TargetAsmInfo.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000022#include "llvm/Target/TargetData.h"
23#include "llvm/Target/TargetFrameInfo.h"
Chris Lattnerd5bbb072009-08-02 01:34:32 +000024#include "llvm/Target/TargetLoweringObjectFile.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000025#include "llvm/Target/TargetOptions.h"
Chris Lattnerd5bbb072009-08-02 01:34:32 +000026#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner6c2f9e12009-08-19 05:49:37 +000027#include "llvm/Support/Dwarf.h"
28#include "llvm/Support/Timer.h"
29#include "llvm/Support/raw_ostream.h"
Bill Wendlingeb907212009-05-15 01:12:28 +000030#include "llvm/ADT/StringExtras.h"
31using namespace llvm;
32
33static TimerGroup &getDwarfTimerGroup() {
34 static TimerGroup DwarfTimerGroup("Dwarf Exception");
35 return DwarfTimerGroup;
36}
37
Bill Wendlingbc0d23a2009-05-15 01:18:50 +000038DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A,
39 const TargetAsmInfo *T)
40 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
41 shouldEmitTableModule(false), shouldEmitMovesModule(false),
42 ExceptionTimer(0) {
43 if (TimePassesIsEnabled)
44 ExceptionTimer = new Timer("Dwarf Exception Writer",
45 getDwarfTimerGroup());
46}
47
48DwarfException::~DwarfException() {
49 delete ExceptionTimer;
50}
51
Bill Wendlingeb907212009-05-15 01:12:28 +000052void DwarfException::EmitCommonEHFrame(const Function *Personality,
53 unsigned Index) {
54 // Size and sign of stack growth.
55 int stackGrowth =
56 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
57 TargetFrameInfo::StackGrowsUp ?
58 TD->getPointerSize() : -TD->getPointerSize();
59
60 // Begin eh frame section.
Chris Lattner6c2f9e12009-08-19 05:49:37 +000061 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
Bill Wendlingeb907212009-05-15 01:12:28 +000062
Chris Lattnere2cf37b2009-07-17 20:46:40 +000063 if (TAI->is_EHSymbolPrivate())
64 O << TAI->getPrivateGlobalPrefix();
Bill Wendlingeb907212009-05-15 01:12:28 +000065
66 O << "EH_frame" << Index << ":\n";
67 EmitLabel("section_eh_frame", Index);
68
69 // Define base labels.
70 EmitLabel("eh_frame_common", Index);
71
72 // Define the eh frame length.
73 EmitDifference("eh_frame_common_end", Index,
74 "eh_frame_common_begin", Index, true);
75 Asm->EOL("Length of Common Information Entry");
76
77 // EH frame header.
78 EmitLabel("eh_frame_common_begin", Index);
79 Asm->EmitInt32((int)0);
80 Asm->EOL("CIE Identifier Tag");
81 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
82 Asm->EOL("CIE Version");
83
84 // The personality presence indicates that language specific information will
85 // show up in the eh frame.
86 Asm->EmitString(Personality ? "zPLR" : "zR");
87 Asm->EOL("CIE Augmentation");
88
89 // Round out reader.
90 Asm->EmitULEB128Bytes(1);
91 Asm->EOL("CIE Code Alignment Factor");
92 Asm->EmitSLEB128Bytes(stackGrowth);
93 Asm->EOL("CIE Data Alignment Factor");
94 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
95 Asm->EOL("CIE Return Address Column");
96
97 // If there is a personality, we need to indicate the functions location.
98 if (Personality) {
99 Asm->EmitULEB128Bytes(7);
100 Asm->EOL("Augmentation Size");
101
102 if (TAI->getNeedsIndirectEncoding()) {
103 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 |
104 dwarf::DW_EH_PE_indirect);
105 Asm->EOL("Personality (pcrel sdata4 indirect)");
106 } else {
107 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
108 Asm->EOL("Personality (pcrel sdata4)");
109 }
110
111 PrintRelDirective(true);
112 O << TAI->getPersonalityPrefix();
113 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
114 O << TAI->getPersonalitySuffix();
115 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
116 O << "-" << TAI->getPCSymbol();
117 Asm->EOL("Personality");
118
119 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
120 Asm->EOL("LSDA Encoding (pcrel sdata4)");
121
122 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
123 Asm->EOL("FDE Encoding (pcrel sdata4)");
124 } else {
125 Asm->EmitULEB128Bytes(1);
126 Asm->EOL("Augmentation Size");
127
128 Asm->EmitInt8(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
129 Asm->EOL("FDE Encoding (pcrel sdata4)");
130 }
131
132 // Indicate locations of general callee saved registers in frame.
133 std::vector<MachineMove> Moves;
134 RI->getInitialFrameState(Moves);
135 EmitFrameMoves(NULL, 0, Moves, true);
136
137 // On Darwin the linker honors the alignment of eh_frame, which means it must
138 // be 8-byte on 64-bit targets to match what gcc does. Otherwise you get
139 // holes which confuse readers of eh_frame.
140 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
141 0, 0, false);
142 EmitLabel("eh_frame_common_end", Index);
143
144 Asm->EOL();
145}
146
147/// EmitEHFrame - Emit function exception frame information.
148///
149void DwarfException::EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
150 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
151 "Should not emit 'available externally' functions at all");
152
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000153 const Function *TheFunc = EHFrameInfo.function;
154
Chris Lattner6c2f9e12009-08-19 05:49:37 +0000155 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getEHFrameSection());
Chris Lattner6a66e582009-08-18 06:13:03 +0000156
Bill Wendlingeb907212009-05-15 01:12:28 +0000157 // Externally visible entry into the functions eh frame info. If the
158 // corresponding function is static, this should not be externally visible.
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000159 if (!TheFunc->hasLocalLinkage())
Bill Wendlingeb907212009-05-15 01:12:28 +0000160 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
161 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
Bill Wendlingeb907212009-05-15 01:12:28 +0000162
163 // If corresponding function is weak definition, this should be too.
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000164 if (TheFunc->isWeakForLinker() && TAI->getWeakDefDirective())
Bill Wendlingeb907212009-05-15 01:12:28 +0000165 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
166
167 // If there are no calls then you can't unwind. This may mean we can omit the
168 // EH Frame, but some environments do not handle weak absolute symbols. If
169 // UnwindTablesMandatory is set we cannot do this optimization; the unwind
170 // info is to be available for non-EH uses.
Chris Lattner3e0f60b2009-07-17 21:00:50 +0000171 if (!EHFrameInfo.hasCalls && !UnwindTablesMandatory &&
172 (!TheFunc->isWeakForLinker() ||
Bill Wendlingeb907212009-05-15 01:12:28 +0000173 !TAI->getWeakDefDirective() ||
174 TAI->getSupportsWeakOmittedEHFrame())) {
175 O << EHFrameInfo.FnName << " = 0\n";
176 // This name has no connection to the function, so it might get
177 // dead-stripped when the function is not, erroneously. Prohibit
178 // dead-stripping unconditionally.
179 if (const char *UsedDirective = TAI->getUsedDirective())
180 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
181 } else {
182 O << EHFrameInfo.FnName << ":\n";
183
184 // EH frame header.
185 EmitDifference("eh_frame_end", EHFrameInfo.Number,
186 "eh_frame_begin", EHFrameInfo.Number, true);
187 Asm->EOL("Length of Frame Information Entry");
188
189 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
190
Chris Lattnera4ff5e42009-07-17 20:53:51 +0000191 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
192 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
193 true, true, false);
Bill Wendlingeb907212009-05-15 01:12:28 +0000194
195 Asm->EOL("FDE CIE offset");
196
197 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
198 Asm->EOL("FDE initial location");
199 EmitDifference("eh_func_end", EHFrameInfo.Number,
200 "eh_func_begin", EHFrameInfo.Number, true);
201 Asm->EOL("FDE address range");
202
203 // If there is a personality and landing pads then point to the language
204 // specific data area in the exception table.
205 if (EHFrameInfo.PersonalityIndex) {
206 Asm->EmitULEB128Bytes(4);
207 Asm->EOL("Augmentation size");
208
209 if (EHFrameInfo.hasLandingPads)
210 EmitReference("exception", EHFrameInfo.Number, true, true);
211 else
212 Asm->EmitInt32((int)0);
213 Asm->EOL("Language Specific Data Area");
214 } else {
215 Asm->EmitULEB128Bytes(0);
216 Asm->EOL("Augmentation size");
217 }
218
219 // Indicate locations of function specific callee saved registers in frame.
220 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
221 true);
222
223 // On Darwin the linker honors the alignment of eh_frame, which means it
224 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise you
225 // get holes which confuse readers of eh_frame.
226 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
227 0, 0, false);
228 EmitLabel("eh_frame_end", EHFrameInfo.Number);
229
230 // If the function is marked used, this table should be also. We cannot
231 // make the mark unconditional in this case, since retaining the table also
232 // retains the function in this case, and there is code around that depends
233 // on unused functions (calling undefined externals) being dead-stripped to
234 // link correctly. Yes, there really is.
Chris Lattner401e10c2009-07-20 06:14:25 +0000235 if (MMI->isUsedFunction(EHFrameInfo.function))
Bill Wendlingeb907212009-05-15 01:12:28 +0000236 if (const char *UsedDirective = TAI->getUsedDirective())
237 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
238 }
239}
240
Bill Wendlingeb907212009-05-15 01:12:28 +0000241/// SharedTypeIds - How many leading type ids two landing pads have in common.
242unsigned DwarfException::SharedTypeIds(const LandingPadInfo *L,
243 const LandingPadInfo *R) {
244 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
245 unsigned LSize = LIds.size(), RSize = RIds.size();
246 unsigned MinSize = LSize < RSize ? LSize : RSize;
247 unsigned Count = 0;
248
249 for (; Count != MinSize; ++Count)
250 if (LIds[Count] != RIds[Count])
251 return Count;
252
253 return Count;
254}
255
256/// PadLT - Order landing pads lexicographically by type id.
257bool DwarfException::PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
258 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
259 unsigned LSize = LIds.size(), RSize = RIds.size();
260 unsigned MinSize = LSize < RSize ? LSize : RSize;
261
262 for (unsigned i = 0; i != MinSize; ++i)
263 if (LIds[i] != RIds[i])
264 return LIds[i] < RIds[i];
265
266 return LSize < RSize;
267}
268
Bill Wendlingd4609622009-07-28 23:23:00 +0000269/// ComputeActionsTable - Compute the actions table and gather the first action
270/// index for each landing pad site.
Bill Wendlingade025c2009-07-29 00:31:35 +0000271unsigned DwarfException::
272ComputeActionsTable(const SmallVectorImpl<const LandingPadInfo*> &LandingPads,
273 SmallVectorImpl<ActionEntry> &Actions,
274 SmallVectorImpl<unsigned> &FirstActions) {
Bill Wendling5e953dd2009-07-28 23:22:13 +0000275 // Negative type IDs index into FilterIds. Positive type IDs index into
276 // TypeInfos. The value written for a positive type ID is just the type ID
277 // itself. For a negative type ID, however, the value written is the
Bill Wendlingeb907212009-05-15 01:12:28 +0000278 // (negative) byte offset of the corresponding FilterIds entry. The byte
Bill Wendling5e953dd2009-07-28 23:22:13 +0000279 // offset is usually equal to the type ID (because the FilterIds entries are
280 // written using a variable width encoding, which outputs one byte per entry
281 // as long as the value written is not too large) but can differ. This kind
282 // of complication does not occur for positive type IDs because type infos are
Bill Wendlingeb907212009-05-15 01:12:28 +0000283 // output using a fixed width encoding. FilterOffsets[i] holds the byte
284 // offset corresponding to FilterIds[i].
Bill Wendling409914b2009-07-29 21:19:44 +0000285
286 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
Bill Wendlingeb907212009-05-15 01:12:28 +0000287 SmallVector<int, 16> FilterOffsets;
288 FilterOffsets.reserve(FilterIds.size());
289 int Offset = -1;
Bill Wendling409914b2009-07-29 21:19:44 +0000290
291 for (std::vector<unsigned>::const_iterator
292 I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000293 FilterOffsets.push_back(Offset);
294 Offset -= TargetAsmInfo::getULEB128Size(*I);
295 }
296
Bill Wendlingeb907212009-05-15 01:12:28 +0000297 FirstActions.reserve(LandingPads.size());
298
299 int FirstAction = 0;
300 unsigned SizeActions = 0;
Bill Wendling5e953dd2009-07-28 23:22:13 +0000301 const LandingPadInfo *PrevLPI = 0;
Bill Wendling409914b2009-07-29 21:19:44 +0000302
Bill Wendling5cff4872009-07-28 23:44:43 +0000303 for (SmallVectorImpl<const LandingPadInfo *>::const_iterator
Bill Wendling5e953dd2009-07-28 23:22:13 +0000304 I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) {
305 const LandingPadInfo *LPI = *I;
306 const std::vector<int> &TypeIds = LPI->TypeIds;
307 const unsigned NumShared = PrevLPI ? SharedTypeIds(LPI, PrevLPI) : 0;
Bill Wendlingeb907212009-05-15 01:12:28 +0000308 unsigned SizeSiteActions = 0;
309
310 if (NumShared < TypeIds.size()) {
311 unsigned SizeAction = 0;
312 ActionEntry *PrevAction = 0;
313
314 if (NumShared) {
Bill Wendling5e953dd2009-07-28 23:22:13 +0000315 const unsigned SizePrevIds = PrevLPI->TypeIds.size();
Bill Wendlingeb907212009-05-15 01:12:28 +0000316 assert(Actions.size());
317 PrevAction = &Actions.back();
318 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
319 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
320
321 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
322 SizeAction -=
323 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
324 SizeAction += -PrevAction->NextAction;
325 PrevAction = PrevAction->Previous;
326 }
327 }
328
329 // Compute the actions.
Bill Wendling5e953dd2009-07-28 23:22:13 +0000330 for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
331 int TypeID = TypeIds[J];
332 assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
Bill Wendlingeb907212009-05-15 01:12:28 +0000333 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
334 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
335
336 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
337 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
338 SizeSiteActions += SizeAction;
339
340 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
341 Actions.push_back(Action);
Bill Wendlingeb907212009-05-15 01:12:28 +0000342 PrevAction = &Actions.back();
343 }
344
345 // Record the first action of the landing pad site.
346 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
347 } // else identical - re-use previous FirstAction
348
349 FirstActions.push_back(FirstAction);
350
351 // Compute this sites contribution to size.
352 SizeActions += SizeSiteActions;
Bill Wendling5e953dd2009-07-28 23:22:13 +0000353
354 PrevLPI = LPI;
Bill Wendlingeb907212009-05-15 01:12:28 +0000355 }
356
Bill Wendling5e953dd2009-07-28 23:22:13 +0000357 return SizeActions;
358}
359
Bill Wendlingade025c2009-07-29 00:31:35 +0000360/// ComputeCallSiteTable - Compute the call-site table. The entry for an invoke
361/// has a try-range containing the call, a non-zero landing pad and an
362/// appropriate action. The entry for an ordinary call has a try-range
363/// containing the call and zero for the landing pad and the action. Calls
364/// marked 'nounwind' have no entry and must not be contained in the try-range
365/// of any entry - they form gaps in the table. Entries must be ordered by
366/// try-range address.
367void DwarfException::
368ComputeCallSiteTable(SmallVectorImpl<CallSiteEntry> &CallSites,
369 const RangeMapType &PadMap,
370 const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
371 const SmallVectorImpl<unsigned> &FirstActions) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000372 // The end label of the previous invoke or nounwind try-range.
373 unsigned LastLabel = 0;
374
375 // Whether there is a potentially throwing instruction (currently this means
376 // an ordinary call) between the end of the previous try-range and now.
377 bool SawPotentiallyThrowing = false;
378
Bill Wendling5cff4872009-07-28 23:44:43 +0000379 // Whether the last CallSite entry was for an invoke.
Bill Wendlingeb907212009-05-15 01:12:28 +0000380 bool PreviousIsInvoke = false;
381
382 // Visit all instructions in order of address.
383 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
384 I != E; ++I) {
385 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
386 MI != E; ++MI) {
387 if (!MI->isLabel()) {
388 SawPotentiallyThrowing |= MI->getDesc().isCall();
389 continue;
390 }
391
392 unsigned BeginLabel = MI->getOperand(0).getImm();
393 assert(BeginLabel && "Invalid label!");
394
395 // End of the previous try-range?
396 if (BeginLabel == LastLabel)
397 SawPotentiallyThrowing = false;
398
399 // Beginning of a new try-range?
400 RangeMapType::iterator L = PadMap.find(BeginLabel);
401 if (L == PadMap.end())
402 // Nope, it was just some random label.
403 continue;
404
405 PadRange P = L->second;
406 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
Bill Wendlingeb907212009-05-15 01:12:28 +0000407 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
408 "Inconsistent landing pad map!");
409
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000410 // For Dwarf exception handling (SjLj handling doesn't use this)
Bill Wendlingeb907212009-05-15 01:12:28 +0000411 // If some instruction between the previous try-range and this one may
412 // throw, create a call-site entry with no landing pad for the region
413 // between the try-ranges.
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000414 if (SawPotentiallyThrowing &&
415 TAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000416 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
417 CallSites.push_back(Site);
418 PreviousIsInvoke = false;
419 }
420
421 LastLabel = LandingPad->EndLabels[P.RangeIndex];
422 assert(BeginLabel && LastLabel && "Invalid landing pad!");
423
424 if (LandingPad->LandingPadLabel) {
425 // This try-range is for an invoke.
426 CallSiteEntry Site = {BeginLabel, LastLabel,
427 LandingPad->LandingPadLabel,
428 FirstActions[P.PadIndex]};
429
430 // Try to merge with the previous call-site.
431 if (PreviousIsInvoke) {
432 CallSiteEntry &Prev = CallSites.back();
433 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
434 // Extend the range of the previous entry.
435 Prev.EndLabel = Site.EndLabel;
436 continue;
437 }
438 }
439
440 // Otherwise, create a new call-site.
441 CallSites.push_back(Site);
442 PreviousIsInvoke = true;
443 } else {
444 // Create a gap.
445 PreviousIsInvoke = false;
446 }
447 }
448 }
449
450 // If some instruction between the previous try-range and the end of the
451 // function may throw, create a call-site entry with no landing pad for the
452 // region following the try-range.
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000453 if (SawPotentiallyThrowing &&
454 TAI->getExceptionHandlingType() == ExceptionHandling::Dwarf) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000455 CallSiteEntry Site = {LastLabel, 0, 0, 0};
456 CallSites.push_back(Site);
457 }
Bill Wendlingade025c2009-07-29 00:31:35 +0000458}
459
Bill Wendling0dafca92009-07-29 00:50:05 +0000460/// EmitExceptionTable - Emit landing pads and actions.
461///
462/// The general organization of the table is complex, but the basic concepts are
463/// easy. First there is a header which describes the location and organization
464/// of the three components that follow.
465///
466/// 1. The landing pad site information describes the range of code covered by
467/// the try. In our case it's an accumulation of the ranges covered by the
468/// invokes in the try. There is also a reference to the landing pad that
469/// handles the exception once processed. Finally an index into the actions
470/// table.
471/// 2. The action table, in our case, is composed of pairs of type ids and next
472/// action offset. Starting with the action index from the landing pad
473/// site, each type Id is checked for a match to the current exception. If
474/// it matches then the exception and type id are passed on to the landing
475/// pad. Otherwise the next action is looked up. This chain is terminated
476/// with a next action of zero. If no type id is found the the frame is
477/// unwound and handling continues.
478/// 3. Type id table contains references to all the C++ typeinfo for all
479/// catches in the function. This tables is reversed indexed base 1.
Bill Wendlingade025c2009-07-29 00:31:35 +0000480void DwarfException::EmitExceptionTable() {
481 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
482 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
483 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
484 if (PadInfos.empty()) return;
485
486 // Sort the landing pads in order of their type ids. This is used to fold
487 // duplicate actions.
488 SmallVector<const LandingPadInfo *, 64> LandingPads;
489 LandingPads.reserve(PadInfos.size());
490
491 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
492 LandingPads.push_back(&PadInfos[i]);
493
494 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
495
496 // Compute the actions table and gather the first action index for each
497 // landing pad site.
498 SmallVector<ActionEntry, 32> Actions;
499 SmallVector<unsigned, 64> FirstActions;
500 unsigned SizeActions = ComputeActionsTable(LandingPads, Actions, FirstActions);
501
502 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
503 // by try-range labels when lowered). Ordinary calls do not, so appropriate
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000504 // try-ranges for them need be deduced when using Dwarf exception handling.
Bill Wendlingade025c2009-07-29 00:31:35 +0000505 RangeMapType PadMap;
506 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
507 const LandingPadInfo *LandingPad = LandingPads[i];
508 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
509 unsigned BeginLabel = LandingPad->BeginLabels[j];
510 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
511 PadRange P = { i, j };
512 PadMap[BeginLabel] = P;
513 }
514 }
515
516 // Compute the call-site table.
517 SmallVector<CallSiteEntry, 64> CallSites;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000518 ComputeCallSiteTable(CallSites, PadMap, LandingPads, FirstActions);
Bill Wendlingeb907212009-05-15 01:12:28 +0000519
520 // Final tallies.
521
522 // Call sites.
523 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
524 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
525 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000526 unsigned SizeSites;
Jim Grosbachbff39232009-08-12 17:38:44 +0000527
528 bool HaveTTData = (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
529 ? (!TypeInfos.empty() || !FilterIds.empty()) : true;
530
531
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000532 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000533 SizeSites = 0;
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000534 } else
535 SizeSites = CallSites.size() *
536 (SiteStartSize + SiteLengthSize + LandingPadSize);
537 for (unsigned i = 0, e = CallSites.size(); i < e; ++i) {
Bill Wendlingeb907212009-05-15 01:12:28 +0000538 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000539 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj)
540 SizeSites += TargetAsmInfo::getULEB128Size(i);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000541 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000542 // Type infos.
543 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
544 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
545
546 unsigned TypeOffset = sizeof(int8_t) + // Call site format
547 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
548 SizeSites + SizeActions + SizeTypes;
549
550 unsigned TotalSize = sizeof(int8_t) + // LPStart format
551 sizeof(int8_t) + // TType format
Jim Grosbachbff39232009-08-12 17:38:44 +0000552 (HaveTTData ?
553 TargetAsmInfo::getULEB128Size(TypeOffset) : 0) + // TType base offset
Bill Wendlingeb907212009-05-15 01:12:28 +0000554 TypeOffset;
555
556 unsigned SizeAlign = (4 - TotalSize) & 3;
557
558 // Begin the exception table.
Chris Lattnerd5bbb072009-08-02 01:34:32 +0000559 const MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection();
Chris Lattner6c2f9e12009-08-19 05:49:37 +0000560 Asm->OutStreamer.SwitchSection(LSDASection);
Bill Wendlingeb907212009-05-15 01:12:28 +0000561 Asm->EmitAlignment(2, 0, 0, false);
562 O << "GCC_except_table" << SubprogramCount << ":\n";
563
564 for (unsigned i = 0; i != SizeAlign; ++i) {
565 Asm->EmitInt8(0);
566 Asm->EOL("Padding");
Bill Wendlingc5800a82009-07-28 21:54:03 +0000567 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000568
569 EmitLabel("exception", SubprogramCount);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000570 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
571 std::string SjLjName = "_lsda_";
572 SjLjName += MF->getFunction()->getName().str();
573 EmitLabel(SjLjName.c_str(), 0);
574 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000575
576 // Emit the header.
577 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
578 Asm->EOL("LPStart format (DW_EH_PE_omit)");
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000579
Bill Wendlingade025c2009-07-29 00:31:35 +0000580#if 0
Chris Lattner81c9a062009-07-31 22:03:47 +0000581 if (TypeInfos.empty() && FilterIds.empty()) {
Chris Lattnerad88bc42009-08-02 03:59:56 +0000582 // If there are no typeinfos or filters, there is nothing to emit, optimize
583 // by specifying the "omit" encoding.
Chris Lattner81c9a062009-07-31 22:03:47 +0000584 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
585 Asm->EOL("TType format (DW_EH_PE_omit)");
586 } else {
Chris Lattnerad88bc42009-08-02 03:59:56 +0000587 // Okay, we have actual filters or typeinfos to emit. As such, we need to
588 // pick a type encoding for them. We're about to emit a list of pointers to
589 // typeinfo objects at the end of the LSDA. However, unless we're in static
590 // mode, this reference will require a relocation by the dynamic linker.
Chris Lattner46b754c2009-07-31 22:18:14 +0000591 //
Chris Lattnerad88bc42009-08-02 03:59:56 +0000592 // Because of this, we have a couple of options:
593 // 1) If we are in -static mode, we can always use an absolute reference
594 // from the LSDA, because the static linker will resolve it.
595 // 2) Otherwise, if the LSDA section is writable, we can output the direct
596 // reference to the typeinfo and allow the dynamic linker to relocate
597 // it. Since it is in a writable section, the dynamic linker won't
598 // have a problem.
599 // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
600 // we need to use some form of indirection. For example, on Darwin,
601 // we can output a statically-relocatable reference to a dyld stub. The
602 // offset to the stub is constant, but the contents are in a section
603 // that is updated by the dynamic linker. This is easy enough, but we
604 // need to tell the personality function of the unwinder to indirect
605 // through the dyld stub.
606 //
607 // FIXME: When this is actually implemented, we'll have to emit the stubs
608 // somewhere. This predicate should be moved to a shared location that is
609 // in target-independent code.
610 //
611 if (LSDASection->isWritable() ||
612 Asm->TM.getRelocationModel() == Reloc::Static) {
613 Asm->EmitInt8(DW_EH_PE_absptr);
614 Asm->EOL("TType format (DW_EH_PE_absptr)");
615 } else {
616 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_indirect | DW_EH_PE_sdata4);
617 Asm->EOL("TType format (DW_EH_PE_pcrel | DW_EH_PE_indirect"
618 " | DW_EH_PE_sdata4)");
619 }
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000620 Asm->EmitULEB128Bytes(TypeOffset);
621 Asm->EOL("TType base offset");
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000622 }
Bill Wendlingade025c2009-07-29 00:31:35 +0000623#else
Jim Grosbachbff39232009-08-12 17:38:44 +0000624 // For SjLj exceptions, if there is no TypeInfo, then we just explicitly
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000625 // say that we're omitting that bit.
626 // FIXME: does this apply to Dwarf also? The above #if 0 implies yes?
Jim Grosbachbff39232009-08-12 17:38:44 +0000627 if (!HaveTTData) {
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000628 Asm->EmitInt8(dwarf::DW_EH_PE_omit);
629 Asm->EOL("TType format (DW_EH_PE_omit)");
630 } else {
631 Asm->EmitInt8(dwarf::DW_EH_PE_absptr);
632 Asm->EOL("TType format (DW_EH_PE_absptr)");
633 Asm->EmitULEB128Bytes(TypeOffset);
634 Asm->EOL("TType base offset");
635 }
Bill Wendlingade025c2009-07-29 00:31:35 +0000636#endif
Bill Wendlingb0d9c3e2009-07-28 22:23:45 +0000637
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000638 // SjLj Exception handilng
639 if (TAI->getExceptionHandlingType() == ExceptionHandling::SjLj) {
640 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
641 Asm->EOL("Call site format (DW_EH_PE_udata4)");
642 Asm->EmitULEB128Bytes(SizeSites);
643 Asm->EOL("Call-site table length");
Bill Wendlingeb907212009-05-15 01:12:28 +0000644
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000645 // Emit the landing pad site information.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000646 unsigned idx = 0;
647 for (SmallVectorImpl<CallSiteEntry>::const_iterator
648 I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
649 const CallSiteEntry &S = *I;
650 Asm->EmitULEB128Bytes(idx);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000651 Asm->EOL("Landing pad");
652 Asm->EmitULEB128Bytes(S.Action);
653 Asm->EOL("Action");
Bill Wendlingeb907212009-05-15 01:12:28 +0000654 }
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000655 } else {
656 // DWARF Exception handling
657 assert(TAI->getExceptionHandlingType() == ExceptionHandling::Dwarf);
Bill Wendlingeb907212009-05-15 01:12:28 +0000658
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000659 Asm->EmitInt8(dwarf::DW_EH_PE_udata4);
660 Asm->EOL("Call site format (DW_EH_PE_udata4)");
661 Asm->EmitULEB128Bytes(SizeSites);
662 Asm->EOL("Call-site table length");
Bill Wendlingeb907212009-05-15 01:12:28 +0000663
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000664 // Emit the landing pad site information.
665 for (SmallVectorImpl<CallSiteEntry>::const_iterator
666 I = CallSites.begin(), E = CallSites.end(); I != E; ++I) {
667 const CallSiteEntry &S = *I;
668 const char *BeginTag;
669 unsigned BeginNumber;
Bill Wendlingeb907212009-05-15 01:12:28 +0000670
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000671 if (!S.BeginLabel) {
672 BeginTag = "eh_func_begin";
673 BeginNumber = SubprogramCount;
674 } else {
675 BeginTag = "label";
676 BeginNumber = S.BeginLabel;
677 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000678
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000679 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
Bill Wendlingeb907212009-05-15 01:12:28 +0000680 true, true);
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000681 Asm->EOL("Region start");
Bill Wendlingeb907212009-05-15 01:12:28 +0000682
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000683 if (!S.EndLabel)
684 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
685 true);
686 else
687 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
Bill Wendlingeb907212009-05-15 01:12:28 +0000688
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000689 Asm->EOL("Region length");
690
691 if (!S.PadLabel)
692 Asm->EmitInt32(0);
693 else
694 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
695 true, true);
696
697 Asm->EOL("Landing pad");
698
699 Asm->EmitULEB128Bytes(S.Action);
700 Asm->EOL("Action");
701 }
Bill Wendlingeb907212009-05-15 01:12:28 +0000702 }
703
704 // Emit the actions.
Bill Wendling5cff4872009-07-28 23:44:43 +0000705 for (SmallVectorImpl<ActionEntry>::const_iterator
706 I = Actions.begin(), E = Actions.end(); I != E; ++I) {
707 const ActionEntry &Action = *I;
Bill Wendlingeb907212009-05-15 01:12:28 +0000708 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
709 Asm->EOL("TypeInfo index");
710 Asm->EmitSLEB128Bytes(Action.NextAction);
711 Asm->EOL("Next action");
712 }
713
714 // Emit the type ids.
Bill Wendling5cff4872009-07-28 23:44:43 +0000715 for (std::vector<GlobalVariable *>::const_reverse_iterator
716 I = TypeInfos.rbegin(), E = TypeInfos.rend(); I != E; ++I) {
717 GlobalVariable *GV = *I;
Bill Wendlingeb907212009-05-15 01:12:28 +0000718 PrintRelDirective();
719
720 if (GV) {
721 std::string GLN;
722 O << Asm->getGlobalLinkName(GV, GLN);
723 } else {
724 O << "0";
725 }
726
727 Asm->EOL("TypeInfo");
728 }
729
730 // Emit the filter typeids.
Bill Wendling5cff4872009-07-28 23:44:43 +0000731 for (std::vector<unsigned>::const_iterator
732 I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
733 unsigned TypeID = *I;
Bill Wendlingeb907212009-05-15 01:12:28 +0000734 Asm->EmitULEB128Bytes(TypeID);
735 Asm->EOL("Filter TypeInfo index");
736 }
737
738 Asm->EmitAlignment(2, 0, 0, false);
739}
740
Bill Wendlingeb907212009-05-15 01:12:28 +0000741/// EndModule - Emit all exception information that should come after the
742/// content.
743void DwarfException::EndModule() {
Jim Grosbach1b747ad2009-08-11 00:09:57 +0000744 if (TAI->getExceptionHandlingType() != ExceptionHandling::Dwarf)
745 return;
Bill Wendlingeb907212009-05-15 01:12:28 +0000746 if (TimePassesIsEnabled)
747 ExceptionTimer->startTimer();
748
749 if (shouldEmitMovesModule || shouldEmitTableModule) {
750 const std::vector<Function *> Personalities = MMI->getPersonalities();
751 for (unsigned i = 0; i < Personalities.size(); ++i)
752 EmitCommonEHFrame(Personalities[i], i);
753
754 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
755 E = EHFrames.end(); I != E; ++I)
756 EmitEHFrame(*I);
757 }
758
759 if (TimePassesIsEnabled)
760 ExceptionTimer->stopTimer();
761}
762
763/// BeginFunction - Gather pre-function exception information. Assumes being
764/// emitted immediately after the function entry point.
765void DwarfException::BeginFunction(MachineFunction *MF) {
766 if (TimePassesIsEnabled)
767 ExceptionTimer->startTimer();
768
769 this->MF = MF;
770 shouldEmitTable = shouldEmitMoves = false;
771
772 if (MMI && TAI->doesSupportExceptionHandling()) {
773 // Map all labels and get rid of any dead landing pads.
774 MMI->TidyLandingPads();
775
776 // If any landing pads survive, we need an EH table.
777 if (MMI->getLandingPads().size())
778 shouldEmitTable = true;
779
780 // See if we need frame move info.
781 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
782 shouldEmitMoves = true;
783
784 if (shouldEmitMoves || shouldEmitTable)
785 // Assumes in correct section after the entry point.
786 EmitLabel("eh_func_begin", ++SubprogramCount);
787 }
788
789 shouldEmitTableModule |= shouldEmitTable;
790 shouldEmitMovesModule |= shouldEmitMoves;
791
792 if (TimePassesIsEnabled)
793 ExceptionTimer->stopTimer();
794}
795
796/// EndFunction - Gather and emit post-function exception information.
797///
798void DwarfException::EndFunction() {
799 if (TimePassesIsEnabled)
800 ExceptionTimer->startTimer();
801
802 if (shouldEmitMoves || shouldEmitTable) {
803 EmitLabel("eh_func_end", SubprogramCount);
804 EmitExceptionTable();
805
806 // Save EH frame information
Bill Wendlingeb907212009-05-15 01:12:28 +0000807 EHFrames.push_back(
Chris Lattnere2cf37b2009-07-17 20:46:40 +0000808 FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
Bill Wendlingeb907212009-05-15 01:12:28 +0000809 SubprogramCount,
810 MMI->getPersonalityIndex(),
811 MF->getFrameInfo()->hasCalls(),
812 !MMI->getLandingPads().empty(),
813 MMI->getFrameMoves(),
814 MF->getFunction()));
815 }
816
817 if (TimePassesIsEnabled)
818 ExceptionTimer->stopTimer();
819}