use stripPointerCasts to simplify some code.
[oota-llvm.git] / lib / CodeGen / MachineModuleInfo.cpp
1 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
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 #include "llvm/CodeGen/MachineModuleInfo.h"
11
12 #include "llvm/Constants.h"
13 #include "llvm/Analysis/ValueTracking.h"
14 #include "llvm/CodeGen/MachineFunctionPass.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/Target/TargetInstrInfo.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Target/TargetOptions.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Module.h"
25 #include "llvm/Support/Dwarf.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/Streams.h"
28 using namespace llvm;
29 using namespace llvm::dwarf;
30
31 // Handle the Pass registration stuff necessary to use TargetData's.
32 static RegisterPass<MachineModuleInfo>
33 X("machinemoduleinfo", "Module Information");
34 char MachineModuleInfo::ID = 0;
35
36 //===----------------------------------------------------------------------===//
37   
38 MachineModuleInfo::MachineModuleInfo()
39 : ImmutablePass(&ID)
40 , LabelIDList()
41 , FrameMoves()
42 , LandingPads()
43 , Personalities()
44 , CallsEHReturn(0)
45 , CallsUnwindInit(0)
46 , DbgInfoAvailable(false)
47 {
48   // Always emit "no personality" info
49   Personalities.push_back(NULL);
50 }
51 MachineModuleInfo::~MachineModuleInfo() {
52
53 }
54
55 /// doInitialization - Initialize the state for a new module.
56 ///
57 bool MachineModuleInfo::doInitialization() {
58   return false;
59 }
60
61 /// doFinalization - Tear down the state after completion of a module.
62 ///
63 bool MachineModuleInfo::doFinalization() {
64   return false;
65 }
66
67 /// BeginFunction - Begin gathering function meta information.
68 ///
69 void MachineModuleInfo::BeginFunction(MachineFunction *MF) {
70   // Coming soon.
71 }
72
73 /// EndFunction - Discard function meta information.
74 ///
75 void MachineModuleInfo::EndFunction() {
76   // Clean up frame info.
77   FrameMoves.clear();
78   
79   // Clean up exception info.
80   LandingPads.clear();
81   TypeInfos.clear();
82   FilterIds.clear();
83   FilterEnds.clear();
84   CallsEHReturn = 0;
85   CallsUnwindInit = 0;
86 }
87
88 /// AnalyzeModule - Scan the module for global debug information.
89 ///
90 void MachineModuleInfo::AnalyzeModule(Module &M) {
91   // Insert functions in the llvm.used array into UsedFunctions.
92   GlobalVariable *GV = M.getGlobalVariable("llvm.used");
93   if (!GV || !GV->hasInitializer()) return;
94
95   // Should be an array of 'i8*'.
96   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
97   if (InitList == 0) return;
98
99   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
100     if (Function *F =
101           dyn_cast<Function>(InitList->getOperand(i)->stripPointerCasts()))
102       UsedFunctions.insert(F);
103 }
104
105 //===-EH-------------------------------------------------------------------===//
106
107 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
108 /// specified MachineBasicBlock.
109 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo
110     (MachineBasicBlock *LandingPad) {
111   unsigned N = LandingPads.size();
112   for (unsigned i = 0; i < N; ++i) {
113     LandingPadInfo &LP = LandingPads[i];
114     if (LP.LandingPadBlock == LandingPad)
115       return LP;
116   }
117   
118   LandingPads.push_back(LandingPadInfo(LandingPad));
119   return LandingPads[N];
120 }
121
122 /// addInvoke - Provide the begin and end labels of an invoke style call and
123 /// associate it with a try landing pad block.
124 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,
125                                   unsigned BeginLabel, unsigned EndLabel) {
126   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
127   LP.BeginLabels.push_back(BeginLabel);
128   LP.EndLabels.push_back(EndLabel);
129 }
130
131 /// addLandingPad - Provide the label of a try LandingPad block.
132 ///
133 unsigned MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
134   unsigned LandingPadLabel = NextLabelID();
135   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
136   LP.LandingPadLabel = LandingPadLabel;  
137   return LandingPadLabel;
138 }
139
140 /// addPersonality - Provide the personality function for the exception
141 /// information.
142 void MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad,
143                                        Function *Personality) {
144   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
145   LP.Personality = Personality;
146
147   for (unsigned i = 0; i < Personalities.size(); ++i)
148     if (Personalities[i] == Personality)
149       return;
150   
151   Personalities.push_back(Personality);
152 }
153
154 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
155 ///
156 void MachineModuleInfo::addCatchTypeInfo(MachineBasicBlock *LandingPad,
157                                         std::vector<GlobalVariable *> &TyInfo) {
158   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
159   for (unsigned N = TyInfo.size(); N; --N)
160     LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
161 }
162
163 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
164 ///
165 void MachineModuleInfo::addFilterTypeInfo(MachineBasicBlock *LandingPad,
166                                         std::vector<GlobalVariable *> &TyInfo) {
167   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
168   std::vector<unsigned> IdsInFilter(TyInfo.size());
169   for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
170     IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
171   LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
172 }
173
174 /// addCleanup - Add a cleanup action for a landing pad.
175 ///
176 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
177   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
178   LP.TypeIds.push_back(0);
179 }
180
181 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
182 /// pads.
183 void MachineModuleInfo::TidyLandingPads() {
184   for (unsigned i = 0; i != LandingPads.size(); ) {
185     LandingPadInfo &LandingPad = LandingPads[i];
186     LandingPad.LandingPadLabel = MappedLabel(LandingPad.LandingPadLabel);
187
188     // Special case: we *should* emit LPs with null LP MBB. This indicates
189     // "nounwind" case.
190     if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
191       LandingPads.erase(LandingPads.begin() + i);
192       continue;
193     }
194
195     for (unsigned j=0; j != LandingPads[i].BeginLabels.size(); ) {
196       unsigned BeginLabel = MappedLabel(LandingPad.BeginLabels[j]);
197       unsigned EndLabel = MappedLabel(LandingPad.EndLabels[j]);
198
199       if (!BeginLabel || !EndLabel) {
200         LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
201         LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
202         continue;
203       }
204
205       LandingPad.BeginLabels[j] = BeginLabel;
206       LandingPad.EndLabels[j] = EndLabel;
207       ++j;
208     }
209
210     // Remove landing pads with no try-ranges.
211     if (LandingPads[i].BeginLabels.empty()) {
212       LandingPads.erase(LandingPads.begin() + i);
213       continue;
214     }
215
216     // If there is no landing pad, ensure that the list of typeids is empty.
217     // If the only typeid is a cleanup, this is the same as having no typeids.
218     if (!LandingPad.LandingPadBlock ||
219         (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
220       LandingPad.TypeIds.clear();
221
222     ++i;
223   }
224 }
225
226 /// getTypeIDFor - Return the type id for the specified typeinfo.  This is 
227 /// function wide.
228 unsigned MachineModuleInfo::getTypeIDFor(GlobalVariable *TI) {
229   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
230     if (TypeInfos[i] == TI) return i + 1;
231
232   TypeInfos.push_back(TI);
233   return TypeInfos.size();
234 }
235
236 /// getFilterIDFor - Return the filter id for the specified typeinfos.  This is
237 /// function wide.
238 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
239   // If the new filter coincides with the tail of an existing filter, then
240   // re-use the existing filter.  Folding filters more than this requires
241   // re-ordering filters and/or their elements - probably not worth it.
242   for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
243        E = FilterEnds.end(); I != E; ++I) {
244     unsigned i = *I, j = TyIds.size();
245
246     while (i && j)
247       if (FilterIds[--i] != TyIds[--j])
248         goto try_next;
249
250     if (!j)
251       // The new filter coincides with range [i, end) of the existing filter.
252       return -(1 + i);
253
254 try_next:;
255   }
256
257   // Add the new filter.
258   int FilterID = -(1 + FilterIds.size());
259   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
260   for (unsigned I = 0, N = TyIds.size(); I != N; ++I)
261     FilterIds.push_back(TyIds[I]);
262   FilterEnds.push_back(FilterIds.size());
263   FilterIds.push_back(0); // terminator
264   return FilterID;
265 }
266
267 /// getPersonality - Return the personality function for the current function.
268 Function *MachineModuleInfo::getPersonality() const {
269   // FIXME: Until PR1414 will be fixed, we're using 1 personality function per
270   // function
271   return !LandingPads.empty() ? LandingPads[0].Personality : NULL;
272 }
273
274 /// getPersonalityIndex - Return unique index for current personality
275 /// function. NULL personality function should always get zero index.
276 unsigned MachineModuleInfo::getPersonalityIndex() const {
277   const Function* Personality = NULL;
278   
279   // Scan landing pads. If there is at least one non-NULL personality - use it.
280   for (unsigned i = 0; i != LandingPads.size(); ++i)
281     if (LandingPads[i].Personality) {
282       Personality = LandingPads[i].Personality;
283       break;
284     }
285   
286   for (unsigned i = 0; i < Personalities.size(); ++i) {
287     if (Personalities[i] == Personality)
288       return i;
289   }
290
291   // This should never happen
292   llvm_unreachable("Personality function should be set!");
293   return 0;
294 }
295
296 //===----------------------------------------------------------------------===//
297 /// DebugLabelFolding pass - This pass prunes out redundant labels.  This allows
298 /// a info consumer to determine if the range of two labels is empty, by seeing
299 /// if the labels map to the same reduced label.
300
301 namespace llvm {
302
303 struct DebugLabelFolder : public MachineFunctionPass {
304   static char ID;
305   DebugLabelFolder() : MachineFunctionPass(&ID) {}
306
307   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
308     AU.addPreservedID(MachineLoopInfoID);
309     AU.addPreservedID(MachineDominatorsID);
310     MachineFunctionPass::getAnalysisUsage(AU);
311   }
312
313   virtual bool runOnMachineFunction(MachineFunction &MF);
314   virtual const char *getPassName() const { return "Label Folder"; }
315 };
316
317 char DebugLabelFolder::ID = 0;
318
319 bool DebugLabelFolder::runOnMachineFunction(MachineFunction &MF) {
320   // Get machine module info.
321   MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
322   if (!MMI) return false;
323   
324   // Track if change is made.
325   bool MadeChange = false;
326   // No prior label to begin.
327   unsigned PriorLabel = 0;
328   
329   // Iterate through basic blocks.
330   for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
331        BB != E; ++BB) {
332     // Iterate through instructions.
333     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
334       // Is it a label.
335       if (I->isDebugLabel() && !MMI->isDbgLabelUsed(I->getOperand(0).getImm())){
336         // The label ID # is always operand #0, an immediate.
337         unsigned NextLabel = I->getOperand(0).getImm();
338         
339         // If there was an immediate prior label.
340         if (PriorLabel) {
341           // Remap the current label to prior label.
342           MMI->RemapLabel(NextLabel, PriorLabel);
343           // Delete the current label.
344           I = BB->erase(I);
345           // Indicate a change has been made.
346           MadeChange = true;
347           continue;
348         } else {
349           // Start a new round.
350           PriorLabel = NextLabel;
351         }
352        } else {
353         // No consecutive labels.
354         PriorLabel = 0;
355       }
356       
357       ++I;
358     }
359   }
360   
361   return MadeChange;
362 }
363
364 FunctionPass *createDebugLabelFoldingPass() { return new DebugLabelFolder(); }
365
366 }
367