LLVM API Documentation

MachineFunction.cpp

Go to the documentation of this file.
00001 //===-- MachineFunction.cpp -----------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Collect native machine code information for a function.  This allows
00011 // target-specific information about the generated code to be stored with each
00012 // function.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/DerivedTypes.h"
00017 #include "llvm/CodeGen/MachineConstantPool.h"
00018 #include "llvm/CodeGen/MachineFunctionPass.h"
00019 #include "llvm/CodeGen/MachineFrameInfo.h"
00020 #include "llvm/CodeGen/MachineInstr.h"
00021 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00022 #include "llvm/CodeGen/MachineRegisterInfo.h"
00023 #include "llvm/CodeGen/Passes.h"
00024 #include "llvm/Target/TargetData.h"
00025 #include "llvm/Target/TargetMachine.h"
00026 #include "llvm/Target/TargetFrameInfo.h"
00027 #include "llvm/Function.h"
00028 #include "llvm/Instructions.h"
00029 #include "llvm/Support/Compiler.h"
00030 #include "llvm/Support/GraphWriter.h"
00031 #include "llvm/Support/raw_ostream.h"
00032 #include "llvm/ADT/STLExtras.h"
00033 #include "llvm/Config/config.h"
00034 #include <fstream>
00035 #include <sstream>
00036 using namespace llvm;
00037 
00038 static AnnotationID MF_AID(
00039   AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
00040 
00041 // Out of line virtual function to home classes.
00042 void MachineFunctionPass::virtfn() {}
00043 
00044 namespace {
00045   struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
00046     static char ID;
00047 
00048     std::ostream *OS;
00049     const std::string Banner;
00050 
00051     Printer (std::ostream *os, const std::string &banner) 
00052       : MachineFunctionPass(&ID), OS(os), Banner(banner) {}
00053 
00054     const char *getPassName() const { return "MachineFunction Printer"; }
00055 
00056     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00057       AU.setPreservesAll();
00058     }
00059 
00060     bool runOnMachineFunction(MachineFunction &MF) {
00061       (*OS) << Banner;
00062       MF.print (*OS);
00063       return false;
00064     }
00065   };
00066   char Printer::ID = 0;
00067 }
00068 
00069 /// Returns a newly-created MachineFunction Printer pass. The default output
00070 /// stream is std::cerr; the default banner is empty.
00071 ///
00072 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
00073                                                      const std::string &Banner){
00074   return new Printer(OS, Banner);
00075 }
00076 
00077 namespace {
00078   struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
00079     static char ID;
00080     Deleter() : MachineFunctionPass(&ID) {}
00081 
00082     const char *getPassName() const { return "Machine Code Deleter"; }
00083 
00084     bool runOnMachineFunction(MachineFunction &MF) {
00085       // Delete the annotation from the function now.
00086       MachineFunction::destruct(MF.getFunction());
00087       return true;
00088     }
00089   };
00090   char Deleter::ID = 0;
00091 }
00092 
00093 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
00094 /// the current function, which should happen after the function has been
00095 /// emitted to a .s file or to memory.
00096 FunctionPass *llvm::createMachineCodeDeleter() {
00097   return new Deleter();
00098 }
00099 
00100 
00101 
00102 //===---------------------------------------------------------------------===//
00103 // MachineFunction implementation
00104 //===---------------------------------------------------------------------===//
00105 
00106 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
00107   MBB->getParent()->DeleteMachineBasicBlock(MBB);
00108 }
00109 
00110 MachineFunction::MachineFunction(const Function *F,
00111                                  const TargetMachine &TM)
00112   : Annotation(MF_AID), Fn(F), Target(TM) {
00113   if (TM.getRegisterInfo())
00114     RegInfo = new (Allocator.Allocate<MachineRegisterInfo>())
00115                   MachineRegisterInfo(*TM.getRegisterInfo());
00116   else
00117     RegInfo = 0;
00118   MFInfo = 0;
00119   FrameInfo = new (Allocator.Allocate<MachineFrameInfo>())
00120                   MachineFrameInfo(*TM.getFrameInfo());
00121   ConstantPool = new (Allocator.Allocate<MachineConstantPool>())
00122                      MachineConstantPool(TM.getTargetData());
00123   
00124   // Set up jump table.
00125   const TargetData &TD = *TM.getTargetData();
00126   bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
00127   unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
00128   unsigned Alignment = IsPic ? TD.getABITypeAlignment(Type::Int32Ty)
00129                              : TD.getPointerABIAlignment();
00130   JumpTableInfo = new (Allocator.Allocate<MachineJumpTableInfo>())
00131                       MachineJumpTableInfo(EntrySize, Alignment);
00132 }
00133 
00134 MachineFunction::~MachineFunction() {
00135   BasicBlocks.clear();
00136   InstructionRecycler.clear(Allocator);
00137   BasicBlockRecycler.clear(Allocator);
00138   if (RegInfo)
00139     RegInfo->~MachineRegisterInfo();        Allocator.Deallocate(RegInfo);
00140   if (MFInfo) {
00141     MFInfo->~MachineFunctionInfo();       Allocator.Deallocate(MFInfo);
00142   }
00143   FrameInfo->~MachineFrameInfo();         Allocator.Deallocate(FrameInfo);
00144   ConstantPool->~MachineConstantPool();   Allocator.Deallocate(ConstantPool);
00145   JumpTableInfo->~MachineJumpTableInfo(); Allocator.Deallocate(JumpTableInfo);
00146 }
00147 
00148 
00149 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
00150 /// recomputes them.  This guarantees that the MBB numbers are sequential,
00151 /// dense, and match the ordering of the blocks within the function.  If a
00152 /// specific MachineBasicBlock is specified, only that block and those after
00153 /// it are renumbered.
00154 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
00155   if (empty()) { MBBNumbering.clear(); return; }
00156   MachineFunction::iterator MBBI, E = end();
00157   if (MBB == 0)
00158     MBBI = begin();
00159   else
00160     MBBI = MBB;
00161   
00162   // Figure out the block number this should have.
00163   unsigned BlockNo = 0;
00164   if (MBBI != begin())
00165     BlockNo = prior(MBBI)->getNumber()+1;
00166   
00167   for (; MBBI != E; ++MBBI, ++BlockNo) {
00168     if (MBBI->getNumber() != (int)BlockNo) {
00169       // Remove use of the old number.
00170       if (MBBI->getNumber() != -1) {
00171         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
00172                "MBB number mismatch!");
00173         MBBNumbering[MBBI->getNumber()] = 0;
00174       }
00175       
00176       // If BlockNo is already taken, set that block's number to -1.
00177       if (MBBNumbering[BlockNo])
00178         MBBNumbering[BlockNo]->setNumber(-1);
00179 
00180       MBBNumbering[BlockNo] = MBBI;
00181       MBBI->setNumber(BlockNo);
00182     }
00183   }    
00184 
00185   // Okay, all the blocks are renumbered.  If we have compactified the block
00186   // numbering, shrink MBBNumbering now.
00187   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
00188   MBBNumbering.resize(BlockNo);
00189 }
00190 
00191 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
00192 /// of `new MachineInstr'.
00193 ///
00194 MachineInstr *
00195 MachineFunction::CreateMachineInstr(const TargetInstrDesc &TID,
00196                                     DebugLoc DL, bool NoImp) {
00197   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
00198     MachineInstr(TID, DL, NoImp);
00199 }
00200 
00201 /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
00202 /// 'Orig' instruction, identical in all ways except the the instruction
00203 /// has no parent, prev, or next.
00204 ///
00205 MachineInstr *
00206 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
00207   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
00208              MachineInstr(*this, *Orig);
00209 }
00210 
00211 /// DeleteMachineInstr - Delete the given MachineInstr.
00212 ///
00213 void
00214 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
00215   // Clear the instructions memoperands. This must be done manually because
00216   // the instruction's parent pointer is now null, so it can't properly
00217   // deallocate them on its own.
00218   MI->clearMemOperands(*this);
00219 
00220   MI->~MachineInstr();
00221   InstructionRecycler.Deallocate(Allocator, MI);
00222 }
00223 
00224 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
00225 /// instead of `new MachineBasicBlock'.
00226 ///
00227 MachineBasicBlock *
00228 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
00229   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
00230              MachineBasicBlock(*this, bb);
00231 }
00232 
00233 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
00234 ///
00235 void
00236 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
00237   assert(MBB->getParent() == this && "MBB parent mismatch!");
00238   MBB->~MachineBasicBlock();
00239   BasicBlockRecycler.Deallocate(Allocator, MBB);
00240 }
00241 
00242 void MachineFunction::dump() const {
00243   print(*cerr.stream());
00244 }
00245 
00246 void MachineFunction::print(std::ostream &OS) const {
00247   OS << "# Machine code for " << Fn->getName () << "():\n";
00248 
00249   // Print Frame Information
00250   FrameInfo->print(*this, OS);
00251   
00252   // Print JumpTable Information
00253   JumpTableInfo->print(OS);
00254 
00255   // Print Constant Pool
00256   {
00257     raw_os_ostream OSS(OS);
00258     ConstantPool->print(OSS);
00259   }
00260   
00261   const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
00262   
00263   if (RegInfo && !RegInfo->livein_empty()) {
00264     OS << "Live Ins:";
00265     for (MachineRegisterInfo::livein_iterator
00266          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
00267       if (TRI)
00268         OS << " " << TRI->getName(I->first);
00269       else
00270         OS << " Reg #" << I->first;
00271       
00272       if (I->second)
00273         OS << " in VR#" << I->second << " ";
00274     }
00275     OS << "\n";
00276   }
00277   if (RegInfo && !RegInfo->liveout_empty()) {
00278     OS << "Live Outs:";
00279     for (MachineRegisterInfo::liveout_iterator
00280          I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I)
00281       if (TRI)
00282         OS << " " << TRI->getName(*I);
00283       else
00284         OS << " Reg #" << *I;
00285     OS << "\n";
00286   }
00287   
00288   for (const_iterator BB = begin(); BB != end(); ++BB)
00289     BB->print(OS);
00290 
00291   OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
00292 }
00293 
00294 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
00295 /// prints out the contents of basic blocks or not.  This is acceptable because
00296 /// this code is only really used for debugging purposes.
00297 ///
00298 static bool CFGOnly = false;
00299 
00300 namespace llvm {
00301   template<>
00302   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
00303     static std::string getGraphName(const MachineFunction *F) {
00304       return "CFG for '" + F->getFunction()->getName() + "' function";
00305     }
00306 
00307     static std::string getNodeLabel(const MachineBasicBlock *Node,
00308                                     const MachineFunction *Graph) {
00309       if (CFGOnly && Node->getBasicBlock() &&
00310           !Node->getBasicBlock()->getName().empty())
00311         return Node->getBasicBlock()->getName() + ":";
00312 
00313       std::ostringstream Out;
00314       if (CFGOnly) {
00315         Out << Node->getNumber() << ':';
00316         return Out.str();
00317       }
00318 
00319       Node->print(Out);
00320 
00321       std::string OutStr = Out.str();
00322       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
00323 
00324       // Process string output to make it nicer...
00325       for (unsigned i = 0; i != OutStr.length(); ++i)
00326         if (OutStr[i] == '\n') {                            // Left justify
00327           OutStr[i] = '\\';
00328           OutStr.insert(OutStr.begin()+i+1, 'l');
00329         }
00330       return OutStr;
00331     }
00332   };
00333 }
00334 
00335 void MachineFunction::viewCFG() const
00336 {
00337 #ifndef NDEBUG
00338   ViewGraph(this, "mf" + getFunction()->getName());
00339 #else
00340   cerr << "SelectionDAG::viewGraph is only available in debug builds on "
00341        << "systems with Graphviz or gv!\n";
00342 #endif // NDEBUG
00343 }
00344 
00345 void MachineFunction::viewCFGOnly() const
00346 {
00347   CFGOnly = true;
00348   viewCFG();
00349   CFGOnly = false;
00350 }
00351 
00352 // The next two methods are used to construct and to retrieve
00353 // the MachineCodeForFunction object for the given function.
00354 // construct() -- Allocates and initializes for a given function and target
00355 // get()       -- Returns a handle to the object.
00356 //                This should not be called before "construct()"
00357 //                for a given Function.
00358 //
00359 MachineFunction&
00360 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
00361 {
00362   assert(Fn->getAnnotation(MF_AID) == 0 &&
00363          "Object already exists for this function!");
00364   MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
00365   Fn->addAnnotation(mcInfo);
00366   return *mcInfo;
00367 }
00368 
00369 void MachineFunction::destruct(const Function *Fn) {
00370   bool Deleted = Fn->deleteAnnotation(MF_AID);
00371   assert(Deleted && "Machine code did not exist for function!"); 
00372   Deleted = Deleted; // silence warning when no assertions.
00373 }
00374 
00375 MachineFunction& MachineFunction::get(const Function *F)
00376 {
00377   MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
00378   assert(mc && "Call construct() method first to allocate the object");
00379   return *mc;
00380 }
00381 
00382 /// getOrCreateDebugLocID - Look up the DebugLocTuple index with the given
00383 /// source file, line, and column. If none currently exists, create add a new
00384 /// new DebugLocTuple and insert it into the DebugIdMap.
00385 unsigned MachineFunction::getOrCreateDebugLocID(unsigned Src, unsigned Line,
00386                                                 unsigned Col) {
00387   struct DebugLocTuple Tuple(Src, Line, Col);
00388   DenseMap<DebugLocTuple, unsigned>::iterator II
00389     = DebugLocInfo.DebugIdMap.find(Tuple);
00390   if (II != DebugLocInfo.DebugIdMap.end())
00391     return II->second;
00392   // Add a new tuple.
00393   unsigned Id = DebugLocInfo.DebugLocations.size();
00394   DebugLocInfo.DebugLocations.push_back(Tuple);
00395   DebugLocInfo.DebugIdMap[Tuple] = Id;
00396   return Id;
00397 }
00398 
00399 //===----------------------------------------------------------------------===//
00400 //  MachineFrameInfo implementation
00401 //===----------------------------------------------------------------------===//
00402 
00403 /// CreateFixedObject - Create a new object at a fixed location on the stack.
00404 /// All fixed objects should be created before other objects are created for
00405 /// efficiency. By default, fixed objects are immutable. This returns an
00406 /// index with a negative value.
00407 ///
00408 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
00409                                         bool Immutable) {
00410   assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
00411   Objects.insert(Objects.begin(), StackObject(Size, 1, SPOffset, Immutable));
00412   return -++NumFixedObjects;
00413 }
00414 
00415 
00416 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
00417   const TargetFrameInfo *FI = MF.getTarget().getFrameInfo();
00418   int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
00419 
00420   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
00421     const StackObject &SO = Objects[i];
00422     OS << "  <fi#" << (int)(i-NumFixedObjects) << ">: ";
00423     if (SO.Size == ~0ULL) {
00424       OS << "dead\n";
00425       continue;
00426     }
00427     if (SO.Size == 0)
00428       OS << "variable sized";
00429     else
00430       OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
00431     OS << " alignment is " << SO.Alignment << " byte"
00432        << (SO.Alignment != 1 ? "s," : ",");
00433 
00434     if (i < NumFixedObjects)
00435       OS << " fixed";
00436     if (i < NumFixedObjects || SO.SPOffset != -1) {
00437       int64_t Off = SO.SPOffset - ValOffset;
00438       OS << " at location [SP";
00439       if (Off > 0)
00440         OS << "+" << Off;
00441       else if (Off < 0)
00442         OS << Off;
00443       OS << "]";
00444     }
00445     OS << "\n";
00446   }
00447 
00448   if (HasVarSizedObjects)
00449     OS << "  Stack frame contains variable sized objects\n";
00450 }
00451 
00452 void MachineFrameInfo::dump(const MachineFunction &MF) const {
00453   print(MF, *cerr.stream());
00454 }
00455 
00456 
00457 //===----------------------------------------------------------------------===//
00458 //  MachineJumpTableInfo implementation
00459 //===----------------------------------------------------------------------===//
00460 
00461 /// getJumpTableIndex - Create a new jump table entry in the jump table info
00462 /// or return an existing one.
00463 ///
00464 unsigned MachineJumpTableInfo::getJumpTableIndex(
00465                                const std::vector<MachineBasicBlock*> &DestBBs) {
00466   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
00467   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
00468     if (JumpTables[i].MBBs == DestBBs)
00469       return i;
00470   
00471   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
00472   return JumpTables.size()-1;
00473 }
00474 
00475 
00476 void MachineJumpTableInfo::print(std::ostream &OS) const {
00477   // FIXME: this is lame, maybe we could print out the MBB numbers or something
00478   // like {1, 2, 4, 5, 3, 0}
00479   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
00480     OS << "  <jt#" << i << "> has " << JumpTables[i].MBBs.size() 
00481        << " entries\n";
00482   }
00483 }
00484 
00485 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
00486 
00487 
00488 //===----------------------------------------------------------------------===//
00489 //  MachineConstantPool implementation
00490 //===----------------------------------------------------------------------===//
00491 
00492 const Type *MachineConstantPoolEntry::getType() const {
00493   if (isMachineConstantPoolEntry())
00494       return Val.MachineCPVal->getType();
00495   return Val.ConstVal->getType();
00496 }
00497 
00498 MachineConstantPool::~MachineConstantPool() {
00499   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
00500     if (Constants[i].isMachineConstantPoolEntry())
00501       delete Constants[i].Val.MachineCPVal;
00502 }
00503 
00504 /// getConstantPoolIndex - Create a new entry in the constant pool or return
00505 /// an existing one.  User must specify the log2 of the minimum required
00506 /// alignment for the object.
00507 ///
00508 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C, 
00509                                                    unsigned Alignment) {
00510   assert(Alignment && "Alignment must be specified!");
00511   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
00512   
00513   // Check to see if we already have this constant.
00514   //
00515   // FIXME, this could be made much more efficient for large constant pools.
00516   unsigned AlignMask = (1 << Alignment)-1;
00517   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
00518     if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
00519       return i;
00520   
00521   unsigned Offset = 0;
00522   if (!Constants.empty()) {
00523     Offset = Constants.back().getOffset();
00524     Offset += TD->getTypePaddedSize(Constants.back().getType());
00525     Offset = (Offset+AlignMask)&~AlignMask;
00526   }
00527   
00528   Constants.push_back(MachineConstantPoolEntry(C, Offset));
00529   return Constants.size()-1;
00530 }
00531 
00532 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
00533                                                    unsigned Alignment) {
00534   assert(Alignment && "Alignment must be specified!");
00535   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
00536   
00537   // Check to see if we already have this constant.
00538   //
00539   // FIXME, this could be made much more efficient for large constant pools.
00540   unsigned AlignMask = (1 << Alignment)-1;
00541   int Idx = V->getExistingMachineCPValue(this, Alignment);
00542   if (Idx != -1)
00543     return (unsigned)Idx;
00544   
00545   unsigned Offset = 0;
00546   if (!Constants.empty()) {
00547     Offset = Constants.back().getOffset();
00548     Offset += TD->getTypePaddedSize(Constants.back().getType());
00549     Offset = (Offset+AlignMask)&~AlignMask;
00550   }
00551   
00552   Constants.push_back(MachineConstantPoolEntry(V, Offset));
00553   return Constants.size()-1;
00554 }
00555 
00556 void MachineConstantPool::print(raw_ostream &OS) const {
00557   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
00558     OS << "  <cp#" << i << "> is";
00559     if (Constants[i].isMachineConstantPoolEntry())
00560       Constants[i].Val.MachineCPVal->print(OS);
00561     else
00562       OS << *(Value*)Constants[i].Val.ConstVal;
00563     OS << " , offset=" << Constants[i].getOffset();
00564     OS << "\n";
00565   }
00566 }
00567 
00568 void MachineConstantPool::dump() const { print(errs()); errs().flush(); }