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/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetFrameInfo.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Support/LeakDetector.h"
29 #include "llvm/Support/GraphWriter.h"
30 #include "llvm/Config/config.h"
37 static AnnotationID MF_AID(
38 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
42 struct Printer : public MachineFunctionPass {
44 const std::string Banner;
46 Printer (std::ostream *_OS, const std::string &_Banner) :
47 OS (_OS), Banner (_Banner) { }
49 const char *getPassName() const { return "MachineFunction Printer"; }
51 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55 bool runOnMachineFunction(MachineFunction &MF) {
63 /// Returns a newly-created MachineFunction Printer pass. The default output
64 /// stream is std::cerr; the default banner is empty.
66 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
67 const std::string &Banner){
68 return new Printer(OS, Banner);
72 struct Deleter : public MachineFunctionPass {
73 const char *getPassName() const { return "Machine Code Deleter"; }
75 bool runOnMachineFunction(MachineFunction &MF) {
76 // Delete the annotation from the function now.
77 MachineFunction::destruct(MF.getFunction());
83 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
84 /// the current function, which should happen after the function has been
85 /// emitted to a .s file or to memory.
86 FunctionPass *llvm::createMachineCodeDeleter() {
92 //===---------------------------------------------------------------------===//
93 // MachineFunction implementation
94 //===---------------------------------------------------------------------===//
96 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
97 MachineBasicBlock* dummy = new MachineBasicBlock();
98 LeakDetector::removeGarbageObject(dummy);
102 void ilist_traits<MachineBasicBlock>::transferNodesFromList(
103 iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
104 ilist_iterator<MachineBasicBlock> first,
105 ilist_iterator<MachineBasicBlock> last) {
106 if (Parent != toList.Parent)
107 for (; first != last; ++first)
108 first->Parent = toList.Parent;
111 MachineFunction::MachineFunction(const Function *F,
112 const TargetMachine &TM)
113 : Annotation(MF_AID), Fn(F), Target(TM), UsedPhysRegs(0) {
114 SSARegMapping = new SSARegMap();
116 FrameInfo = new MachineFrameInfo();
117 ConstantPool = new MachineConstantPool(TM.getTargetData());
118 JumpTableInfo = new MachineJumpTableInfo(TM.getTargetData());
119 BasicBlocks.Parent = this;
122 MachineFunction::~MachineFunction() {
124 delete SSARegMapping;
128 delete JumpTableInfo;
129 delete[] UsedPhysRegs;
132 void MachineFunction::dump() const { print(std::cerr); }
134 void MachineFunction::print(std::ostream &OS) const {
135 OS << "# Machine code for " << Fn->getName () << "():\n";
137 // Print Frame Information
138 getFrameInfo()->print(*this, OS);
140 // Print JumpTable Information
141 getJumpTableInfo()->print(OS);
143 // Print Constant Pool
144 getConstantPool()->print(OS);
146 const MRegisterInfo *MRI = getTarget().getRegisterInfo();
148 if (livein_begin() != livein_end()) {
150 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
152 OS << " " << MRI->getName(I->first);
154 OS << " Reg #" << I->first;
158 if (liveout_begin() != liveout_end()) {
160 for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
162 OS << " " << MRI->getName(*I);
164 OS << " Reg #" << *I;
168 for (const_iterator BB = begin(); BB != end(); ++BB)
171 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
174 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
175 /// prints out the contents of basic blocks or not. This is acceptable because
176 /// this code is only really used for debugging purposes.
178 static bool CFGOnly = false;
182 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
183 static std::string getGraphName(const MachineFunction *F) {
184 return "CFG for '" + F->getFunction()->getName() + "' function";
187 static std::string getNodeLabel(const MachineBasicBlock *Node,
188 const MachineFunction *Graph) {
189 if (CFGOnly && Node->getBasicBlock() &&
190 !Node->getBasicBlock()->getName().empty())
191 return Node->getBasicBlock()->getName() + ":";
193 std::ostringstream Out;
195 Out << Node->getNumber() << ':';
201 std::string OutStr = Out.str();
202 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
204 // Process string output to make it nicer...
205 for (unsigned i = 0; i != OutStr.length(); ++i)
206 if (OutStr[i] == '\n') { // Left justify
208 OutStr.insert(OutStr.begin()+i+1, 'l');
215 void MachineFunction::viewCFG() const
218 std::string Filename = "/tmp/cfg." + getFunction()->getName() + ".dot";
219 std::cerr << "Writing '" << Filename << "'... ";
220 std::ofstream F(Filename.c_str());
223 std::cerr << " error opening file for writing!\n";
232 std::cerr << "Running 'Graphviz' program... " << std::flush;
233 if (system((LLVM_PATH_GRAPHVIZ " " + Filename).c_str())) {
234 std::cerr << "Error viewing graph: 'Graphviz' not in path?\n";
236 system(("rm " + Filename).c_str());
239 #endif // HAVE_GRAPHVIZ
242 std::cerr << "Running 'dot' program... " << std::flush;
243 if (system(("dot -Tps -Nfontname=Courier -Gsize=7.5,10 " + Filename
244 + " > /tmp/cfg.tempgraph.ps").c_str())) {
245 std::cerr << "Error running dot: 'dot' not in path?\n";
248 system("gv /tmp/cfg.tempgraph.ps");
250 system(("rm " + Filename + " /tmp/cfg.tempgraph.ps").c_str());
254 std::cerr << "MachineFunction::viewCFG is only available in debug builds on "
255 << "systems with Graphviz or gv!\n";
258 system(("rm " + Filename).c_str());
262 void MachineFunction::viewCFGOnly() const
269 // The next two methods are used to construct and to retrieve
270 // the MachineCodeForFunction object for the given function.
271 // construct() -- Allocates and initializes for a given function and target
272 // get() -- Returns a handle to the object.
273 // This should not be called before "construct()"
274 // for a given Function.
277 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
279 assert(Fn->getAnnotation(MF_AID) == 0 &&
280 "Object already exists for this function!");
281 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
282 Fn->addAnnotation(mcInfo);
286 void MachineFunction::destruct(const Function *Fn) {
287 bool Deleted = Fn->deleteAnnotation(MF_AID);
288 assert(Deleted && "Machine code did not exist for function!");
291 MachineFunction& MachineFunction::get(const Function *F)
293 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
294 assert(mc && "Call construct() method first to allocate the object");
298 void MachineFunction::clearSSARegMap() {
299 delete SSARegMapping;
303 //===----------------------------------------------------------------------===//
304 // MachineFrameInfo implementation
305 //===----------------------------------------------------------------------===//
307 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
308 int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
310 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
311 const StackObject &SO = Objects[i];
312 OS << " <fi #" << (int)(i-NumFixedObjects) << ">: ";
314 OS << "variable sized";
316 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
317 OS << " alignment is " << SO.Alignment << " byte"
318 << (SO.Alignment != 1 ? "s," : ",");
320 if (i < NumFixedObjects)
322 if (i < NumFixedObjects || SO.SPOffset != -1) {
323 int Off = SO.SPOffset - ValOffset;
324 OS << " at location [SP";
334 if (HasVarSizedObjects)
335 OS << " Stack frame contains variable sized objects\n";
338 void MachineFrameInfo::dump(const MachineFunction &MF) const {
339 print(MF, std::cerr);
343 //===----------------------------------------------------------------------===//
344 // MachineJumpTableInfo implementation
345 //===----------------------------------------------------------------------===//
347 /// getJumpTableIndex - Create a new jump table entry in the jump table info
348 /// or return an existing one.
350 unsigned MachineJumpTableInfo::getJumpTableIndex(
351 std::vector<MachineBasicBlock*> &DestBBs) {
352 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
353 if (JumpTables[i].MBBs == DestBBs)
356 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
357 return JumpTables.size()-1;
361 void MachineJumpTableInfo::print(std::ostream &OS) const {
362 // FIXME: this is lame, maybe we could print out the MBB numbers or something
363 // like {1, 2, 4, 5, 3, 0}
364 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
365 OS << " <jt #" << i << "> has " << JumpTables[i].MBBs.size()
370 unsigned MachineJumpTableInfo::getEntrySize() const {
371 return TD->getPointerSize();
374 unsigned MachineJumpTableInfo::getAlignment() const {
375 return TD->getPointerAlignment();
378 void MachineJumpTableInfo::dump() const { print(std::cerr); }
381 //===----------------------------------------------------------------------===//
382 // MachineConstantPool implementation
383 //===----------------------------------------------------------------------===//
385 /// getConstantPoolIndex - Create a new entry in the constant pool or return
386 /// an existing one. User must specify an alignment in bytes for the object.
388 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
389 unsigned Alignment) {
390 assert(Alignment && "Alignment must be specified!");
391 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
393 // Check to see if we already have this constant.
395 // FIXME, this could be made much more efficient for large constant pools.
396 unsigned AlignMask = (1 << Alignment)-1;
397 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
398 if (Constants[i].Val == C && (Constants[i].Offset & AlignMask) == 0)
402 if (!Constants.empty()) {
403 Offset = Constants.back().Offset;
404 Offset += TD->getTypeSize(Constants.back().Val->getType());
405 Offset = (Offset+AlignMask)&~AlignMask;
408 Constants.push_back(MachineConstantPoolEntry(C, Offset));
409 return Constants.size()-1;
413 void MachineConstantPool::print(std::ostream &OS) const {
414 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
415 OS << " <cp #" << i << "> is" << *(Value*)Constants[i].Val;
416 OS << " , offset=" << Constants[i].Offset;
421 void MachineConstantPool::dump() const { print(std::cerr); }