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/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/ADT/STLExtras.h"
32 #include "llvm/Config/config.h"
33 #include <fstream>
34 #include <sstream>
35 using namespace llvm;
36 
37 static AnnotationID MF_AID(
38   AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
39 
40 // Out of line virtual function to home classes.
41 void MachineFunctionPass::virtfn() {}
42 
43 namespace {
44   struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
45     static char ID;
46 
47     std::ostream *OS;
48     const std::string Banner;
49 
50     Printer (std::ostream *os, const std::string &banner)
51       : MachineFunctionPass((intptr_t)&ID), 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   char Printer::ID = 0;
66 }
67 
68 /// Returns a newly-created MachineFunction Printer pass. The default output
69 /// stream is std::cerr; the default banner is empty.
70 ///
71 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
72                                                      const std::string &Banner){
73   return new Printer(OS, Banner);
74 }
75 
76 namespace {
77   struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
78     static char ID;
79     Deleter() : MachineFunctionPass((intptr_t)&ID) {}
80 
81     const char *getPassName() const { return "Machine Code Deleter"; }
82 
83     bool runOnMachineFunction(MachineFunction &MF) {
84       // Delete the annotation from the function now.
85       MachineFunction::destruct(MF.getFunction());
86       return true;
87     }
88   };
89   char Deleter::ID = 0;
90 }
91 
92 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
93 /// the current function, which should happen after the function has been
94 /// emitted to a .s file or to memory.
95 FunctionPass *llvm::createMachineCodeDeleter() {
96   return new Deleter();
97 }
98 
99 
100 
101 //===---------------------------------------------------------------------===//
102 // MachineFunction implementation
103 //===---------------------------------------------------------------------===//
104 
105 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
106   MBB->getParent()->DeleteMachineBasicBlock(MBB);
107 }
108 
109 MachineFunction::MachineFunction(const Function *F,
110                                  const TargetMachine &TM)
111   : Annotation(MF_AID), Fn(F), Target(TM) {
112   RegInfo = new (Allocator.Allocate<MachineRegisterInfo>())
113                 MachineRegisterInfo(*TM.getRegisterInfo());
114   MFInfo = 0;
115   FrameInfo = new (Allocator.Allocate<MachineFrameInfo>())
116                   MachineFrameInfo(*TM.getFrameInfo());
117   ConstantPool = new (Allocator.Allocate<MachineConstantPool>())
118                      MachineConstantPool(TM.getTargetData());
119 
120   // Set up jump table.
121   const TargetData &TD = *TM.getTargetData();
122   bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
123   unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
124   unsigned Alignment = IsPic ? TD.getABITypeAlignment(Type::Int32Ty)
125                              : TD.getPointerABIAlignment();
126   JumpTableInfo = new (Allocator.Allocate<MachineJumpTableInfo>())
127                       MachineJumpTableInfo(EntrySize, Alignment);
128 }
129 
130 MachineFunction::~MachineFunction() {
131   BasicBlocks.clear();
132   InstructionRecycler.clear(Allocator);
133   BasicBlockRecycler.clear(Allocator);
134   RegInfo->~MachineRegisterInfo();        Allocator.Deallocate(RegInfo);
135   if (MFInfo) {
136     MFInfo->~MachineFunctionInfo();       Allocator.Deallocate(MFInfo);
137   }
138   FrameInfo->~MachineFrameInfo();         Allocator.Deallocate(FrameInfo);
139   ConstantPool->~MachineConstantPool();   Allocator.Deallocate(ConstantPool);
140   JumpTableInfo->~MachineJumpTableInfo(); Allocator.Deallocate(JumpTableInfo);
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 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
187 /// of `new MachineInstr'.
188 ///
189 MachineInstr *
190 MachineFunction::CreateMachineInstr(const TargetInstrDesc &TID, bool NoImp) {
191   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
192              MachineInstr(TID, NoImp);
193 }
194 
195 /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
196 /// 'Orig' instruction, identical in all ways except the the instruction
197 /// has no parent, prev, or next.
198 ///
199 MachineInstr *
200 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
201   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
202              MachineInstr(*this, *Orig);
203 }
204 
205 /// DeleteMachineInstr - Delete the given MachineInstr.
206 ///
207 void
208 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
209   // Clear the instructions memoperands. This must be done manually because
210   // the instruction's parent pointer is now null, so it can't properly
211   // deallocate them on its own.
212   MI->clearMemOperands(*this);
213 
214   MI->~MachineInstr();
215   InstructionRecycler.Deallocate(Allocator, MI);
216 }
217 
218 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
219 /// instead of `new MachineBasicBlock'.
220 ///
221 MachineBasicBlock *
222 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
223   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
224              MachineBasicBlock(*this, bb);
225 }
226 
227 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
228 ///
229 void
230 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
231   assert(MBB->getParent() == this && "MBB parent mismatch!");
232   MBB->~MachineBasicBlock();
233   BasicBlockRecycler.Deallocate(Allocator, MBB);
234 }
235 
236 void MachineFunction::dump() const {
237   print(*cerr.stream());
238 }
239 
240 void MachineFunction::print(std::ostream &OS) const {
241   OS << "# Machine code for " << Fn->getName () << "():\n";
242 
243   // Print Frame Information
244   FrameInfo->print(*this, OS);
245 
246   // Print JumpTable Information
247   JumpTableInfo->print(OS);
248 
249   // Print Constant Pool
250   ConstantPool->print(OS);
251 
252   const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
253 
254   if (!RegInfo->livein_empty()) {
255     OS << "Live Ins:";
256     for (MachineRegisterInfo::livein_iterator
257          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
258       if (TRI)
259         OS << " " << TRI->getName(I->first);
260       else
261         OS << " Reg #" << I->first;
262 
263       if (I->second)
264         OS << " in VR#" << I->second << " ";
265     }
266     OS << "\n";
267   }
268   if (!RegInfo->liveout_empty()) {
269     OS << "Live Outs:";
270     for (MachineRegisterInfo::liveout_iterator
271          I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I)
272       if (TRI)
273         OS << " " << TRI->getName(*I);
274       else
275         OS << " Reg #" << *I;
276     OS << "\n";
277   }
278 
279   for (const_iterator BB = begin(); BB != end(); ++BB)
280     BB->print(OS);
281 
282   OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
283 }
284 
285 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
286 /// prints out the contents of basic blocks or not.  This is acceptable because
287 /// this code is only really used for debugging purposes.
288 ///
289 static bool CFGOnly = false;
290 
291 namespace llvm {
292   template<>
293   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
294     static std::string getGraphName(const MachineFunction *F) {
295       return "CFG for '" + F->getFunction()->getName() + "' function";
296     }
297 
298     static std::string getNodeLabel(const MachineBasicBlock *Node,
299                                     const MachineFunction *Graph) {
300       if (CFGOnly && Node->getBasicBlock() &&
301           !Node->getBasicBlock()->getName().empty())
302         return Node->getBasicBlock()->getName() + ":";
303 
304       std::ostringstream Out;
305       if (CFGOnly) {
306         Out << Node->getNumber() << ':';
307         return Out.str();
308       }
309 
310       Node->print(Out);
311 
312       std::string OutStr = Out.str();
313       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
314 
315       // Process string output to make it nicer...
316       for (unsigned i = 0; i != OutStr.length(); ++i)
317         if (OutStr[i] == '\n') {                            // Left justify
318           OutStr[i] = '\\';
319           OutStr.insert(OutStr.begin()+i+1, 'l');
320         }
321       return OutStr;
322     }
323   };
324 }
325 
326 void MachineFunction::viewCFG() const
327 {
328 #ifndef NDEBUG
329   ViewGraph(this, "mf" + getFunction()->getName());
330 #else
331   cerr << "SelectionDAG::viewGraph is only available in debug builds on "
332        << "systems with Graphviz or gv!\n";
333 #endif // NDEBUG
334 }
335 
336 void MachineFunction::viewCFGOnly() const
337 {
338   CFGOnly = true;
339   viewCFG();
340   CFGOnly = false;
341 }
342 
343 // The next two methods are used to construct and to retrieve
344 // the MachineCodeForFunction object for the given function.
345 // construct() -- Allocates and initializes for a given function and target
346 // get()       -- Returns a handle to the object.
347 //                This should not be called before "construct()"
348 //                for a given Function.
349 //
350 MachineFunction&
351 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
352 {
353   assert(Fn->getAnnotation(MF_AID) == 0 &&
354          "Object already exists for this function!");
355   MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
356   Fn->addAnnotation(mcInfo);
357   return *mcInfo;
358 }
359 
360 void MachineFunction::destruct(const Function *Fn) {
361   bool Deleted = Fn->deleteAnnotation(MF_AID);
362   assert(Deleted && "Machine code did not exist for function!");
363   Deleted = Deleted; // silence warning when no assertions.
364 }
365 
366 MachineFunction& MachineFunction::get(const Function *F)
367 {
368   MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
369   assert(mc && "Call construct() method first to allocate the object");
370   return *mc;
371 }
372 
373 //===----------------------------------------------------------------------===//
374 //  MachineFrameInfo implementation
375 //===----------------------------------------------------------------------===//
376 
377 /// CreateFixedObject - Create a new object at a fixed location on the stack.
378 /// All fixed objects should be created before other objects are created for
379 /// efficiency. By default, fixed objects are immutable. This returns an
380 /// index with a negative value.
381 ///
382 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
383                                         bool Immutable) {
384   assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
385   Objects.insert(Objects.begin(), StackObject(Size, 1, SPOffset, Immutable));
386   return -++NumFixedObjects;
387 }
388 
389 
390 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
391   int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
392 
393   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
394     const StackObject &SO = Objects[i];
395     OS << "  <fi #" << (int)(i-NumFixedObjects) << ">: ";
396     if (SO.Size == ~0ULL) {
397       OS << "dead\n";
398       continue;
399     }
400     if (SO.Size == 0)
401       OS << "variable sized";
402     else
403       OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
404     OS << " alignment is " << SO.Alignment << " byte"
405        << (SO.Alignment != 1 ? "s," : ",");
406 
407     if (i < NumFixedObjects)
408       OS << " fixed";
409     if (i < NumFixedObjects || SO.SPOffset != -1) {
410       int64_t Off = SO.SPOffset - ValOffset;
411       OS << " at location [SP";
412       if (Off > 0)
413         OS << "+" << Off;
414       else if (Off < 0)
415         OS << Off;
416       OS << "]";
417     }
418     OS << "\n";
419   }
420 
421   if (HasVarSizedObjects)
422     OS << "  Stack frame contains variable sized objects\n";
423 }
424 
425 void MachineFrameInfo::dump(const MachineFunction &MF) const {
426   print(MF, *cerr.stream());
427 }
428 
429 
430 //===----------------------------------------------------------------------===//
431 //  MachineJumpTableInfo implementation
432 //===----------------------------------------------------------------------===//
433 
434 /// getJumpTableIndex - Create a new jump table entry in the jump table info
435 /// or return an existing one.
436 ///
437 unsigned MachineJumpTableInfo::getJumpTableIndex(
438                                const std::vector<MachineBasicBlock*> &DestBBs) {
439   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
440   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
441     if (JumpTables[i].MBBs == DestBBs)
442       return i;
443 
444   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
445   return JumpTables.size()-1;
446 }
447 
448 
449 void MachineJumpTableInfo::print(std::ostream &OS) const {
450   // FIXME: this is lame, maybe we could print out the MBB numbers or something
451   // like {1, 2, 4, 5, 3, 0}
452   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
453     OS << "  <jt #" << i << "> has " << JumpTables[i].MBBs.size()
454        << " entries\n";
455   }
456 }
457 
458 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
459 
460 
461 //===----------------------------------------------------------------------===//
462 //  MachineConstantPool implementation
463 //===----------------------------------------------------------------------===//
464 
465 const Type *MachineConstantPoolEntry::getType() const {
466   if (isMachineConstantPoolEntry())
467       return Val.MachineCPVal->getType();
468   return Val.ConstVal->getType();
469 }
470 
471 MachineConstantPool::~MachineConstantPool() {
472   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
473     if (Constants[i].isMachineConstantPoolEntry())
474       delete Constants[i].Val.MachineCPVal;
475 }
476 
477 /// getConstantPoolIndex - Create a new entry in the constant pool or return
478 /// an existing one.  User must specify an alignment in bytes for the object.
479 ///
480 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
481                                                    unsigned Alignment) {
482   assert(Alignment && "Alignment must be specified!");
483   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
484 
485   // Check to see if we already have this constant.
486   //
487   // FIXME, this could be made much more efficient for large constant pools.
488   unsigned AlignMask = (1 << Alignment)-1;
489   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
490     if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
491       return i;
492 
493   unsigned Offset = 0;
494   if (!Constants.empty()) {
495     Offset = Constants.back().getOffset();
496     Offset += TD->getABITypeSize(Constants.back().getType());
497     Offset = (Offset+AlignMask)&~AlignMask;
498   }
499 
500   Constants.push_back(MachineConstantPoolEntry(C, Offset));
501   return Constants.size()-1;
502 }
503 
504 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
505                                                    unsigned Alignment) {
506   assert(Alignment && "Alignment must be specified!");
507   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
508 
509   // Check to see if we already have this constant.
510   //
511   // FIXME, this could be made much more efficient for large constant pools.
512   unsigned AlignMask = (1 << Alignment)-1;
513   int Idx = V->getExistingMachineCPValue(this, Alignment);
514   if (Idx != -1)
515     return (unsigned)Idx;
516 
517   unsigned Offset = 0;
518   if (!Constants.empty()) {
519     Offset = Constants.back().getOffset();
520     Offset += TD->getABITypeSize(Constants.back().getType());
521     Offset = (Offset+AlignMask)&~AlignMask;
522   }
523 
524   Constants.push_back(MachineConstantPoolEntry(V, Offset));
525   return Constants.size()-1;
526 }
527 
528 
529 void MachineConstantPool::print(std::ostream &OS) const {
530   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
531     OS << "  <cp #" << i << "> is";
532     if (Constants[i].isMachineConstantPoolEntry())
533       Constants[i].Val.MachineCPVal->print(OS);
534     else
535       OS << *(Value*)Constants[i].Val.ConstVal;
536     OS << " , offset=" << Constants[i].getOffset();
537     OS << "\n";
538   }
539 }
540 
541 void MachineConstantPool::dump() const { print(*cerr.stream()); }
542