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