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/Passes.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetFrameInfo.h"
24 #include "llvm/Function.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Support/LeakDetector.h"
27 #include "llvm/Support/GraphWriter.h"
28 #include "llvm/Config/config.h"
35 static AnnotationID MF_AID(
36 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
40 struct Printer : public MachineFunctionPass {
42 const std::string Banner;
44 Printer (std::ostream *_OS, const std::string &_Banner) :
45 OS (_OS), Banner (_Banner) { }
47 const char *getPassName() const { return "MachineFunction Printer"; }
49 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
53 bool runOnMachineFunction(MachineFunction &MF) {
61 /// Returns a newly-created MachineFunction Printer pass. The default output
62 /// stream is std::cerr; the default banner is empty.
64 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
65 const std::string &Banner){
66 return new Printer(OS, Banner);
70 struct Deleter : public MachineFunctionPass {
71 const char *getPassName() const { return "Machine Code Deleter"; }
73 bool runOnMachineFunction(MachineFunction &MF) {
74 // Delete the annotation from the function now.
75 MachineFunction::destruct(MF.getFunction());
81 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
82 /// the current function, which should happen after the function has been
83 /// emitted to a .s file or to memory.
84 FunctionPass *llvm::createMachineCodeDeleter() {
90 //===---------------------------------------------------------------------===//
91 // MachineFunction implementation
92 //===---------------------------------------------------------------------===//
94 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
95 MachineBasicBlock* dummy = new MachineBasicBlock();
96 LeakDetector::removeGarbageObject(dummy);
100 void ilist_traits<MachineBasicBlock>::transferNodesFromList(
101 iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
102 ilist_iterator<MachineBasicBlock> first,
103 ilist_iterator<MachineBasicBlock> last) {
104 if (Parent != toList.Parent)
105 for (; first != last; ++first)
106 first->Parent = toList.Parent;
109 MachineFunction::MachineFunction(const Function *F,
110 const TargetMachine &TM)
111 : Annotation(MF_AID), Fn(F), Target(TM), UsedPhysRegs(0) {
112 SSARegMapping = new SSARegMap();
114 FrameInfo = new MachineFrameInfo();
115 ConstantPool = new MachineConstantPool(TM.getTargetData());
116 BasicBlocks.Parent = this;
119 MachineFunction::~MachineFunction() {
121 delete SSARegMapping;
125 delete[] UsedPhysRegs;
128 void MachineFunction::dump() const { print(std::cerr); }
130 void MachineFunction::print(std::ostream &OS) const {
131 OS << "# Machine code for " << Fn->getName () << "():\n";
133 // Print Frame Information
134 getFrameInfo()->print(*this, OS);
136 // Print Constant Pool
137 getConstantPool()->print(OS);
139 const MRegisterInfo *MRI = getTarget().getRegisterInfo();
141 if (livein_begin() != livein_end()) {
143 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
145 OS << " " << MRI->getName(I->first);
147 OS << " Reg #" << I->first;
151 if (liveout_begin() != liveout_end()) {
153 for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
155 OS << " " << MRI->getName(*I);
157 OS << " Reg #" << *I;
161 for (const_iterator BB = begin(); BB != end(); ++BB)
164 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
167 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
168 /// prints out the contents of basic blocks or not. This is acceptable because
169 /// this code is only really used for debugging purposes.
171 static bool CFGOnly = false;
175 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
176 static std::string getGraphName(const MachineFunction *F) {
177 return "CFG for '" + F->getFunction()->getName() + "' function";
180 static std::string getNodeLabel(const MachineBasicBlock *Node,
181 const MachineFunction *Graph) {
182 if (CFGOnly && Node->getBasicBlock() &&
183 !Node->getBasicBlock()->getName().empty())
184 return Node->getBasicBlock()->getName() + ":";
186 std::ostringstream Out;
188 Out << Node->getNumber() << ':';
194 std::string OutStr = Out.str();
195 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
197 // Process string output to make it nicer...
198 for (unsigned i = 0; i != OutStr.length(); ++i)
199 if (OutStr[i] == '\n') { // Left justify
201 OutStr.insert(OutStr.begin()+i+1, 'l');
208 void MachineFunction::viewCFG() const
211 std::string Filename = "/tmp/cfg." + getFunction()->getName() + ".dot";
212 std::cerr << "Writing '" << Filename << "'... ";
213 std::ofstream F(Filename.c_str());
216 std::cerr << " error opening file for writing!\n";
225 std::cerr << "Running 'Graphviz' program... " << std::flush;
226 if (system((LLVM_PATH_GRAPHVIZ " " + Filename).c_str())) {
227 std::cerr << "Error viewing graph: 'Graphviz' not in path?\n";
229 system(("rm " + Filename).c_str());
232 #endif // HAVE_GRAPHVIZ
235 std::cerr << "Running 'dot' program... " << std::flush;
236 if (system(("dot -Tps -Nfontname=Courier -Gsize=7.5,10 " + Filename
237 + " > /tmp/cfg.tempgraph.ps").c_str())) {
238 std::cerr << "Error running dot: 'dot' not in path?\n";
241 system("gv /tmp/cfg.tempgraph.ps");
243 system(("rm " + Filename + " /tmp/cfg.tempgraph.ps").c_str());
247 std::cerr << "MachineFunction::viewCFG is only available in debug builds on "
248 << "systems with Graphviz or gv!\n";
251 system(("rm " + Filename).c_str());
255 void MachineFunction::viewCFGOnly() const
262 // The next two methods are used to construct and to retrieve
263 // the MachineCodeForFunction object for the given function.
264 // construct() -- Allocates and initializes for a given function and target
265 // get() -- Returns a handle to the object.
266 // This should not be called before "construct()"
267 // for a given Function.
270 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
272 assert(Fn->getAnnotation(MF_AID) == 0 &&
273 "Object already exists for this function!");
274 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
275 Fn->addAnnotation(mcInfo);
279 void MachineFunction::destruct(const Function *Fn) {
280 bool Deleted = Fn->deleteAnnotation(MF_AID);
281 assert(Deleted && "Machine code did not exist for function!");
284 MachineFunction& MachineFunction::get(const Function *F)
286 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
287 assert(mc && "Call construct() method first to allocate the object");
291 void MachineFunction::clearSSARegMap() {
292 delete SSARegMapping;
296 //===----------------------------------------------------------------------===//
297 // MachineFrameInfo implementation
298 //===----------------------------------------------------------------------===//
300 /// CreateStackObject - Create a stack object for a value of the specified type.
302 int MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) {
303 return CreateStackObject((unsigned)TD.getTypeSize(Ty),
304 TD.getTypeAlignment(Ty));
308 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
309 int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
311 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
312 const StackObject &SO = Objects[i];
313 OS << " <fi #" << (int)(i-NumFixedObjects) << ">: ";
315 OS << "variable sized";
317 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
318 OS << " alignment is " << SO.Alignment << " byte"
319 << (SO.Alignment != 1 ? "s," : ",");
321 if (i < NumFixedObjects)
323 if (i < NumFixedObjects || SO.SPOffset != -1) {
324 int Off = SO.SPOffset - ValOffset;
325 OS << " at location [SP";
335 if (HasVarSizedObjects)
336 OS << " Stack frame contains variable sized objects\n";
339 void MachineFrameInfo::dump(const MachineFunction &MF) const {
340 print(MF, std::cerr);
344 //===----------------------------------------------------------------------===//
345 // MachineConstantPool implementation
346 //===----------------------------------------------------------------------===//
348 /// getConstantPoolIndex - Create a new entry in the constant pool or return
349 /// an existing one. User must specify an alignment in bytes for the object.
351 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
352 unsigned Alignment) {
353 assert(Alignment && "Alignment must be specified!");
354 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
356 // Check to see if we already have this constant.
358 // FIXME, this could be made much more efficient for large constant pools.
359 unsigned AlignMask = (1 << Alignment)-1;
360 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
361 if (Constants[i].Val == C && (Constants[i].Offset & AlignMask) == 0)
365 if (!Constants.empty()) {
366 Offset = Constants.back().Offset;
367 Offset += TD.getTypeSize(Constants.back().Val->getType());
368 Offset = (Offset+AlignMask)&~AlignMask;
371 Constants.push_back(MachineConstantPoolEntry(C, Offset));
372 return Constants.size()-1;
376 void MachineConstantPool::print(std::ostream &OS) const {
377 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
378 OS << " <cp #" << i << "> is" << *(Value*)Constants[i].Val;
379 OS << " , offset=" << Constants[i].Offset;
384 void MachineConstantPool::dump() const { print(std::cerr); }