MachineFunction.cpp revision a4eb44a285984ec999de632beb5145b099f5416d
1//===-- MachineFunction.cpp -----------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Collect native machine code information for a function.  This allows
11// target-specific information about the generated code to be stored with each
12// function.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/CodeGen/MachineFunctionPass.h"
17#include "llvm/CodeGen/MachineInstr.h"
18#include "llvm/CodeGen/SSARegMap.h"
19#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineConstantPool.h"
21#include "llvm/CodeGen/MachineJumpTableInfo.h"
22#include "llvm/CodeGen/Passes.h"
23#include "llvm/Target/TargetData.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Target/TargetFrameInfo.h"
26#include "llvm/Function.h"
27#include "llvm/Instructions.h"
28#include "llvm/Support/Compiler.h"
29#include "llvm/Support/GraphWriter.h"
30#include "llvm/Support/LeakDetector.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/Config/config.h"
33#include <fstream>
34#include <iostream>
35#include <sstream>
36
37using namespace llvm;
38
39static AnnotationID MF_AID(
40  AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
41
42// Out of line virtual function to home classes.
43void MachineFunctionPass::virtfn() {}
44
45namespace {
46  struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
47    std::ostream *OS;
48    const std::string Banner;
49
50    Printer (std::ostream *_OS, const std::string &_Banner) :
51      OS (_OS), Banner (_Banner) { }
52
53    const char *getPassName() const { return "MachineFunction Printer"; }
54
55    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56      AU.setPreservesAll();
57    }
58
59    bool runOnMachineFunction(MachineFunction &MF) {
60      (*OS) << Banner;
61      MF.print (*OS);
62      return false;
63    }
64  };
65}
66
67/// Returns a newly-created MachineFunction Printer pass. The default output
68/// stream is std::cerr; the default banner is empty.
69///
70FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
71                                                     const std::string &Banner){
72  return new Printer(OS, Banner);
73}
74
75namespace {
76  struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
77    const char *getPassName() const { return "Machine Code Deleter"; }
78
79    bool runOnMachineFunction(MachineFunction &MF) {
80      // Delete the annotation from the function now.
81      MachineFunction::destruct(MF.getFunction());
82      return true;
83    }
84  };
85}
86
87/// MachineCodeDeletion Pass - This pass deletes all of the machine code for
88/// the current function, which should happen after the function has been
89/// emitted to a .s file or to memory.
90FunctionPass *llvm::createMachineCodeDeleter() {
91  return new Deleter();
92}
93
94
95
96//===---------------------------------------------------------------------===//
97// MachineFunction implementation
98//===---------------------------------------------------------------------===//
99
100MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
101  MachineBasicBlock* dummy = new MachineBasicBlock();
102  LeakDetector::removeGarbageObject(dummy);
103  return dummy;
104}
105
106void ilist_traits<MachineBasicBlock>::transferNodesFromList(
107  iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
108  ilist_iterator<MachineBasicBlock> first,
109  ilist_iterator<MachineBasicBlock> last) {
110  if (Parent != toList.Parent)
111    for (; first != last; ++first)
112      first->Parent = toList.Parent;
113}
114
115MachineFunction::MachineFunction(const Function *F,
116                                 const TargetMachine &TM)
117  : Annotation(MF_AID), Fn(F), Target(TM), UsedPhysRegs(0) {
118  SSARegMapping = new SSARegMap();
119  MFInfo = 0;
120  FrameInfo = new MachineFrameInfo();
121  ConstantPool = new MachineConstantPool(TM.getTargetData());
122  JumpTableInfo = new MachineJumpTableInfo(TM.getTargetData());
123  BasicBlocks.Parent = this;
124}
125
126MachineFunction::~MachineFunction() {
127  BasicBlocks.clear();
128  delete SSARegMapping;
129  delete MFInfo;
130  delete FrameInfo;
131  delete ConstantPool;
132  delete JumpTableInfo;
133  delete[] UsedPhysRegs;
134}
135
136
137/// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
138/// recomputes them.  This guarantees that the MBB numbers are sequential,
139/// dense, and match the ordering of the blocks within the function.  If a
140/// specific MachineBasicBlock is specified, only that block and those after
141/// it are renumbered.
142void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
143  if (empty()) { MBBNumbering.clear(); return; }
144  MachineFunction::iterator MBBI, E = end();
145  if (MBB == 0)
146    MBBI = begin();
147  else
148    MBBI = MBB;
149
150  // Figure out the block number this should have.
151  unsigned BlockNo = 0;
152  if (MBBI != begin())
153    BlockNo = prior(MBBI)->getNumber()+1;
154
155  for (; MBBI != E; ++MBBI, ++BlockNo) {
156    if (MBBI->getNumber() != (int)BlockNo) {
157      // Remove use of the old number.
158      if (MBBI->getNumber() != -1) {
159        assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
160               "MBB number mismatch!");
161        MBBNumbering[MBBI->getNumber()] = 0;
162      }
163
164      // If BlockNo is already taken, set that block's number to -1.
165      if (MBBNumbering[BlockNo])
166        MBBNumbering[BlockNo]->setNumber(-1);
167
168      MBBNumbering[BlockNo] = MBBI;
169      MBBI->setNumber(BlockNo);
170    }
171  }
172
173  // Okay, all the blocks are renumbered.  If we have compactified the block
174  // numbering, shrink MBBNumbering now.
175  assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
176  MBBNumbering.resize(BlockNo);
177}
178
179
180void MachineFunction::dump() const { print(std::cerr); }
181
182void MachineFunction::print(std::ostream &OS) const {
183  OS << "# Machine code for " << Fn->getName () << "():\n";
184
185  // Print Frame Information
186  getFrameInfo()->print(*this, OS);
187
188  // Print JumpTable Information
189  getJumpTableInfo()->print(OS);
190
191  // Print Constant Pool
192  getConstantPool()->print(OS);
193
194  const MRegisterInfo *MRI = getTarget().getRegisterInfo();
195
196  if (livein_begin() != livein_end()) {
197    OS << "Live Ins:";
198    for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
199      if (MRI)
200        OS << " " << MRI->getName(I->first);
201      else
202        OS << " Reg #" << I->first;
203
204      if (I->second)
205        OS << " in VR#" << I->second << " ";
206    }
207    OS << "\n";
208  }
209  if (liveout_begin() != liveout_end()) {
210    OS << "Live Outs:";
211    for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
212      if (MRI)
213        OS << " " << MRI->getName(*I);
214      else
215        OS << " Reg #" << *I;
216    OS << "\n";
217  }
218
219  for (const_iterator BB = begin(); BB != end(); ++BB)
220    BB->print(OS);
221
222  OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
223}
224
225/// CFGOnly flag - This is used to control whether or not the CFG graph printer
226/// prints out the contents of basic blocks or not.  This is acceptable because
227/// this code is only really used for debugging purposes.
228///
229static bool CFGOnly = false;
230
231namespace llvm {
232  template<>
233  struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
234    static std::string getGraphName(const MachineFunction *F) {
235      return "CFG for '" + F->getFunction()->getName() + "' function";
236    }
237
238    static std::string getNodeLabel(const MachineBasicBlock *Node,
239                                    const MachineFunction *Graph) {
240      if (CFGOnly && Node->getBasicBlock() &&
241          !Node->getBasicBlock()->getName().empty())
242        return Node->getBasicBlock()->getName() + ":";
243
244      std::ostringstream Out;
245      if (CFGOnly) {
246        Out << Node->getNumber() << ':';
247        return Out.str();
248      }
249
250      Node->print(Out);
251
252      std::string OutStr = Out.str();
253      if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
254
255      // Process string output to make it nicer...
256      for (unsigned i = 0; i != OutStr.length(); ++i)
257        if (OutStr[i] == '\n') {                            // Left justify
258          OutStr[i] = '\\';
259          OutStr.insert(OutStr.begin()+i+1, 'l');
260        }
261      return OutStr;
262    }
263  };
264}
265
266void MachineFunction::viewCFG() const
267{
268#ifndef NDEBUG
269  ViewGraph(this, "mf" + getFunction()->getName());
270#else
271  std::cerr << "SelectionDAG::viewGraph is only available in debug builds on "
272            << "systems with Graphviz or gv!\n";
273#endif // NDEBUG
274}
275
276void MachineFunction::viewCFGOnly() const
277{
278  CFGOnly = true;
279  viewCFG();
280  CFGOnly = false;
281}
282
283// The next two methods are used to construct and to retrieve
284// the MachineCodeForFunction object for the given function.
285// construct() -- Allocates and initializes for a given function and target
286// get()       -- Returns a handle to the object.
287//                This should not be called before "construct()"
288//                for a given Function.
289//
290MachineFunction&
291MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
292{
293  assert(Fn->getAnnotation(MF_AID) == 0 &&
294         "Object already exists for this function!");
295  MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
296  Fn->addAnnotation(mcInfo);
297  return *mcInfo;
298}
299
300void MachineFunction::destruct(const Function *Fn) {
301  bool Deleted = Fn->deleteAnnotation(MF_AID);
302  assert(Deleted && "Machine code did not exist for function!");
303}
304
305MachineFunction& MachineFunction::get(const Function *F)
306{
307  MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
308  assert(mc && "Call construct() method first to allocate the object");
309  return *mc;
310}
311
312void MachineFunction::clearSSARegMap() {
313  delete SSARegMapping;
314  SSARegMapping = 0;
315}
316
317//===----------------------------------------------------------------------===//
318//  MachineFrameInfo implementation
319//===----------------------------------------------------------------------===//
320
321void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
322  int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
323
324  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
325    const StackObject &SO = Objects[i];
326    OS << "  <fi #" << (int)(i-NumFixedObjects) << ">: ";
327    if (SO.Size == 0)
328      OS << "variable sized";
329    else
330      OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
331    OS << " alignment is " << SO.Alignment << " byte"
332       << (SO.Alignment != 1 ? "s," : ",");
333
334    if (i < NumFixedObjects)
335      OS << " fixed";
336    if (i < NumFixedObjects || SO.SPOffset != -1) {
337      int Off = SO.SPOffset - ValOffset;
338      OS << " at location [SP";
339      if (Off > 0)
340        OS << "+" << Off;
341      else if (Off < 0)
342        OS << Off;
343      OS << "]";
344    }
345    OS << "\n";
346  }
347
348  if (HasVarSizedObjects)
349    OS << "  Stack frame contains variable sized objects\n";
350}
351
352void MachineFrameInfo::dump(const MachineFunction &MF) const {
353  print(MF, std::cerr);
354}
355
356
357//===----------------------------------------------------------------------===//
358//  MachineJumpTableInfo implementation
359//===----------------------------------------------------------------------===//
360
361/// getJumpTableIndex - Create a new jump table entry in the jump table info
362/// or return an existing one.
363///
364unsigned MachineJumpTableInfo::getJumpTableIndex(
365                               const std::vector<MachineBasicBlock*> &DestBBs) {
366  assert(!DestBBs.empty() && "Cannot create an empty jump table!");
367  for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
368    if (JumpTables[i].MBBs == DestBBs)
369      return i;
370
371  JumpTables.push_back(MachineJumpTableEntry(DestBBs));
372  return JumpTables.size()-1;
373}
374
375
376void MachineJumpTableInfo::print(std::ostream &OS) const {
377  // FIXME: this is lame, maybe we could print out the MBB numbers or something
378  // like {1, 2, 4, 5, 3, 0}
379  for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
380    OS << "  <jt #" << i << "> has " << JumpTables[i].MBBs.size()
381       << " entries\n";
382  }
383}
384
385unsigned MachineJumpTableInfo::getEntrySize() const {
386  return TD->getPointerSize();
387}
388
389unsigned MachineJumpTableInfo::getAlignment() const {
390  return TD->getPointerAlignment();
391}
392
393void MachineJumpTableInfo::dump() const { print(std::cerr); }
394
395
396//===----------------------------------------------------------------------===//
397//  MachineConstantPool implementation
398//===----------------------------------------------------------------------===//
399
400const Type *MachineConstantPoolEntry::getType() const {
401  if (isMachineConstantPoolEntry())
402      return Val.MachineCPVal->getType();
403  return Val.ConstVal->getType();
404}
405
406MachineConstantPool::~MachineConstantPool() {
407  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
408    if (Constants[i].isMachineConstantPoolEntry())
409      delete Constants[i].Val.MachineCPVal;
410}
411
412/// getConstantPoolIndex - Create a new entry in the constant pool or return
413/// an existing one.  User must specify an alignment in bytes for the object.
414///
415unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
416                                                   unsigned Alignment) {
417  assert(Alignment && "Alignment must be specified!");
418  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
419
420  // Check to see if we already have this constant.
421  //
422  // FIXME, this could be made much more efficient for large constant pools.
423  unsigned AlignMask = (1 << Alignment)-1;
424  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
425    if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
426      return i;
427
428  unsigned Offset = 0;
429  if (!Constants.empty()) {
430    Offset = Constants.back().getOffset();
431    Offset += TD->getTypeSize(Constants.back().getType());
432    Offset = (Offset+AlignMask)&~AlignMask;
433  }
434
435  Constants.push_back(MachineConstantPoolEntry(C, Offset));
436  return Constants.size()-1;
437}
438
439unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
440                                                   unsigned Alignment) {
441  assert(Alignment && "Alignment must be specified!");
442  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
443
444  // Check to see if we already have this constant.
445  //
446  // FIXME, this could be made much more efficient for large constant pools.
447  unsigned AlignMask = (1 << Alignment)-1;
448  int Idx = V->getExistingMachineCPValue(this, Alignment);
449  if (Idx != -1)
450    return (unsigned)Idx;
451
452  unsigned Offset = 0;
453  if (!Constants.empty()) {
454    Offset = Constants.back().getOffset();
455    Offset += TD->getTypeSize(Constants.back().getType());
456    Offset = (Offset+AlignMask)&~AlignMask;
457  }
458
459  Constants.push_back(MachineConstantPoolEntry(V, Offset));
460  return Constants.size()-1;
461}
462
463
464void MachineConstantPool::print(std::ostream &OS) const {
465  for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
466    OS << "  <cp #" << i << "> is";
467    if (Constants[i].isMachineConstantPoolEntry())
468      Constants[i].Val.MachineCPVal->print(OS);
469    else
470      OS << *(Value*)Constants[i].Val.ConstVal;
471    OS << " , offset=" << Constants[i].Offset;
472    OS << "\n";
473  }
474}
475
476void MachineConstantPool::dump() const { print(std::cerr); }
477