fix an infinite loop compiling ldecod, notice by JeffC.
[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/DerivedTypes.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/SSARegMap.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetFrameInfo.h"
28 #include "llvm/Function.h"
29 #include "llvm/Instructions.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/GraphWriter.h"
32 #include "llvm/Support/LeakDetector.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Config/config.h"
35 #include <fstream>
36 #include <sstream>
37 using namespace llvm;
38
39 static AnnotationID MF_AID(
40   AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
41
42 // Out of line virtual function to home classes.
43 void MachineFunctionPass::virtfn() {}
44
45 namespace {
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 ///
70 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
71                                                      const std::string &Banner){
72   return new Printer(OS, Banner);
73 }
74
75 namespace {
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.
90 FunctionPass *llvm::createMachineCodeDeleter() {
91   return new Deleter();
92 }
93
94
95
96 //===---------------------------------------------------------------------===//
97 // MachineFunction implementation
98 //===---------------------------------------------------------------------===//
99
100 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
101   MachineBasicBlock* dummy = new MachineBasicBlock();
102   LeakDetector::removeGarbageObject(dummy);
103   return dummy;
104 }
105
106 void 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
115 MachineFunction::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   
123   // Set up jump table.
124   const TargetData &TD = *TM.getTargetData();
125   bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
126   unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
127   unsigned Alignment = IsPic ? TD.getABITypeAlignment(Type::Int32Ty)
128                              : TD.getPointerABIAlignment();
129   JumpTableInfo = new MachineJumpTableInfo(EntrySize, Alignment);
130   
131   BasicBlocks.Parent = this;
132 }
133
134 MachineFunction::~MachineFunction() {
135   BasicBlocks.clear();
136   delete SSARegMapping;
137   delete MFInfo;
138   delete FrameInfo;
139   delete ConstantPool;
140   delete JumpTableInfo;
141   delete[] UsedPhysRegs;
142 }
143
144
145 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
146 /// recomputes them.  This guarantees that the MBB numbers are sequential,
147 /// dense, and match the ordering of the blocks within the function.  If a
148 /// specific MachineBasicBlock is specified, only that block and those after
149 /// it are renumbered.
150 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
151   if (empty()) { MBBNumbering.clear(); return; }
152   MachineFunction::iterator MBBI, E = end();
153   if (MBB == 0)
154     MBBI = begin();
155   else
156     MBBI = MBB;
157   
158   // Figure out the block number this should have.
159   unsigned BlockNo = 0;
160   if (MBBI != begin())
161     BlockNo = prior(MBBI)->getNumber()+1;
162   
163   for (; MBBI != E; ++MBBI, ++BlockNo) {
164     if (MBBI->getNumber() != (int)BlockNo) {
165       // Remove use of the old number.
166       if (MBBI->getNumber() != -1) {
167         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
168                "MBB number mismatch!");
169         MBBNumbering[MBBI->getNumber()] = 0;
170       }
171       
172       // If BlockNo is already taken, set that block's number to -1.
173       if (MBBNumbering[BlockNo])
174         MBBNumbering[BlockNo]->setNumber(-1);
175
176       MBBNumbering[BlockNo] = MBBI;
177       MBBI->setNumber(BlockNo);
178     }
179   }    
180
181   // Okay, all the blocks are renumbered.  If we have compactified the block
182   // numbering, shrink MBBNumbering now.
183   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
184   MBBNumbering.resize(BlockNo);
185 }
186
187
188 void MachineFunction::dump() const { print(*cerr.stream()); }
189
190 void MachineFunction::print(std::ostream &OS) const {
191   OS << "# Machine code for " << Fn->getName () << "():\n";
192
193   // Print Frame Information
194   getFrameInfo()->print(*this, OS);
195   
196   // Print JumpTable Information
197   getJumpTableInfo()->print(OS);
198
199   // Print Constant Pool
200   getConstantPool()->print(OS);
201   
202   const MRegisterInfo *MRI = getTarget().getRegisterInfo();
203   
204   if (livein_begin() != livein_end()) {
205     OS << "Live Ins:";
206     for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
207       if (MRI)
208         OS << " " << MRI->getName(I->first);
209       else
210         OS << " Reg #" << I->first;
211       
212       if (I->second)
213         OS << " in VR#" << I->second << " ";
214     }
215     OS << "\n";
216   }
217   if (liveout_begin() != liveout_end()) {
218     OS << "Live Outs:";
219     for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
220       if (MRI)
221         OS << " " << MRI->getName(*I);
222       else
223         OS << " Reg #" << *I;
224     OS << "\n";
225   }
226   
227   for (const_iterator BB = begin(); BB != end(); ++BB)
228     BB->print(OS);
229
230   OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
231 }
232
233 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
234 /// prints out the contents of basic blocks or not.  This is acceptable because
235 /// this code is only really used for debugging purposes.
236 ///
237 static bool CFGOnly = false;
238
239 namespace llvm {
240   template<>
241   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
242     static std::string getGraphName(const MachineFunction *F) {
243       return "CFG for '" + F->getFunction()->getName() + "' function";
244     }
245
246     static std::string getNodeLabel(const MachineBasicBlock *Node,
247                                     const MachineFunction *Graph) {
248       if (CFGOnly && Node->getBasicBlock() &&
249           !Node->getBasicBlock()->getName().empty())
250         return Node->getBasicBlock()->getName() + ":";
251
252       std::ostringstream Out;
253       if (CFGOnly) {
254         Out << Node->getNumber() << ':';
255         return Out.str();
256       }
257
258       Node->print(Out);
259
260       std::string OutStr = Out.str();
261       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
262
263       // Process string output to make it nicer...
264       for (unsigned i = 0; i != OutStr.length(); ++i)
265         if (OutStr[i] == '\n') {                            // Left justify
266           OutStr[i] = '\\';
267           OutStr.insert(OutStr.begin()+i+1, 'l');
268         }
269       return OutStr;
270     }
271   };
272 }
273
274 void MachineFunction::viewCFG() const
275 {
276 #ifndef NDEBUG
277   ViewGraph(this, "mf" + getFunction()->getName());
278 #else
279   cerr << "SelectionDAG::viewGraph is only available in debug builds on "
280        << "systems with Graphviz or gv!\n";
281 #endif // NDEBUG
282 }
283
284 void MachineFunction::viewCFGOnly() const
285 {
286   CFGOnly = true;
287   viewCFG();
288   CFGOnly = false;
289 }
290
291 // The next two methods are used to construct and to retrieve
292 // the MachineCodeForFunction object for the given function.
293 // construct() -- Allocates and initializes for a given function and target
294 // get()       -- Returns a handle to the object.
295 //                This should not be called before "construct()"
296 //                for a given Function.
297 //
298 MachineFunction&
299 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
300 {
301   assert(Fn->getAnnotation(MF_AID) == 0 &&
302          "Object already exists for this function!");
303   MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
304   Fn->addAnnotation(mcInfo);
305   return *mcInfo;
306 }
307
308 void MachineFunction::destruct(const Function *Fn) {
309   bool Deleted = Fn->deleteAnnotation(MF_AID);
310   assert(Deleted && "Machine code did not exist for function!");
311 }
312
313 MachineFunction& MachineFunction::get(const Function *F)
314 {
315   MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
316   assert(mc && "Call construct() method first to allocate the object");
317   return *mc;
318 }
319
320 void MachineFunction::clearSSARegMap() {
321   delete SSARegMapping;
322   SSARegMapping = 0;
323 }
324
325 //===----------------------------------------------------------------------===//
326 //  MachineFrameInfo implementation
327 //===----------------------------------------------------------------------===//
328
329 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
330   int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
331
332   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
333     const StackObject &SO = Objects[i];
334     OS << "  <fi #" << (int)(i-NumFixedObjects) << ">: ";
335     if (SO.Size == 0)
336       OS << "variable sized";
337     else
338       OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
339     OS << " alignment is " << SO.Alignment << " byte"
340        << (SO.Alignment != 1 ? "s," : ",");
341
342     if (i < NumFixedObjects)
343       OS << " fixed";
344     if (i < NumFixedObjects || SO.SPOffset != -1) {
345       int Off = SO.SPOffset - ValOffset;
346       OS << " at location [SP";
347       if (Off > 0)
348         OS << "+" << Off;
349       else if (Off < 0)
350         OS << Off;
351       OS << "]";
352     }
353     OS << "\n";
354   }
355
356   if (HasVarSizedObjects)
357     OS << "  Stack frame contains variable sized objects\n";
358 }
359
360 void MachineFrameInfo::dump(const MachineFunction &MF) const {
361   print(MF, *cerr.stream());
362 }
363
364
365 //===----------------------------------------------------------------------===//
366 //  MachineJumpTableInfo implementation
367 //===----------------------------------------------------------------------===//
368
369 /// getJumpTableIndex - Create a new jump table entry in the jump table info
370 /// or return an existing one.
371 ///
372 unsigned MachineJumpTableInfo::getJumpTableIndex(
373                                const std::vector<MachineBasicBlock*> &DestBBs) {
374   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
375   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
376     if (JumpTables[i].MBBs == DestBBs)
377       return i;
378   
379   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
380   return JumpTables.size()-1;
381 }
382
383
384 void MachineJumpTableInfo::print(std::ostream &OS) const {
385   // FIXME: this is lame, maybe we could print out the MBB numbers or something
386   // like {1, 2, 4, 5, 3, 0}
387   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
388     OS << "  <jt #" << i << "> has " << JumpTables[i].MBBs.size() 
389        << " entries\n";
390   }
391 }
392
393 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
394
395
396 //===----------------------------------------------------------------------===//
397 //  MachineConstantPool implementation
398 //===----------------------------------------------------------------------===//
399
400 const Type *MachineConstantPoolEntry::getType() const {
401   if (isMachineConstantPoolEntry())
402       return Val.MachineCPVal->getType();
403   return Val.ConstVal->getType();
404 }
405
406 MachineConstantPool::~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 ///
415 unsigned 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
439 unsigned 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
464 void 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].getOffset();
472     OS << "\n";
473   }
474 }
475
476 void MachineConstantPool::dump() const { print(*cerr.stream()); }