Fix casting so there's no warning on Alpha.
[oota-llvm.git] / lib / CodeGen / MachineFunction.cpp
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/LeakDetector.h"
29 #include "llvm/Support/GraphWriter.h"
30 #include "llvm/Config/config.h"
31 #include <fstream>
32 #include <iostream>
33 #include <sstream>
34
35 using namespace llvm;
36
37 static AnnotationID MF_AID(
38   AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
39
40
41 namespace {
42   struct Printer : public MachineFunctionPass {
43     std::ostream *OS;
44     const std::string Banner;
45
46     Printer (std::ostream *_OS, const std::string &_Banner) :
47       OS (_OS), Banner (_Banner) { }
48
49     const char *getPassName() const { return "MachineFunction Printer"; }
50
51     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
52       AU.setPreservesAll();
53     }
54
55     bool runOnMachineFunction(MachineFunction &MF) {
56       (*OS) << Banner;
57       MF.print (*OS);
58       return false;
59     }
60   };
61 }
62
63 /// Returns a newly-created MachineFunction Printer pass. The default output
64 /// stream is std::cerr; the default banner is empty.
65 ///
66 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
67                                                      const std::string &Banner){
68   return new Printer(OS, Banner);
69 }
70
71 namespace {
72   struct Deleter : public MachineFunctionPass {
73     const char *getPassName() const { return "Machine Code Deleter"; }
74
75     bool runOnMachineFunction(MachineFunction &MF) {
76       // Delete the annotation from the function now.
77       MachineFunction::destruct(MF.getFunction());
78       return true;
79     }
80   };
81 }
82
83 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
84 /// the current function, which should happen after the function has been
85 /// emitted to a .s file or to memory.
86 FunctionPass *llvm::createMachineCodeDeleter() {
87   return new Deleter();
88 }
89
90
91
92 //===---------------------------------------------------------------------===//
93 // MachineFunction implementation
94 //===---------------------------------------------------------------------===//
95
96 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
97   MachineBasicBlock* dummy = new MachineBasicBlock();
98   LeakDetector::removeGarbageObject(dummy);
99   return dummy;
100 }
101
102 void ilist_traits<MachineBasicBlock>::transferNodesFromList(
103   iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
104   ilist_iterator<MachineBasicBlock> first,
105   ilist_iterator<MachineBasicBlock> last) {
106   if (Parent != toList.Parent)
107     for (; first != last; ++first)
108       first->Parent = toList.Parent;
109 }
110
111 MachineFunction::MachineFunction(const Function *F,
112                                  const TargetMachine &TM)
113   : Annotation(MF_AID), Fn(F), Target(TM), UsedPhysRegs(0) {
114   SSARegMapping = new SSARegMap();
115   MFInfo = 0;
116   FrameInfo = new MachineFrameInfo();
117   ConstantPool = new MachineConstantPool(TM.getTargetData());
118   JumpTableInfo = new MachineJumpTableInfo(TM.getTargetData());
119   BasicBlocks.Parent = this;
120 }
121
122 MachineFunction::~MachineFunction() {
123   BasicBlocks.clear();
124   delete SSARegMapping;
125   delete MFInfo;
126   delete FrameInfo;
127   delete ConstantPool;
128   delete JumpTableInfo;
129   delete[] UsedPhysRegs;
130 }
131
132 void MachineFunction::dump() const { print(std::cerr); }
133
134 void MachineFunction::print(std::ostream &OS) const {
135   OS << "# Machine code for " << Fn->getName () << "():\n";
136
137   // Print Frame Information
138   getFrameInfo()->print(*this, OS);
139   
140   // Print JumpTable Information
141   getJumpTableInfo()->print(OS);
142
143   // Print Constant Pool
144   getConstantPool()->print(OS);
145   
146   const MRegisterInfo *MRI = getTarget().getRegisterInfo();
147   
148   if (livein_begin() != livein_end()) {
149     OS << "Live Ins:";
150     for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
151       if (MRI)
152         OS << " " << MRI->getName(I->first);
153       else
154         OS << " Reg #" << I->first;
155       
156       if (I->second)
157         OS << " in VR#" << I->second << " ";
158     }
159     OS << "\n";
160   }
161   if (liveout_begin() != liveout_end()) {
162     OS << "Live Outs:";
163     for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
164       if (MRI)
165         OS << " " << MRI->getName(*I);
166       else
167         OS << " Reg #" << *I;
168     OS << "\n";
169   }
170   
171   for (const_iterator BB = begin(); BB != end(); ++BB)
172     BB->print(OS);
173
174   OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
175 }
176
177 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
178 /// prints out the contents of basic blocks or not.  This is acceptable because
179 /// this code is only really used for debugging purposes.
180 ///
181 static bool CFGOnly = false;
182
183 namespace llvm {
184   template<>
185   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
186     static std::string getGraphName(const MachineFunction *F) {
187       return "CFG for '" + F->getFunction()->getName() + "' function";
188     }
189
190     static std::string getNodeLabel(const MachineBasicBlock *Node,
191                                     const MachineFunction *Graph) {
192       if (CFGOnly && Node->getBasicBlock() &&
193           !Node->getBasicBlock()->getName().empty())
194         return Node->getBasicBlock()->getName() + ":";
195
196       std::ostringstream Out;
197       if (CFGOnly) {
198         Out << Node->getNumber() << ':';
199         return Out.str();
200       }
201
202       Node->print(Out);
203
204       std::string OutStr = Out.str();
205       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
206
207       // Process string output to make it nicer...
208       for (unsigned i = 0; i != OutStr.length(); ++i)
209         if (OutStr[i] == '\n') {                            // Left justify
210           OutStr[i] = '\\';
211           OutStr.insert(OutStr.begin()+i+1, 'l');
212         }
213       return OutStr;
214     }
215   };
216 }
217
218 void MachineFunction::viewCFG() const
219 {
220 #ifndef NDEBUG
221   std::string Filename = "/tmp/cfg." + getFunction()->getName() + ".dot";
222   std::cerr << "Writing '" << Filename << "'... ";
223   std::ofstream F(Filename.c_str());
224
225   if (!F) {
226     std::cerr << "  error opening file for writing!\n";
227     return;
228   }
229
230   WriteGraph(F, this);
231   F.close();
232   std::cerr << "\n";
233
234 #ifdef HAVE_GRAPHVIZ
235   std::cerr << "Running 'Graphviz' program... " << std::flush;
236   if (system((LLVM_PATH_GRAPHVIZ " " + Filename).c_str())) {
237     std::cerr << "Error viewing graph: 'Graphviz' not in path?\n";
238   } else {
239     system(("rm " + Filename).c_str());
240     return;
241   }
242 #endif  // HAVE_GRAPHVIZ
243
244 #ifdef HAVE_GV
245   std::cerr << "Running 'dot' program... " << std::flush;
246   if (system(("dot -Tps -Nfontname=Courier -Gsize=7.5,10 " + Filename
247               + " > /tmp/cfg.tempgraph.ps").c_str())) {
248     std::cerr << "Error running dot: 'dot' not in path?\n";
249   } else {
250     std::cerr << "\n";
251     system("gv /tmp/cfg.tempgraph.ps");
252   }
253   system(("rm " + Filename + " /tmp/cfg.tempgraph.ps").c_str());
254   return;
255 #endif  // HAVE_GV
256 #endif  // NDEBUG
257   std::cerr << "MachineFunction::viewCFG is only available in debug builds on "
258             << "systems with Graphviz or gv!\n";
259
260 #ifndef NDEBUG
261   system(("rm " + Filename).c_str());
262 #endif
263 }
264
265 void MachineFunction::viewCFGOnly() const
266 {
267   CFGOnly = true;
268   viewCFG();
269   CFGOnly = false;
270 }
271
272 // The next two methods are used to construct and to retrieve
273 // the MachineCodeForFunction object for the given function.
274 // construct() -- Allocates and initializes for a given function and target
275 // get()       -- Returns a handle to the object.
276 //                This should not be called before "construct()"
277 //                for a given Function.
278 //
279 MachineFunction&
280 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
281 {
282   assert(Fn->getAnnotation(MF_AID) == 0 &&
283          "Object already exists for this function!");
284   MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
285   Fn->addAnnotation(mcInfo);
286   return *mcInfo;
287 }
288
289 void MachineFunction::destruct(const Function *Fn) {
290   bool Deleted = Fn->deleteAnnotation(MF_AID);
291   assert(Deleted && "Machine code did not exist for function!");
292 }
293
294 MachineFunction& MachineFunction::get(const Function *F)
295 {
296   MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
297   assert(mc && "Call construct() method first to allocate the object");
298   return *mc;
299 }
300
301 void MachineFunction::clearSSARegMap() {
302   delete SSARegMapping;
303   SSARegMapping = 0;
304 }
305
306 //===----------------------------------------------------------------------===//
307 //  MachineFrameInfo implementation
308 //===----------------------------------------------------------------------===//
309
310 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
311   int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
312
313   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
314     const StackObject &SO = Objects[i];
315     OS << "  <fi #" << (int)(i-NumFixedObjects) << ">: ";
316     if (SO.Size == 0)
317       OS << "variable sized";
318     else
319       OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
320     OS << " alignment is " << SO.Alignment << " byte"
321        << (SO.Alignment != 1 ? "s," : ",");
322
323     if (i < NumFixedObjects)
324       OS << " fixed";
325     if (i < NumFixedObjects || SO.SPOffset != -1) {
326       int Off = SO.SPOffset - ValOffset;
327       OS << " at location [SP";
328       if (Off > 0)
329         OS << "+" << Off;
330       else if (Off < 0)
331         OS << Off;
332       OS << "]";
333     }
334     OS << "\n";
335   }
336
337   if (HasVarSizedObjects)
338     OS << "  Stack frame contains variable sized objects\n";
339 }
340
341 void MachineFrameInfo::dump(const MachineFunction &MF) const {
342   print(MF, std::cerr);
343 }
344
345
346 //===----------------------------------------------------------------------===//
347 //  MachineJumpTableInfo implementation
348 //===----------------------------------------------------------------------===//
349
350 /// getJumpTableIndex - Create a new jump table entry in the jump table info
351 /// or return an existing one.
352 ///
353 unsigned MachineJumpTableInfo::getJumpTableIndex(
354                                      std::vector<MachineBasicBlock*> &DestBBs) {
355   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
356     if (JumpTables[i].MBBs == DestBBs)
357       return i;
358   
359   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
360   return JumpTables.size()-1;
361 }
362
363
364 void MachineJumpTableInfo::print(std::ostream &OS) const {
365   // FIXME: this is lame, maybe we could print out the MBB numbers or something
366   // like {1, 2, 4, 5, 3, 0}
367   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
368     OS << "  <jt #" << i << "> has " << JumpTables[i].MBBs.size() 
369        << " entries\n";
370   }
371 }
372
373 unsigned MachineJumpTableInfo::getEntrySize() const { 
374   return TD->getPointerSize(); 
375 }
376
377 unsigned MachineJumpTableInfo::getAlignment() const { 
378   return TD->getPointerAlignment(); 
379 }
380
381 void MachineJumpTableInfo::dump() const { print(std::cerr); }
382
383
384 //===----------------------------------------------------------------------===//
385 //  MachineConstantPool implementation
386 //===----------------------------------------------------------------------===//
387
388 /// getConstantPoolIndex - Create a new entry in the constant pool or return
389 /// an existing one.  User must specify an alignment in bytes for the object.
390 ///
391 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C, 
392                                                    unsigned Alignment) {
393   assert(Alignment && "Alignment must be specified!");
394   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
395   
396   // Check to see if we already have this constant.
397   //
398   // FIXME, this could be made much more efficient for large constant pools.
399   unsigned AlignMask = (1 << Alignment)-1;
400   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
401     if (Constants[i].Val == C && (Constants[i].Offset & AlignMask) == 0)
402       return i;
403   
404   unsigned Offset = 0;
405   if (!Constants.empty()) {
406     Offset = Constants.back().Offset;
407     Offset += TD->getTypeSize(Constants.back().Val->getType());
408     Offset = (Offset+AlignMask)&~AlignMask;
409   }
410   
411   Constants.push_back(MachineConstantPoolEntry(C, Offset));
412   return Constants.size()-1;
413 }
414
415
416 void MachineConstantPool::print(std::ostream &OS) const {
417   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
418     OS << "  <cp #" << i << "> is" << *(Value*)Constants[i].Val;
419     OS << " , offset=" << Constants[i].Offset;
420     OS << "\n";
421   }
422 }
423
424 void MachineConstantPool::dump() const { print(std::cerr); }