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;
157 OS << " in VR#" << I->second << " ";
161 if (liveout_begin() != liveout_end()) {
163 for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
165 OS << " " << MRI->getName(*I);
167 OS << " Reg #" << *I;
171 for (const_iterator BB = begin(); BB != end(); ++BB)
174 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
177 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
178 /// prints out the contents of basic blocks or not. This is acceptable because
179 /// this code is only really used for debugging purposes.
181 static bool CFGOnly = false;
185 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
186 static std::string getGraphName(const MachineFunction *F) {
187 return "CFG for '" + F->getFunction()->getName() + "' function";
190 static std::string getNodeLabel(const MachineBasicBlock *Node,
191 const MachineFunction *Graph) {
192 if (CFGOnly && Node->getBasicBlock() &&
193 !Node->getBasicBlock()->getName().empty())
194 return Node->getBasicBlock()->getName() + ":";
196 std::ostringstream Out;
198 Out << Node->getNumber() << ':';
204 std::string OutStr = Out.str();
205 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
207 // Process string output to make it nicer...
208 for (unsigned i = 0; i != OutStr.length(); ++i)
209 if (OutStr[i] == '\n') { // Left justify
211 OutStr.insert(OutStr.begin()+i+1, 'l');
218 void MachineFunction::viewCFG() const
221 std::string Filename = "/tmp/cfg." + getFunction()->getName() + ".dot";
222 std::cerr << "Writing '" << Filename << "'... ";
223 std::ofstream F(Filename.c_str());
226 std::cerr << " error opening file for writing!\n";
235 std::cerr << "Running 'Graphviz' program... " << std::flush;
236 if (system((LLVM_PATH_GRAPHVIZ " " + Filename).c_str())) {
237 std::cerr << "Error viewing graph: 'Graphviz' not in path?\n";
239 system(("rm " + Filename).c_str());
242 #endif // HAVE_GRAPHVIZ
245 std::cerr << "Running 'dot' program... " << std::flush;
246 if (system(("dot -Tps -Nfontname=Courier -Gsize=7.5,10 " + Filename
247 + " > /tmp/cfg.tempgraph.ps").c_str())) {
248 std::cerr << "Error running dot: 'dot' not in path?\n";
251 system("gv /tmp/cfg.tempgraph.ps");
253 system(("rm " + Filename + " /tmp/cfg.tempgraph.ps").c_str());
257 std::cerr << "MachineFunction::viewCFG is only available in debug builds on "
258 << "systems with Graphviz or gv!\n";
261 system(("rm " + Filename).c_str());
265 void MachineFunction::viewCFGOnly() const
272 // The next two methods are used to construct and to retrieve
273 // the MachineCodeForFunction object for the given function.
274 // construct() -- Allocates and initializes for a given function and target
275 // get() -- Returns a handle to the object.
276 // This should not be called before "construct()"
277 // for a given Function.
280 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
282 assert(Fn->getAnnotation(MF_AID) == 0 &&
283 "Object already exists for this function!");
284 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
285 Fn->addAnnotation(mcInfo);
289 void MachineFunction::destruct(const Function *Fn) {
290 bool Deleted = Fn->deleteAnnotation(MF_AID);
291 assert(Deleted && "Machine code did not exist for function!");
294 MachineFunction& MachineFunction::get(const Function *F)
296 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
297 assert(mc && "Call construct() method first to allocate the object");
301 void MachineFunction::clearSSARegMap() {
302 delete SSARegMapping;
306 //===----------------------------------------------------------------------===//
307 // MachineFrameInfo implementation
308 //===----------------------------------------------------------------------===//
310 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
311 int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
313 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
314 const StackObject &SO = Objects[i];
315 OS << " <fi #" << (int)(i-NumFixedObjects) << ">: ";
317 OS << "variable sized";
319 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
320 OS << " alignment is " << SO.Alignment << " byte"
321 << (SO.Alignment != 1 ? "s," : ",");
323 if (i < NumFixedObjects)
325 if (i < NumFixedObjects || SO.SPOffset != -1) {
326 int Off = SO.SPOffset - ValOffset;
327 OS << " at location [SP";
337 if (HasVarSizedObjects)
338 OS << " Stack frame contains variable sized objects\n";
341 void MachineFrameInfo::dump(const MachineFunction &MF) const {
342 print(MF, std::cerr);
346 //===----------------------------------------------------------------------===//
347 // MachineJumpTableInfo implementation
348 //===----------------------------------------------------------------------===//
350 /// getJumpTableIndex - Create a new jump table entry in the jump table info
351 /// or return an existing one.
353 unsigned MachineJumpTableInfo::getJumpTableIndex(
354 std::vector<MachineBasicBlock*> &DestBBs) {
355 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
356 if (JumpTables[i].MBBs == DestBBs)
359 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
360 return JumpTables.size()-1;
364 void MachineJumpTableInfo::print(std::ostream &OS) const {
365 // FIXME: this is lame, maybe we could print out the MBB numbers or something
366 // like {1, 2, 4, 5, 3, 0}
367 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
368 OS << " <jt #" << i << "> has " << JumpTables[i].MBBs.size()
373 unsigned MachineJumpTableInfo::getEntrySize() const {
374 return TD->getPointerSize();
377 unsigned MachineJumpTableInfo::getAlignment() const {
378 return TD->getPointerAlignment();
381 void MachineJumpTableInfo::dump() const { print(std::cerr); }
384 //===----------------------------------------------------------------------===//
385 // MachineConstantPool implementation
386 //===----------------------------------------------------------------------===//
388 /// getConstantPoolIndex - Create a new entry in the constant pool or return
389 /// an existing one. User must specify an alignment in bytes for the object.
391 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
392 unsigned Alignment) {
393 assert(Alignment && "Alignment must be specified!");
394 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
396 // Check to see if we already have this constant.
398 // FIXME, this could be made much more efficient for large constant pools.
399 unsigned AlignMask = (1 << Alignment)-1;
400 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
401 if (Constants[i].Val == C && (Constants[i].Offset & AlignMask) == 0)
405 if (!Constants.empty()) {
406 Offset = Constants.back().Offset;
407 Offset += TD->getTypeSize(Constants.back().Val->getType());
408 Offset = (Offset+AlignMask)&~AlignMask;
411 Constants.push_back(MachineConstantPoolEntry(C, Offset));
412 return Constants.size()-1;
416 void MachineConstantPool::print(std::ostream &OS) const {
417 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
418 OS << " <cp #" << i << "> is" << *(Value*)Constants[i].Val;
419 OS << " , offset=" << Constants[i].Offset;
424 void MachineConstantPool::dump() const { print(std::cerr); }