Delete the MacOSJITEventListener per echristo's request. It was disabled by
[oota-llvm.git] / lib / ExecutionEngine / JIT / JITDwarfEmitter.cpp
1 //===----- JITDwarfEmitter.cpp - Write dwarf tables into memory -----------===//
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 defines a JITDwarfEmitter object that is used by the JIT to
11 // write dwarf tables to memory.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "JIT.h"
16 #include "JITDwarfEmitter.h"
17 #include "llvm/Function.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/CodeGen/JITCodeEmitter.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineLocation.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/ExecutionEngine/JITMemoryManager.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetFrameInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 using namespace llvm;
32
33 JITDwarfEmitter::JITDwarfEmitter(JIT& theJit) : MMI(0), Jit(theJit) {}
34
35
36 unsigned char* JITDwarfEmitter::EmitDwarfTable(MachineFunction& F, 
37                                                JITCodeEmitter& jce,
38                                                unsigned char* StartFunction,
39                                                unsigned char* EndFunction,
40                                                unsigned char* &EHFramePtr) {
41   assert(MMI && "MachineModuleInfo not registered!");
42
43   const TargetMachine& TM = F.getTarget();
44   TD = TM.getTargetData();
45   stackGrowthDirection = TM.getFrameInfo()->getStackGrowthDirection();
46   RI = TM.getRegisterInfo();
47   JCE = &jce;
48   
49   unsigned char* ExceptionTable = EmitExceptionTable(&F, StartFunction,
50                                                      EndFunction);
51       
52   unsigned char* Result = 0;
53
54   const std::vector<Function *> Personalities = MMI->getPersonalities();
55   EHFramePtr = EmitCommonEHFrame(Personalities[MMI->getPersonalityIndex()]);
56
57   Result = EmitEHFrame(Personalities[MMI->getPersonalityIndex()], EHFramePtr,
58                        StartFunction, EndFunction, ExceptionTable);
59
60   return Result;
61 }
62
63
64 void 
65 JITDwarfEmitter::EmitFrameMoves(intptr_t BaseLabelPtr,
66                                 const std::vector<MachineMove> &Moves) const {
67   unsigned PointerSize = TD->getPointerSize();
68   int stackGrowth = stackGrowthDirection == TargetFrameInfo::StackGrowsUp ?
69           PointerSize : -PointerSize;
70   bool IsLocal = false;
71   unsigned BaseLabelID = 0;
72
73   for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
74     const MachineMove &Move = Moves[i];
75     unsigned LabelID = Move.getLabelID();
76     
77     if (LabelID) {
78       LabelID = MMI->MappedLabel(LabelID);
79     
80       // Throw out move if the label is invalid.
81       if (!LabelID) continue;
82     }
83     
84     intptr_t LabelPtr = 0;
85     if (LabelID) LabelPtr = JCE->getLabelAddress(LabelID);
86
87     const MachineLocation &Dst = Move.getDestination();
88     const MachineLocation &Src = Move.getSource();
89     
90     // Advance row if new location.
91     if (BaseLabelPtr && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
92       JCE->emitByte(dwarf::DW_CFA_advance_loc4);
93       JCE->emitInt32(LabelPtr - BaseLabelPtr);
94       
95       BaseLabelID = LabelID; 
96       BaseLabelPtr = LabelPtr;
97       IsLocal = true;
98     }
99     
100     // If advancing cfa.
101     if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
102       if (!Src.isReg()) {
103         if (Src.getReg() == MachineLocation::VirtualFP) {
104           JCE->emitByte(dwarf::DW_CFA_def_cfa_offset);
105         } else {
106           JCE->emitByte(dwarf::DW_CFA_def_cfa);
107           JCE->emitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), true));
108         }
109         
110         JCE->emitULEB128Bytes(-Src.getOffset());
111       } else {
112         llvm_unreachable("Machine move not supported yet.");
113       }
114     } else if (Src.isReg() &&
115       Src.getReg() == MachineLocation::VirtualFP) {
116       if (Dst.isReg()) {
117         JCE->emitByte(dwarf::DW_CFA_def_cfa_register);
118         JCE->emitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), true));
119       } else {
120         llvm_unreachable("Machine move not supported yet.");
121       }
122     } else {
123       unsigned Reg = RI->getDwarfRegNum(Src.getReg(), true);
124       int Offset = Dst.getOffset() / stackGrowth;
125       
126       if (Offset < 0) {
127         JCE->emitByte(dwarf::DW_CFA_offset_extended_sf);
128         JCE->emitULEB128Bytes(Reg);
129         JCE->emitSLEB128Bytes(Offset);
130       } else if (Reg < 64) {
131         JCE->emitByte(dwarf::DW_CFA_offset + Reg);
132         JCE->emitULEB128Bytes(Offset);
133       } else {
134         JCE->emitByte(dwarf::DW_CFA_offset_extended);
135         JCE->emitULEB128Bytes(Reg);
136         JCE->emitULEB128Bytes(Offset);
137       }
138     }
139   }
140 }
141
142 /// SharedTypeIds - How many leading type ids two landing pads have in common.
143 static unsigned SharedTypeIds(const LandingPadInfo *L,
144                               const LandingPadInfo *R) {
145   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
146   unsigned LSize = LIds.size(), RSize = RIds.size();
147   unsigned MinSize = LSize < RSize ? LSize : RSize;
148   unsigned Count = 0;
149
150   for (; Count != MinSize; ++Count)
151     if (LIds[Count] != RIds[Count])
152       return Count;
153
154   return Count;
155 }
156
157
158 /// PadLT - Order landing pads lexicographically by type id.
159 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
160   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
161   unsigned LSize = LIds.size(), RSize = RIds.size();
162   unsigned MinSize = LSize < RSize ? LSize : RSize;
163
164   for (unsigned i = 0; i != MinSize; ++i)
165     if (LIds[i] != RIds[i])
166       return LIds[i] < RIds[i];
167
168   return LSize < RSize;
169 }
170
171 namespace {
172
173 struct KeyInfo {
174   static inline unsigned getEmptyKey() { return -1U; }
175   static inline unsigned getTombstoneKey() { return -2U; }
176   static unsigned getHashValue(const unsigned &Key) { return Key; }
177   static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
178   static bool isPod() { return true; }
179 };
180
181 /// ActionEntry - Structure describing an entry in the actions table.
182 struct ActionEntry {
183   int ValueForTypeID; // The value to write - may not be equal to the type id.
184   int NextAction;
185   struct ActionEntry *Previous;
186 };
187
188 /// PadRange - Structure holding a try-range and the associated landing pad.
189 struct PadRange {
190   // The index of the landing pad.
191   unsigned PadIndex;
192   // The index of the begin and end labels in the landing pad's label lists.
193   unsigned RangeIndex;
194 };
195
196 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
197
198 /// CallSiteEntry - Structure describing an entry in the call-site table.
199 struct CallSiteEntry {
200   unsigned BeginLabel; // zero indicates the start of the function.
201   unsigned EndLabel;   // zero indicates the end of the function.
202   unsigned PadLabel;   // zero indicates that there is no landing pad.
203   unsigned Action;
204 };
205
206 }
207
208 unsigned char* JITDwarfEmitter::EmitExceptionTable(MachineFunction* MF,
209                                          unsigned char* StartFunction,
210                                          unsigned char* EndFunction) const {
211   assert(MMI && "MachineModuleInfo not registered!");
212
213   // Map all labels and get rid of any dead landing pads.
214   MMI->TidyLandingPads();
215
216   const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
217   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
218   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
219   if (PadInfos.empty()) return 0;
220
221   // Sort the landing pads in order of their type ids.  This is used to fold
222   // duplicate actions.
223   SmallVector<const LandingPadInfo *, 64> LandingPads;
224   LandingPads.reserve(PadInfos.size());
225   for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
226     LandingPads.push_back(&PadInfos[i]);
227   std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
228
229   // Negative type ids index into FilterIds, positive type ids index into
230   // TypeInfos.  The value written for a positive type id is just the type
231   // id itself.  For a negative type id, however, the value written is the
232   // (negative) byte offset of the corresponding FilterIds entry.  The byte
233   // offset is usually equal to the type id, because the FilterIds entries
234   // are written using a variable width encoding which outputs one byte per
235   // entry as long as the value written is not too large, but can differ.
236   // This kind of complication does not occur for positive type ids because
237   // type infos are output using a fixed width encoding.
238   // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
239   SmallVector<int, 16> FilterOffsets;
240   FilterOffsets.reserve(FilterIds.size());
241   int Offset = -1;
242   for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
243     E = FilterIds.end(); I != E; ++I) {
244     FilterOffsets.push_back(Offset);
245     Offset -= MCAsmInfo::getULEB128Size(*I);
246   }
247
248   // Compute the actions table and gather the first action index for each
249   // landing pad site.
250   SmallVector<ActionEntry, 32> Actions;
251   SmallVector<unsigned, 64> FirstActions;
252   FirstActions.reserve(LandingPads.size());
253
254   int FirstAction = 0;
255   unsigned SizeActions = 0;
256   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
257     const LandingPadInfo *LP = LandingPads[i];
258     const std::vector<int> &TypeIds = LP->TypeIds;
259     const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
260     unsigned SizeSiteActions = 0;
261
262     if (NumShared < TypeIds.size()) {
263       unsigned SizeAction = 0;
264       ActionEntry *PrevAction = 0;
265
266       if (NumShared) {
267         const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
268         assert(Actions.size());
269         PrevAction = &Actions.back();
270         SizeAction = MCAsmInfo::getSLEB128Size(PrevAction->NextAction) +
271           MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
272         for (unsigned j = NumShared; j != SizePrevIds; ++j) {
273           SizeAction -= MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
274           SizeAction += -PrevAction->NextAction;
275           PrevAction = PrevAction->Previous;
276         }
277       }
278
279       // Compute the actions.
280       for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
281         int TypeID = TypeIds[I];
282         assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
283         int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
284         unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
285
286         int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
287         SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
288         SizeSiteActions += SizeAction;
289
290         ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
291         Actions.push_back(Action);
292
293         PrevAction = &Actions.back();
294       }
295
296       // Record the first action of the landing pad site.
297       FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
298     } // else identical - re-use previous FirstAction
299
300     FirstActions.push_back(FirstAction);
301
302     // Compute this sites contribution to size.
303     SizeActions += SizeSiteActions;
304   }
305
306   // Compute the call-site table.  Entries must be ordered by address.
307   SmallVector<CallSiteEntry, 64> CallSites;
308
309   RangeMapType PadMap;
310   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
311     const LandingPadInfo *LandingPad = LandingPads[i];
312     for (unsigned j=0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
313       unsigned BeginLabel = LandingPad->BeginLabels[j];
314       assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
315       PadRange P = { i, j };
316       PadMap[BeginLabel] = P;
317     }
318   }
319
320   bool MayThrow = false;
321   unsigned LastLabel = 0;
322   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
323         I != E; ++I) {
324     for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
325           MI != E; ++MI) {
326       if (!MI->isLabel()) {
327         MayThrow |= MI->getDesc().isCall();
328         continue;
329       }
330
331       unsigned BeginLabel = MI->getOperand(0).getImm();
332       assert(BeginLabel && "Invalid label!");
333
334       if (BeginLabel == LastLabel)
335         MayThrow = false;
336
337       RangeMapType::iterator L = PadMap.find(BeginLabel);
338
339       if (L == PadMap.end())
340         continue;
341
342       PadRange P = L->second;
343       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
344
345       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
346               "Inconsistent landing pad map!");
347
348       // If some instruction between the previous try-range and this one may
349       // throw, create a call-site entry with no landing pad for the region
350       // between the try-ranges.
351       if (MayThrow) {
352         CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
353         CallSites.push_back(Site);
354       }
355
356       LastLabel = LandingPad->EndLabels[P.RangeIndex];
357       CallSiteEntry Site = {BeginLabel, LastLabel,
358         LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
359
360       assert(Site.BeginLabel && Site.EndLabel && Site.PadLabel &&
361               "Invalid landing pad!");
362
363       // Try to merge with the previous call-site.
364       if (CallSites.size()) {
365         CallSiteEntry &Prev = CallSites.back();
366         if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
367           // Extend the range of the previous entry.
368           Prev.EndLabel = Site.EndLabel;
369           continue;
370         }
371       }
372
373       // Otherwise, create a new call-site.
374       CallSites.push_back(Site);
375     }
376   }
377   // If some instruction between the previous try-range and the end of the
378   // function may throw, create a call-site entry with no landing pad for the
379   // region following the try-range.
380   if (MayThrow) {
381     CallSiteEntry Site = {LastLabel, 0, 0, 0};
382     CallSites.push_back(Site);
383   }
384
385   // Final tallies.
386   unsigned SizeSites = CallSites.size() * (sizeof(int32_t) + // Site start.
387                                             sizeof(int32_t) + // Site length.
388                                             sizeof(int32_t)); // Landing pad.
389   for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
390     SizeSites += MCAsmInfo::getULEB128Size(CallSites[i].Action);
391
392   unsigned SizeTypes = TypeInfos.size() * TD->getPointerSize();
393
394   unsigned TypeOffset = sizeof(int8_t) + // Call site format
395                         // Call-site table length
396                         MCAsmInfo::getULEB128Size(SizeSites) + 
397                         SizeSites + SizeActions + SizeTypes;
398
399   // Begin the exception table.
400   JCE->emitAlignmentWithFill(4, 0);
401   // Asm->EOL("Padding");
402
403   unsigned char* DwarfExceptionTable = (unsigned char*)JCE->getCurrentPCValue();
404
405   // Emit the header.
406   JCE->emitByte(dwarf::DW_EH_PE_omit);
407   // Asm->EOL("LPStart format (DW_EH_PE_omit)");
408   JCE->emitByte(dwarf::DW_EH_PE_absptr);
409   // Asm->EOL("TType format (DW_EH_PE_absptr)");
410   JCE->emitULEB128Bytes(TypeOffset);
411   // Asm->EOL("TType base offset");
412   JCE->emitByte(dwarf::DW_EH_PE_udata4);
413   // Asm->EOL("Call site format (DW_EH_PE_udata4)");
414   JCE->emitULEB128Bytes(SizeSites);
415   // Asm->EOL("Call-site table length");
416
417   // Emit the landing pad site information.
418   for (unsigned i = 0; i < CallSites.size(); ++i) {
419     CallSiteEntry &S = CallSites[i];
420     intptr_t BeginLabelPtr = 0;
421     intptr_t EndLabelPtr = 0;
422
423     if (!S.BeginLabel) {
424       BeginLabelPtr = (intptr_t)StartFunction;
425       JCE->emitInt32(0);
426     } else {
427       BeginLabelPtr = JCE->getLabelAddress(S.BeginLabel);
428       JCE->emitInt32(BeginLabelPtr - (intptr_t)StartFunction);
429     }
430
431     // Asm->EOL("Region start");
432
433     if (!S.EndLabel) {
434       EndLabelPtr = (intptr_t)EndFunction;
435       JCE->emitInt32((intptr_t)EndFunction - BeginLabelPtr);
436     } else {
437       EndLabelPtr = JCE->getLabelAddress(S.EndLabel);
438       JCE->emitInt32(EndLabelPtr - BeginLabelPtr);
439     }
440     //Asm->EOL("Region length");
441
442     if (!S.PadLabel) {
443       JCE->emitInt32(0);
444     } else {
445       unsigned PadLabelPtr = JCE->getLabelAddress(S.PadLabel);
446       JCE->emitInt32(PadLabelPtr - (intptr_t)StartFunction);
447     }
448     // Asm->EOL("Landing pad");
449
450     JCE->emitULEB128Bytes(S.Action);
451     // Asm->EOL("Action");
452   }
453
454   // Emit the actions.
455   for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
456     ActionEntry &Action = Actions[I];
457
458     JCE->emitSLEB128Bytes(Action.ValueForTypeID);
459     //Asm->EOL("TypeInfo index");
460     JCE->emitSLEB128Bytes(Action.NextAction);
461     //Asm->EOL("Next action");
462   }
463
464   // Emit the type ids.
465   for (unsigned M = TypeInfos.size(); M; --M) {
466     GlobalVariable *GV = TypeInfos[M - 1];
467     
468     if (GV) {
469       if (TD->getPointerSize() == sizeof(int32_t))
470         JCE->emitInt32((intptr_t)Jit.getOrEmitGlobalVariable(GV));
471       else
472         JCE->emitInt64((intptr_t)Jit.getOrEmitGlobalVariable(GV));
473     } else {
474       if (TD->getPointerSize() == sizeof(int32_t))
475         JCE->emitInt32(0);
476       else
477         JCE->emitInt64(0);
478     }
479     // Asm->EOL("TypeInfo");
480   }
481
482   // Emit the filter typeids.
483   for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
484     unsigned TypeID = FilterIds[j];
485     JCE->emitULEB128Bytes(TypeID);
486     //Asm->EOL("Filter TypeInfo index");
487   }
488
489   JCE->emitAlignmentWithFill(4, 0);
490
491   return DwarfExceptionTable;
492 }
493
494 unsigned char*
495 JITDwarfEmitter::EmitCommonEHFrame(const Function* Personality) const {
496   unsigned PointerSize = TD->getPointerSize();
497   int stackGrowth = stackGrowthDirection == TargetFrameInfo::StackGrowsUp ?
498           PointerSize : -PointerSize;
499   
500   unsigned char* StartCommonPtr = (unsigned char*)JCE->getCurrentPCValue();
501   // EH Common Frame header
502   JCE->allocateSpace(4, 0);
503   unsigned char* FrameCommonBeginPtr = (unsigned char*)JCE->getCurrentPCValue();
504   JCE->emitInt32((int)0);
505   JCE->emitByte(dwarf::DW_CIE_VERSION);
506   JCE->emitString(Personality ? "zPLR" : "zR");
507   JCE->emitULEB128Bytes(1);
508   JCE->emitSLEB128Bytes(stackGrowth);
509   JCE->emitByte(RI->getDwarfRegNum(RI->getRARegister(), true));
510
511   if (Personality) {
512     // Augmentation Size: 3 small ULEBs of one byte each, and the personality
513     // function which size is PointerSize.
514     JCE->emitULEB128Bytes(3 + PointerSize); 
515     
516     // We set the encoding of the personality as direct encoding because we use
517     // the function pointer. The encoding is not relative because the current
518     // PC value may be bigger than the personality function pointer.
519     if (PointerSize == 4) {
520       JCE->emitByte(dwarf::DW_EH_PE_sdata4); 
521       JCE->emitInt32(((intptr_t)Jit.getPointerToGlobal(Personality)));
522     } else {
523       JCE->emitByte(dwarf::DW_EH_PE_sdata8);
524       JCE->emitInt64(((intptr_t)Jit.getPointerToGlobal(Personality)));
525     }
526
527     JCE->emitULEB128Bytes(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
528     JCE->emitULEB128Bytes(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
529   } else {
530     JCE->emitULEB128Bytes(1);
531     JCE->emitULEB128Bytes(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
532   }
533
534   std::vector<MachineMove> Moves;
535   RI->getInitialFrameState(Moves);
536   EmitFrameMoves(0, Moves);
537
538   JCE->emitAlignmentWithFill(PointerSize, dwarf::DW_CFA_nop);
539
540   JCE->emitInt32At((uintptr_t*)StartCommonPtr,
541                    (uintptr_t)((unsigned char*)JCE->getCurrentPCValue() -
542                                FrameCommonBeginPtr));
543
544   return StartCommonPtr;
545 }
546
547
548 unsigned char*
549 JITDwarfEmitter::EmitEHFrame(const Function* Personality,
550                              unsigned char* StartCommonPtr,
551                              unsigned char* StartFunction, 
552                              unsigned char* EndFunction,
553                              unsigned char* ExceptionTable) const {
554   unsigned PointerSize = TD->getPointerSize();
555   
556   // EH frame header.
557   unsigned char* StartEHPtr = (unsigned char*)JCE->getCurrentPCValue();
558   JCE->allocateSpace(4, 0);
559   unsigned char* FrameBeginPtr = (unsigned char*)JCE->getCurrentPCValue();
560   // FDE CIE Offset
561   JCE->emitInt32(FrameBeginPtr - StartCommonPtr);
562   JCE->emitInt32(StartFunction - (unsigned char*)JCE->getCurrentPCValue());
563   JCE->emitInt32(EndFunction - StartFunction);
564
565   // If there is a personality and landing pads then point to the language
566   // specific data area in the exception table.
567   if (Personality) {
568     JCE->emitULEB128Bytes(PointerSize == 4 ? 4 : 8);
569         
570     if (PointerSize == 4) {
571       if (!MMI->getLandingPads().empty())
572         JCE->emitInt32(ExceptionTable-(unsigned char*)JCE->getCurrentPCValue());
573       else
574         JCE->emitInt32((int)0);
575     } else {
576       if (!MMI->getLandingPads().empty())
577         JCE->emitInt64(ExceptionTable-(unsigned char*)JCE->getCurrentPCValue());
578       else
579         JCE->emitInt64((int)0);
580     }
581   } else {
582     JCE->emitULEB128Bytes(0);
583   }
584       
585   // Indicate locations of function specific  callee saved registers in
586   // frame.
587   EmitFrameMoves((intptr_t)StartFunction, MMI->getFrameMoves());
588
589   JCE->emitAlignmentWithFill(PointerSize, dwarf::DW_CFA_nop);
590
591   // Indicate the size of the table
592   JCE->emitInt32At((uintptr_t*)StartEHPtr,
593                    (uintptr_t)((unsigned char*)JCE->getCurrentPCValue() -
594                                StartEHPtr));
595
596   // Double zeroes for the unwind runtime
597   if (PointerSize == 8) {
598     JCE->emitInt64(0);
599     JCE->emitInt64(0);
600   } else {
601     JCE->emitInt32(0);
602     JCE->emitInt32(0);
603   }
604   
605   return StartEHPtr;
606 }
607
608 unsigned JITDwarfEmitter::GetDwarfTableSizeInBytes(MachineFunction& F,
609                                          JITCodeEmitter& jce,
610                                          unsigned char* StartFunction,
611                                          unsigned char* EndFunction) {
612   const TargetMachine& TM = F.getTarget();
613   TD = TM.getTargetData();
614   stackGrowthDirection = TM.getFrameInfo()->getStackGrowthDirection();
615   RI = TM.getRegisterInfo();
616   JCE = &jce;
617   unsigned FinalSize = 0;
618   
619   FinalSize += GetExceptionTableSizeInBytes(&F);
620       
621   const std::vector<Function *> Personalities = MMI->getPersonalities();
622   FinalSize += 
623     GetCommonEHFrameSizeInBytes(Personalities[MMI->getPersonalityIndex()]);
624
625   FinalSize += GetEHFrameSizeInBytes(Personalities[MMI->getPersonalityIndex()],
626                                      StartFunction);
627
628   return FinalSize;
629 }
630
631 /// RoundUpToAlign - Add the specified alignment to FinalSize and returns
632 /// the new value.
633 static unsigned RoundUpToAlign(unsigned FinalSize, unsigned Alignment) {
634   if (Alignment == 0) Alignment = 1;
635   // Since we do not know where the buffer will be allocated, be pessimistic.
636   return FinalSize + Alignment;
637 }
638   
639 unsigned
640 JITDwarfEmitter::GetEHFrameSizeInBytes(const Function* Personality,
641                                        unsigned char* StartFunction) const { 
642   unsigned PointerSize = TD->getPointerSize();
643   unsigned FinalSize = 0;
644   // EH frame header.
645   FinalSize += PointerSize;
646   // FDE CIE Offset
647   FinalSize += 3 * PointerSize;
648   // If there is a personality and landing pads then point to the language
649   // specific data area in the exception table.
650   if (Personality) {
651     FinalSize += MCAsmInfo::getULEB128Size(4); 
652     FinalSize += PointerSize;
653   } else {
654     FinalSize += MCAsmInfo::getULEB128Size(0);
655   }
656       
657   // Indicate locations of function specific  callee saved registers in
658   // frame.
659   FinalSize += GetFrameMovesSizeInBytes((intptr_t)StartFunction,
660                                         MMI->getFrameMoves());
661       
662   FinalSize = RoundUpToAlign(FinalSize, 4);
663   
664   // Double zeroes for the unwind runtime
665   FinalSize += 2 * PointerSize;
666
667   return FinalSize;
668 }
669
670 unsigned JITDwarfEmitter::GetCommonEHFrameSizeInBytes(const Function* Personality) 
671   const {
672
673   unsigned PointerSize = TD->getPointerSize();
674   int stackGrowth = stackGrowthDirection == TargetFrameInfo::StackGrowsUp ?
675           PointerSize : -PointerSize;
676   unsigned FinalSize = 0; 
677   // EH Common Frame header
678   FinalSize += PointerSize;
679   FinalSize += 4;
680   FinalSize += 1;
681   FinalSize += Personality ? 5 : 3; // "zPLR" or "zR"
682   FinalSize += MCAsmInfo::getULEB128Size(1);
683   FinalSize += MCAsmInfo::getSLEB128Size(stackGrowth);
684   FinalSize += 1;
685   
686   if (Personality) {
687     FinalSize += MCAsmInfo::getULEB128Size(7);
688     
689     // Encoding
690     FinalSize+= 1;
691     //Personality
692     FinalSize += PointerSize;
693     
694     FinalSize += MCAsmInfo::getULEB128Size(dwarf::DW_EH_PE_pcrel);
695     FinalSize += MCAsmInfo::getULEB128Size(dwarf::DW_EH_PE_pcrel);
696       
697   } else {
698     FinalSize += MCAsmInfo::getULEB128Size(1);
699     FinalSize += MCAsmInfo::getULEB128Size(dwarf::DW_EH_PE_pcrel);
700   }
701
702   std::vector<MachineMove> Moves;
703   RI->getInitialFrameState(Moves);
704   FinalSize += GetFrameMovesSizeInBytes(0, Moves);
705   FinalSize = RoundUpToAlign(FinalSize, 4);
706   return FinalSize;
707 }
708
709 unsigned
710 JITDwarfEmitter::GetFrameMovesSizeInBytes(intptr_t BaseLabelPtr,
711                                   const std::vector<MachineMove> &Moves) const {
712   unsigned PointerSize = TD->getPointerSize();
713   int stackGrowth = stackGrowthDirection == TargetFrameInfo::StackGrowsUp ?
714           PointerSize : -PointerSize;
715   bool IsLocal = BaseLabelPtr;
716   unsigned FinalSize = 0; 
717
718   for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
719     const MachineMove &Move = Moves[i];
720     unsigned LabelID = Move.getLabelID();
721     
722     if (LabelID) {
723       LabelID = MMI->MappedLabel(LabelID);
724     
725       // Throw out move if the label is invalid.
726       if (!LabelID) continue;
727     }
728     
729     intptr_t LabelPtr = 0;
730     if (LabelID) LabelPtr = JCE->getLabelAddress(LabelID);
731
732     const MachineLocation &Dst = Move.getDestination();
733     const MachineLocation &Src = Move.getSource();
734     
735     // Advance row if new location.
736     if (BaseLabelPtr && LabelID && (BaseLabelPtr != LabelPtr || !IsLocal)) {
737       FinalSize++;
738       FinalSize += PointerSize;
739       BaseLabelPtr = LabelPtr;
740       IsLocal = true;
741     }
742     
743     // If advancing cfa.
744     if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
745       if (!Src.isReg()) {
746         if (Src.getReg() == MachineLocation::VirtualFP) {
747           ++FinalSize;
748         } else {
749           ++FinalSize;
750           unsigned RegNum = RI->getDwarfRegNum(Src.getReg(), true);
751           FinalSize += MCAsmInfo::getULEB128Size(RegNum);
752         }
753         
754         int Offset = -Src.getOffset();
755         
756         FinalSize += MCAsmInfo::getULEB128Size(Offset);
757       } else {
758         llvm_unreachable("Machine move no supported yet.");
759       }
760     } else if (Src.isReg() &&
761       Src.getReg() == MachineLocation::VirtualFP) {
762       if (Dst.isReg()) {
763         ++FinalSize;
764         unsigned RegNum = RI->getDwarfRegNum(Dst.getReg(), true);
765         FinalSize += MCAsmInfo::getULEB128Size(RegNum);
766       } else {
767         llvm_unreachable("Machine move no supported yet.");
768       }
769     } else {
770       unsigned Reg = RI->getDwarfRegNum(Src.getReg(), true);
771       int Offset = Dst.getOffset() / stackGrowth;
772       
773       if (Offset < 0) {
774         ++FinalSize;
775         FinalSize += MCAsmInfo::getULEB128Size(Reg);
776         FinalSize += MCAsmInfo::getSLEB128Size(Offset);
777       } else if (Reg < 64) {
778         ++FinalSize;
779         FinalSize += MCAsmInfo::getULEB128Size(Offset);
780       } else {
781         ++FinalSize;
782         FinalSize += MCAsmInfo::getULEB128Size(Reg);
783         FinalSize += MCAsmInfo::getULEB128Size(Offset);
784       }
785     }
786   }
787   return FinalSize;
788 }
789
790 unsigned 
791 JITDwarfEmitter::GetExceptionTableSizeInBytes(MachineFunction* MF) const {
792   unsigned FinalSize = 0;
793
794   // Map all labels and get rid of any dead landing pads.
795   MMI->TidyLandingPads();
796
797   const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
798   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
799   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
800   if (PadInfos.empty()) return 0;
801
802   // Sort the landing pads in order of their type ids.  This is used to fold
803   // duplicate actions.
804   SmallVector<const LandingPadInfo *, 64> LandingPads;
805   LandingPads.reserve(PadInfos.size());
806   for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
807     LandingPads.push_back(&PadInfos[i]);
808   std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
809
810   // Negative type ids index into FilterIds, positive type ids index into
811   // TypeInfos.  The value written for a positive type id is just the type
812   // id itself.  For a negative type id, however, the value written is the
813   // (negative) byte offset of the corresponding FilterIds entry.  The byte
814   // offset is usually equal to the type id, because the FilterIds entries
815   // are written using a variable width encoding which outputs one byte per
816   // entry as long as the value written is not too large, but can differ.
817   // This kind of complication does not occur for positive type ids because
818   // type infos are output using a fixed width encoding.
819   // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
820   SmallVector<int, 16> FilterOffsets;
821   FilterOffsets.reserve(FilterIds.size());
822   int Offset = -1;
823   for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
824     E = FilterIds.end(); I != E; ++I) {
825     FilterOffsets.push_back(Offset);
826     Offset -= MCAsmInfo::getULEB128Size(*I);
827   }
828
829   // Compute the actions table and gather the first action index for each
830   // landing pad site.
831   SmallVector<ActionEntry, 32> Actions;
832   SmallVector<unsigned, 64> FirstActions;
833   FirstActions.reserve(LandingPads.size());
834
835   int FirstAction = 0;
836   unsigned SizeActions = 0;
837   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
838     const LandingPadInfo *LP = LandingPads[i];
839     const std::vector<int> &TypeIds = LP->TypeIds;
840     const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
841     unsigned SizeSiteActions = 0;
842
843     if (NumShared < TypeIds.size()) {
844       unsigned SizeAction = 0;
845       ActionEntry *PrevAction = 0;
846
847       if (NumShared) {
848         const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
849         assert(Actions.size());
850         PrevAction = &Actions.back();
851         SizeAction = MCAsmInfo::getSLEB128Size(PrevAction->NextAction) +
852           MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
853         for (unsigned j = NumShared; j != SizePrevIds; ++j) {
854           SizeAction -= MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
855           SizeAction += -PrevAction->NextAction;
856           PrevAction = PrevAction->Previous;
857         }
858       }
859
860       // Compute the actions.
861       for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
862         int TypeID = TypeIds[I];
863         assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
864         int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
865         unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
866
867         int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
868         SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
869         SizeSiteActions += SizeAction;
870
871         ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
872         Actions.push_back(Action);
873
874         PrevAction = &Actions.back();
875       }
876
877       // Record the first action of the landing pad site.
878       FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
879     } // else identical - re-use previous FirstAction
880
881     FirstActions.push_back(FirstAction);
882
883     // Compute this sites contribution to size.
884     SizeActions += SizeSiteActions;
885   }
886
887   // Compute the call-site table.  Entries must be ordered by address.
888   SmallVector<CallSiteEntry, 64> CallSites;
889
890   RangeMapType PadMap;
891   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
892     const LandingPadInfo *LandingPad = LandingPads[i];
893     for (unsigned j=0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
894       unsigned BeginLabel = LandingPad->BeginLabels[j];
895       assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
896       PadRange P = { i, j };
897       PadMap[BeginLabel] = P;
898     }
899   }
900
901   bool MayThrow = false;
902   unsigned LastLabel = 0;
903   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
904         I != E; ++I) {
905     for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
906           MI != E; ++MI) {
907       if (!MI->isLabel()) {
908         MayThrow |= MI->getDesc().isCall();
909         continue;
910       }
911
912       unsigned BeginLabel = MI->getOperand(0).getImm();
913       assert(BeginLabel && "Invalid label!");
914
915       if (BeginLabel == LastLabel)
916         MayThrow = false;
917
918       RangeMapType::iterator L = PadMap.find(BeginLabel);
919
920       if (L == PadMap.end())
921         continue;
922
923       PadRange P = L->second;
924       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
925
926       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
927               "Inconsistent landing pad map!");
928
929       // If some instruction between the previous try-range and this one may
930       // throw, create a call-site entry with no landing pad for the region
931       // between the try-ranges.
932       if (MayThrow) {
933         CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
934         CallSites.push_back(Site);
935       }
936
937       LastLabel = LandingPad->EndLabels[P.RangeIndex];
938       CallSiteEntry Site = {BeginLabel, LastLabel,
939         LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
940
941       assert(Site.BeginLabel && Site.EndLabel && Site.PadLabel &&
942               "Invalid landing pad!");
943
944       // Try to merge with the previous call-site.
945       if (CallSites.size()) {
946         CallSiteEntry &Prev = CallSites.back();
947         if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
948           // Extend the range of the previous entry.
949           Prev.EndLabel = Site.EndLabel;
950           continue;
951         }
952       }
953
954       // Otherwise, create a new call-site.
955       CallSites.push_back(Site);
956     }
957   }
958   // If some instruction between the previous try-range and the end of the
959   // function may throw, create a call-site entry with no landing pad for the
960   // region following the try-range.
961   if (MayThrow) {
962     CallSiteEntry Site = {LastLabel, 0, 0, 0};
963     CallSites.push_back(Site);
964   }
965
966   // Final tallies.
967   unsigned SizeSites = CallSites.size() * (sizeof(int32_t) + // Site start.
968                                             sizeof(int32_t) + // Site length.
969                                             sizeof(int32_t)); // Landing pad.
970   for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
971     SizeSites += MCAsmInfo::getULEB128Size(CallSites[i].Action);
972
973   unsigned SizeTypes = TypeInfos.size() * TD->getPointerSize();
974
975   unsigned TypeOffset = sizeof(int8_t) + // Call site format
976                         // Call-site table length
977                         MCAsmInfo::getULEB128Size(SizeSites) + 
978                         SizeSites + SizeActions + SizeTypes;
979
980   unsigned TotalSize = sizeof(int8_t) + // LPStart format
981                        sizeof(int8_t) + // TType format
982                        MCAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
983                        TypeOffset;
984
985   unsigned SizeAlign = (4 - TotalSize) & 3;
986
987   // Begin the exception table.
988   FinalSize = RoundUpToAlign(FinalSize, 4);
989   for (unsigned i = 0; i != SizeAlign; ++i) {
990     ++FinalSize;
991   }
992   
993   unsigned PointerSize = TD->getPointerSize();
994
995   // Emit the header.
996   ++FinalSize;
997   // Asm->EOL("LPStart format (DW_EH_PE_omit)");
998   ++FinalSize;
999   // Asm->EOL("TType format (DW_EH_PE_absptr)");
1000   ++FinalSize;
1001   // Asm->EOL("TType base offset");
1002   ++FinalSize;
1003   // Asm->EOL("Call site format (DW_EH_PE_udata4)");
1004   ++FinalSize;
1005   // Asm->EOL("Call-site table length");
1006
1007   // Emit the landing pad site information.
1008   for (unsigned i = 0; i < CallSites.size(); ++i) {
1009     CallSiteEntry &S = CallSites[i];
1010
1011     // Asm->EOL("Region start");
1012     FinalSize += PointerSize;
1013     
1014     //Asm->EOL("Region length");
1015     FinalSize += PointerSize;
1016
1017     // Asm->EOL("Landing pad");
1018     FinalSize += PointerSize;
1019
1020     FinalSize += MCAsmInfo::getULEB128Size(S.Action);
1021     // Asm->EOL("Action");
1022   }
1023
1024   // Emit the actions.
1025   for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
1026     ActionEntry &Action = Actions[I];
1027
1028     //Asm->EOL("TypeInfo index");
1029     FinalSize += MCAsmInfo::getSLEB128Size(Action.ValueForTypeID);
1030     //Asm->EOL("Next action");
1031     FinalSize += MCAsmInfo::getSLEB128Size(Action.NextAction);
1032   }
1033
1034   // Emit the type ids.
1035   for (unsigned M = TypeInfos.size(); M; --M) {
1036     // Asm->EOL("TypeInfo");
1037     FinalSize += PointerSize;
1038   }
1039
1040   // Emit the filter typeids.
1041   for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
1042     unsigned TypeID = FilterIds[j];
1043     FinalSize += MCAsmInfo::getULEB128Size(TypeID);
1044     //Asm->EOL("Filter TypeInfo index");
1045   }
1046   
1047   FinalSize = RoundUpToAlign(FinalSize, 4);
1048
1049   return FinalSize;
1050 }