1 //===-- MachineFunction.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // Collect native machine code information for a function. This allows
11 // target-specific information about the generated code to be stored with each
14 //===----------------------------------------------------------------------===//
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/TargetMachine.h"
24 #include "llvm/Target/TargetFrameInfo.h"
25 #include "llvm/Function.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Support/LeakDetector.h"
28 #include "llvm/Support/GraphWriter.h"
29 #include "llvm/Config/config.h"
36 static AnnotationID MF_AID(
37 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
41 struct Printer : public MachineFunctionPass {
43 const std::string Banner;
45 Printer (std::ostream *_OS, const std::string &_Banner) :
46 OS (_OS), Banner (_Banner) { }
48 const char *getPassName() const { return "MachineFunction Printer"; }
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54 bool runOnMachineFunction(MachineFunction &MF) {
62 /// Returns a newly-created MachineFunction Printer pass. The default output
63 /// stream is std::cerr; the default banner is empty.
65 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
66 const std::string &Banner){
67 return new Printer(OS, Banner);
71 struct Deleter : public MachineFunctionPass {
72 const char *getPassName() const { return "Machine Code Deleter"; }
74 bool runOnMachineFunction(MachineFunction &MF) {
75 // Delete the annotation from the function now.
76 MachineFunction::destruct(MF.getFunction());
82 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
83 /// the current function, which should happen after the function has been
84 /// emitted to a .s file or to memory.
85 FunctionPass *llvm::createMachineCodeDeleter() {
91 //===---------------------------------------------------------------------===//
92 // MachineFunction implementation
93 //===---------------------------------------------------------------------===//
95 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
96 MachineBasicBlock* dummy = new MachineBasicBlock();
97 LeakDetector::removeGarbageObject(dummy);
101 void ilist_traits<MachineBasicBlock>::transferNodesFromList(
102 iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
103 ilist_iterator<MachineBasicBlock> first,
104 ilist_iterator<MachineBasicBlock> last) {
105 if (Parent != toList.Parent)
106 for (; first != last; ++first)
107 first->Parent = toList.Parent;
110 MachineFunction::MachineFunction(const Function *F,
111 const TargetMachine &TM)
112 : Annotation(MF_AID), Fn(F), Target(TM), UsedPhysRegs(0) {
113 SSARegMapping = new SSARegMap();
115 FrameInfo = new MachineFrameInfo();
116 ConstantPool = new MachineConstantPool(TM.getTargetData());
117 JumpTableInfo = new MachineJumpTableInfo(TM.getTargetData());
118 BasicBlocks.Parent = this;
121 MachineFunction::~MachineFunction() {
123 delete SSARegMapping;
127 delete JumpTableInfo;
128 delete[] UsedPhysRegs;
131 void MachineFunction::dump() const { print(std::cerr); }
133 void MachineFunction::print(std::ostream &OS) const {
134 OS << "# Machine code for " << Fn->getName () << "():\n";
136 // Print Frame Information
137 getFrameInfo()->print(*this, OS);
139 // Print JumpTable Information
140 getJumpTableInfo()->print(OS);
142 // Print Constant Pool
143 getConstantPool()->print(OS);
145 const MRegisterInfo *MRI = getTarget().getRegisterInfo();
147 if (livein_begin() != livein_end()) {
149 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
151 OS << " " << MRI->getName(I->first);
153 OS << " Reg #" << I->first;
157 if (liveout_begin() != liveout_end()) {
159 for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
161 OS << " " << MRI->getName(*I);
163 OS << " Reg #" << *I;
167 for (const_iterator BB = begin(); BB != end(); ++BB)
170 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
173 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
174 /// prints out the contents of basic blocks or not. This is acceptable because
175 /// this code is only really used for debugging purposes.
177 static bool CFGOnly = false;
181 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
182 static std::string getGraphName(const MachineFunction *F) {
183 return "CFG for '" + F->getFunction()->getName() + "' function";
186 static std::string getNodeLabel(const MachineBasicBlock *Node,
187 const MachineFunction *Graph) {
188 if (CFGOnly && Node->getBasicBlock() &&
189 !Node->getBasicBlock()->getName().empty())
190 return Node->getBasicBlock()->getName() + ":";
192 std::ostringstream Out;
194 Out << Node->getNumber() << ':';
200 std::string OutStr = Out.str();
201 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
203 // Process string output to make it nicer...
204 for (unsigned i = 0; i != OutStr.length(); ++i)
205 if (OutStr[i] == '\n') { // Left justify
207 OutStr.insert(OutStr.begin()+i+1, 'l');
214 void MachineFunction::viewCFG() const
217 std::string Filename = "/tmp/cfg." + getFunction()->getName() + ".dot";
218 std::cerr << "Writing '" << Filename << "'... ";
219 std::ofstream F(Filename.c_str());
222 std::cerr << " error opening file for writing!\n";
231 std::cerr << "Running 'Graphviz' program... " << std::flush;
232 if (system((LLVM_PATH_GRAPHVIZ " " + Filename).c_str())) {
233 std::cerr << "Error viewing graph: 'Graphviz' not in path?\n";
235 system(("rm " + Filename).c_str());
238 #endif // HAVE_GRAPHVIZ
241 std::cerr << "Running 'dot' program... " << std::flush;
242 if (system(("dot -Tps -Nfontname=Courier -Gsize=7.5,10 " + Filename
243 + " > /tmp/cfg.tempgraph.ps").c_str())) {
244 std::cerr << "Error running dot: 'dot' not in path?\n";
247 system("gv /tmp/cfg.tempgraph.ps");
249 system(("rm " + Filename + " /tmp/cfg.tempgraph.ps").c_str());
253 std::cerr << "MachineFunction::viewCFG is only available in debug builds on "
254 << "systems with Graphviz or gv!\n";
257 system(("rm " + Filename).c_str());
261 void MachineFunction::viewCFGOnly() const
268 // The next two methods are used to construct and to retrieve
269 // the MachineCodeForFunction object for the given function.
270 // construct() -- Allocates and initializes for a given function and target
271 // get() -- Returns a handle to the object.
272 // This should not be called before "construct()"
273 // for a given Function.
276 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
278 assert(Fn->getAnnotation(MF_AID) == 0 &&
279 "Object already exists for this function!");
280 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
281 Fn->addAnnotation(mcInfo);
285 void MachineFunction::destruct(const Function *Fn) {
286 bool Deleted = Fn->deleteAnnotation(MF_AID);
287 assert(Deleted && "Machine code did not exist for function!");
290 MachineFunction& MachineFunction::get(const Function *F)
292 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
293 assert(mc && "Call construct() method first to allocate the object");
297 void MachineFunction::clearSSARegMap() {
298 delete SSARegMapping;
302 //===----------------------------------------------------------------------===//
303 // MachineFrameInfo implementation
304 //===----------------------------------------------------------------------===//
306 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
307 int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
309 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
310 const StackObject &SO = Objects[i];
311 OS << " <fi #" << (int)(i-NumFixedObjects) << ">: ";
313 OS << "variable sized";
315 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
316 OS << " alignment is " << SO.Alignment << " byte"
317 << (SO.Alignment != 1 ? "s," : ",");
319 if (i < NumFixedObjects)
321 if (i < NumFixedObjects || SO.SPOffset != -1) {
322 int Off = SO.SPOffset - ValOffset;
323 OS << " at location [SP";
333 if (HasVarSizedObjects)
334 OS << " Stack frame contains variable sized objects\n";
337 void MachineFrameInfo::dump(const MachineFunction &MF) const {
338 print(MF, std::cerr);
342 //===----------------------------------------------------------------------===//
343 // MachineJumpTableInfo implementation
344 //===----------------------------------------------------------------------===//
346 /// getJumpTableIndex - Create a new jump table entry in the jump table info
347 /// or return an existing one.
349 unsigned MachineJumpTableInfo::getJumpTableIndex(
350 std::vector<MachineBasicBlock*> &DestBBs) {
351 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
352 if (JumpTables[i].MBBs == DestBBs)
355 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
356 return JumpTables.size()-1;
360 void MachineJumpTableInfo::print(std::ostream &OS) const {
361 // FIXME: this is lame, maybe we could print out the MBB numbers or something
362 // like {1, 2, 4, 5, 3, 0}
363 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
364 OS << " <jt #" << i << "> has " << JumpTables[i].MBBs.size()
369 void MachineJumpTableInfo::dump() const { print(std::cerr); }
372 //===----------------------------------------------------------------------===//
373 // MachineConstantPool implementation
374 //===----------------------------------------------------------------------===//
376 /// getConstantPoolIndex - Create a new entry in the constant pool or return
377 /// an existing one. User must specify an alignment in bytes for the object.
379 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
380 unsigned Alignment) {
381 assert(Alignment && "Alignment must be specified!");
382 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
384 // Check to see if we already have this constant.
386 // FIXME, this could be made much more efficient for large constant pools.
387 unsigned AlignMask = (1 << Alignment)-1;
388 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
389 if (Constants[i].Val == C && (Constants[i].Offset & AlignMask) == 0)
393 if (!Constants.empty()) {
394 Offset = Constants.back().Offset;
395 Offset += TD.getTypeSize(Constants.back().Val->getType());
396 Offset = (Offset+AlignMask)&~AlignMask;
399 Constants.push_back(MachineConstantPoolEntry(C, Offset));
400 return Constants.size()-1;
404 void MachineConstantPool::print(std::ostream &OS) const {
405 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
406 OS << " <cp #" << i << "> is" << *(Value*)Constants[i].Val;
407 OS << " , offset=" << Constants[i].Offset;
412 void MachineConstantPool::dump() const { print(std::cerr); }