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/TargetLowering.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetFrameInfo.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/GraphWriter.h"
31 #include "llvm/Support/LeakDetector.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Config/config.h"
38 static AnnotationID MF_AID(
39 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
41 // Out of line virtual function to home classes.
42 void MachineFunctionPass::virtfn() {}
45 struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
47 const std::string Banner;
49 Printer (std::ostream *_OS, const std::string &_Banner) :
50 OS (_OS), Banner (_Banner) { }
52 const char *getPassName() const { return "MachineFunction Printer"; }
54 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
58 bool runOnMachineFunction(MachineFunction &MF) {
66 /// Returns a newly-created MachineFunction Printer pass. The default output
67 /// stream is std::cerr; the default banner is empty.
69 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
70 const std::string &Banner){
71 return new Printer(OS, Banner);
75 struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
76 const char *getPassName() const { return "Machine Code Deleter"; }
78 bool runOnMachineFunction(MachineFunction &MF) {
79 // Delete the annotation from the function now.
80 MachineFunction::destruct(MF.getFunction());
86 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
87 /// the current function, which should happen after the function has been
88 /// emitted to a .s file or to memory.
89 FunctionPass *llvm::createMachineCodeDeleter() {
95 //===---------------------------------------------------------------------===//
96 // MachineFunction implementation
97 //===---------------------------------------------------------------------===//
99 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
100 MachineBasicBlock* dummy = new MachineBasicBlock();
101 LeakDetector::removeGarbageObject(dummy);
105 void ilist_traits<MachineBasicBlock>::transferNodesFromList(
106 iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
107 ilist_iterator<MachineBasicBlock> first,
108 ilist_iterator<MachineBasicBlock> last) {
109 if (Parent != toList.Parent)
110 for (; first != last; ++first)
111 first->Parent = toList.Parent;
114 MachineFunction::MachineFunction(const Function *F,
115 const TargetMachine &TM)
116 : Annotation(MF_AID), Fn(F), Target(TM), UsedPhysRegs(0) {
117 SSARegMapping = new SSARegMap();
119 FrameInfo = new MachineFrameInfo();
120 ConstantPool = new MachineConstantPool(TM.getTargetData());
122 // Set up jump table.
123 const TargetData &TD = *TM.getTargetData();
124 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
125 unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
126 unsigned Alignment = IsPic ? TD.getIntAlignment() : TD.getPointerAlignment();
127 JumpTableInfo = new MachineJumpTableInfo(EntrySize, Alignment);
129 BasicBlocks.Parent = this;
132 MachineFunction::~MachineFunction() {
134 delete SSARegMapping;
138 delete JumpTableInfo;
139 delete[] UsedPhysRegs;
143 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
144 /// recomputes them. This guarantees that the MBB numbers are sequential,
145 /// dense, and match the ordering of the blocks within the function. If a
146 /// specific MachineBasicBlock is specified, only that block and those after
147 /// it are renumbered.
148 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
149 if (empty()) { MBBNumbering.clear(); return; }
150 MachineFunction::iterator MBBI, E = end();
156 // Figure out the block number this should have.
157 unsigned BlockNo = 0;
159 BlockNo = prior(MBBI)->getNumber()+1;
161 for (; MBBI != E; ++MBBI, ++BlockNo) {
162 if (MBBI->getNumber() != (int)BlockNo) {
163 // Remove use of the old number.
164 if (MBBI->getNumber() != -1) {
165 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
166 "MBB number mismatch!");
167 MBBNumbering[MBBI->getNumber()] = 0;
170 // If BlockNo is already taken, set that block's number to -1.
171 if (MBBNumbering[BlockNo])
172 MBBNumbering[BlockNo]->setNumber(-1);
174 MBBNumbering[BlockNo] = MBBI;
175 MBBI->setNumber(BlockNo);
179 // Okay, all the blocks are renumbered. If we have compactified the block
180 // numbering, shrink MBBNumbering now.
181 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
182 MBBNumbering.resize(BlockNo);
186 void MachineFunction::dump() const { print(*cerr.stream()); }
188 void MachineFunction::print(std::ostream &OS) const {
189 OS << "# Machine code for " << Fn->getName () << "():\n";
191 // Print Frame Information
192 getFrameInfo()->print(*this, OS);
194 // Print JumpTable Information
195 getJumpTableInfo()->print(OS);
197 // Print Constant Pool
198 getConstantPool()->print(OS);
200 const MRegisterInfo *MRI = getTarget().getRegisterInfo();
202 if (livein_begin() != livein_end()) {
204 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
206 OS << " " << MRI->getName(I->first);
208 OS << " Reg #" << I->first;
211 OS << " in VR#" << I->second << " ";
215 if (liveout_begin() != liveout_end()) {
217 for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
219 OS << " " << MRI->getName(*I);
221 OS << " Reg #" << *I;
225 for (const_iterator BB = begin(); BB != end(); ++BB)
228 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
231 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
232 /// prints out the contents of basic blocks or not. This is acceptable because
233 /// this code is only really used for debugging purposes.
235 static bool CFGOnly = false;
239 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
240 static std::string getGraphName(const MachineFunction *F) {
241 return "CFG for '" + F->getFunction()->getName() + "' function";
244 static std::string getNodeLabel(const MachineBasicBlock *Node,
245 const MachineFunction *Graph) {
246 if (CFGOnly && Node->getBasicBlock() &&
247 !Node->getBasicBlock()->getName().empty())
248 return Node->getBasicBlock()->getName() + ":";
250 std::ostringstream Out;
252 Out << Node->getNumber() << ':';
258 std::string OutStr = Out.str();
259 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
261 // Process string output to make it nicer...
262 for (unsigned i = 0; i != OutStr.length(); ++i)
263 if (OutStr[i] == '\n') { // Left justify
265 OutStr.insert(OutStr.begin()+i+1, 'l');
272 void MachineFunction::viewCFG() const
275 ViewGraph(this, "mf" + getFunction()->getName());
277 cerr << "SelectionDAG::viewGraph is only available in debug builds on "
278 << "systems with Graphviz or gv!\n";
282 void MachineFunction::viewCFGOnly() const
289 // The next two methods are used to construct and to retrieve
290 // the MachineCodeForFunction object for the given function.
291 // construct() -- Allocates and initializes for a given function and target
292 // get() -- Returns a handle to the object.
293 // This should not be called before "construct()"
294 // for a given Function.
297 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
299 assert(Fn->getAnnotation(MF_AID) == 0 &&
300 "Object already exists for this function!");
301 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
302 Fn->addAnnotation(mcInfo);
306 void MachineFunction::destruct(const Function *Fn) {
307 bool Deleted = Fn->deleteAnnotation(MF_AID);
308 assert(Deleted && "Machine code did not exist for function!");
311 MachineFunction& MachineFunction::get(const Function *F)
313 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
314 assert(mc && "Call construct() method first to allocate the object");
318 void MachineFunction::clearSSARegMap() {
319 delete SSARegMapping;
323 //===----------------------------------------------------------------------===//
324 // MachineFrameInfo implementation
325 //===----------------------------------------------------------------------===//
327 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
328 int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
330 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
331 const StackObject &SO = Objects[i];
332 OS << " <fi #" << (int)(i-NumFixedObjects) << ">: ";
334 OS << "variable sized";
336 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
337 OS << " alignment is " << SO.Alignment << " byte"
338 << (SO.Alignment != 1 ? "s," : ",");
340 if (i < NumFixedObjects)
342 if (i < NumFixedObjects || SO.SPOffset != -1) {
343 int Off = SO.SPOffset - ValOffset;
344 OS << " at location [SP";
354 if (HasVarSizedObjects)
355 OS << " Stack frame contains variable sized objects\n";
358 void MachineFrameInfo::dump(const MachineFunction &MF) const {
359 print(MF, *cerr.stream());
363 //===----------------------------------------------------------------------===//
364 // MachineJumpTableInfo implementation
365 //===----------------------------------------------------------------------===//
367 /// getJumpTableIndex - Create a new jump table entry in the jump table info
368 /// or return an existing one.
370 unsigned MachineJumpTableInfo::getJumpTableIndex(
371 const std::vector<MachineBasicBlock*> &DestBBs) {
372 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
373 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
374 if (JumpTables[i].MBBs == DestBBs)
377 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
378 return JumpTables.size()-1;
382 void MachineJumpTableInfo::print(std::ostream &OS) const {
383 // FIXME: this is lame, maybe we could print out the MBB numbers or something
384 // like {1, 2, 4, 5, 3, 0}
385 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
386 OS << " <jt #" << i << "> has " << JumpTables[i].MBBs.size()
391 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
394 //===----------------------------------------------------------------------===//
395 // MachineConstantPool implementation
396 //===----------------------------------------------------------------------===//
398 const Type *MachineConstantPoolEntry::getType() const {
399 if (isMachineConstantPoolEntry())
400 return Val.MachineCPVal->getType();
401 return Val.ConstVal->getType();
404 MachineConstantPool::~MachineConstantPool() {
405 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
406 if (Constants[i].isMachineConstantPoolEntry())
407 delete Constants[i].Val.MachineCPVal;
410 /// getConstantPoolIndex - Create a new entry in the constant pool or return
411 /// an existing one. User must specify an alignment in bytes for the object.
413 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
414 unsigned Alignment) {
415 assert(Alignment && "Alignment must be specified!");
416 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
418 // Check to see if we already have this constant.
420 // FIXME, this could be made much more efficient for large constant pools.
421 unsigned AlignMask = (1 << Alignment)-1;
422 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
423 if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
427 if (!Constants.empty()) {
428 Offset = Constants.back().getOffset();
429 Offset += TD->getTypeSize(Constants.back().getType());
430 Offset = (Offset+AlignMask)&~AlignMask;
433 Constants.push_back(MachineConstantPoolEntry(C, Offset));
434 return Constants.size()-1;
437 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
438 unsigned Alignment) {
439 assert(Alignment && "Alignment must be specified!");
440 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
442 // Check to see if we already have this constant.
444 // FIXME, this could be made much more efficient for large constant pools.
445 unsigned AlignMask = (1 << Alignment)-1;
446 int Idx = V->getExistingMachineCPValue(this, Alignment);
448 return (unsigned)Idx;
451 if (!Constants.empty()) {
452 Offset = Constants.back().getOffset();
453 Offset += TD->getTypeSize(Constants.back().getType());
454 Offset = (Offset+AlignMask)&~AlignMask;
457 Constants.push_back(MachineConstantPoolEntry(V, Offset));
458 return Constants.size()-1;
462 void MachineConstantPool::print(std::ostream &OS) const {
463 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
464 OS << " <cp #" << i << "> is";
465 if (Constants[i].isMachineConstantPoolEntry())
466 Constants[i].Val.MachineCPVal->print(OS);
468 OS << *(Value*)Constants[i].Val.ConstVal;
469 OS << " , offset=" << Constants[i].Offset;
474 void MachineConstantPool::dump() const { print(*cerr.stream()); }