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