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