1 //===-- MachineFunction.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/DerivedTypes.h"
17 #include "llvm/CodeGen/MachineConstantPool.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineJumpTableInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/Target/TargetData.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/ADT/STLExtras.h"
32 #include "llvm/Config/config.h"
37 static AnnotationID MF_AID(
38 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
40 // Out of line virtual function to home classes.
41 void MachineFunctionPass::virtfn() {}
44 struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
48 const std::string Banner;
50 Printer (std::ostream *os, const std::string &banner)
51 : MachineFunctionPass((intptr_t)&ID), OS(os), Banner(banner) {}
53 const char *getPassName() const { return "MachineFunction Printer"; }
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 bool runOnMachineFunction(MachineFunction &MF) {
68 /// Returns a newly-created MachineFunction Printer pass. The default output
69 /// stream is std::cerr; the default banner is empty.
71 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
72 const std::string &Banner){
73 return new Printer(OS, Banner);
77 struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
79 Deleter() : MachineFunctionPass((intptr_t)&ID) {}
81 const char *getPassName() const { return "Machine Code Deleter"; }
83 bool runOnMachineFunction(MachineFunction &MF) {
84 // Delete the annotation from the function now.
85 MachineFunction::destruct(MF.getFunction());
92 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
93 /// the current function, which should happen after the function has been
94 /// emitted to a .s file or to memory.
95 FunctionPass *llvm::createMachineCodeDeleter() {
101 //===---------------------------------------------------------------------===//
102 // MachineFunction implementation
103 //===---------------------------------------------------------------------===//
105 void alist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
106 MBB->getParent()->DeleteMachineBasicBlock(MBB);
109 MachineFunction::MachineFunction(const Function *F,
110 const TargetMachine &TM)
111 : Annotation(MF_AID), Fn(F), Target(TM) {
112 RegInfo = new (Allocator.Allocate<MachineRegisterInfo>())
113 MachineRegisterInfo(*TM.getRegisterInfo());
115 FrameInfo = new (Allocator.Allocate<MachineFrameInfo>())
116 MachineFrameInfo(*TM.getFrameInfo());
117 ConstantPool = new (Allocator.Allocate<MachineConstantPool>())
118 MachineConstantPool(TM.getTargetData());
120 // Set up jump table.
121 const TargetData &TD = *TM.getTargetData();
122 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
123 unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
124 unsigned Alignment = IsPic ? TD.getABITypeAlignment(Type::Int32Ty)
125 : TD.getPointerABIAlignment();
126 JumpTableInfo = new (Allocator.Allocate<MachineJumpTableInfo>())
127 MachineJumpTableInfo(EntrySize, Alignment);
130 MachineFunction::~MachineFunction() {
132 InstructionRecycler.clear(Allocator);
133 BasicBlockRecycler.clear(Allocator);
134 MemOperandRecycler.clear(Allocator);
135 RegInfo->~MachineRegisterInfo(); Allocator.Deallocate(RegInfo);
137 MFInfo->~MachineFunctionInfo(); Allocator.Deallocate(MFInfo);
139 FrameInfo->~MachineFrameInfo(); Allocator.Deallocate(FrameInfo);
140 ConstantPool->~MachineConstantPool(); Allocator.Deallocate(ConstantPool);
141 JumpTableInfo->~MachineJumpTableInfo(); Allocator.Deallocate(JumpTableInfo);
145 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
146 /// recomputes them. This guarantees that the MBB numbers are sequential,
147 /// dense, and match the ordering of the blocks within the function. If a
148 /// specific MachineBasicBlock is specified, only that block and those after
149 /// it are renumbered.
150 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
151 if (empty()) { MBBNumbering.clear(); return; }
152 MachineFunction::iterator MBBI, E = end();
158 // Figure out the block number this should have.
159 unsigned BlockNo = 0;
161 BlockNo = prior(MBBI)->getNumber()+1;
163 for (; MBBI != E; ++MBBI, ++BlockNo) {
164 if (MBBI->getNumber() != (int)BlockNo) {
165 // Remove use of the old number.
166 if (MBBI->getNumber() != -1) {
167 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
168 "MBB number mismatch!");
169 MBBNumbering[MBBI->getNumber()] = 0;
172 // If BlockNo is already taken, set that block's number to -1.
173 if (MBBNumbering[BlockNo])
174 MBBNumbering[BlockNo]->setNumber(-1);
176 MBBNumbering[BlockNo] = MBBI;
177 MBBI->setNumber(BlockNo);
181 // Okay, all the blocks are renumbered. If we have compactified the block
182 // numbering, shrink MBBNumbering now.
183 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
184 MBBNumbering.resize(BlockNo);
187 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
188 /// of `new MachineInstr'.
191 MachineFunction::CreateMachineInstr(const TargetInstrDesc &TID, bool NoImp) {
192 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
193 MachineInstr(TID, NoImp);
196 /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
197 /// 'Orig' instruction, identical in all ways except the the instruction
198 /// has no parent, prev, or next.
201 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
202 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
203 MachineInstr(*this, *Orig);
206 /// DeleteMachineInstr - Delete the given MachineInstr.
209 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
210 // Clear the instructions memoperands. This must be done manually because
211 // the instruction's parent pointer is now null, so it can't properly
212 // deallocate them on its own.
213 MI->clearMemOperands(*this);
216 InstructionRecycler.Deallocate(Allocator, MI);
219 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
220 /// instead of `new MachineBasicBlock'.
223 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
224 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
225 MachineBasicBlock(*this, bb);
228 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
231 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
232 assert(MBB->getParent() == this && "MBB parent mismatch!");
233 MBB->~MachineBasicBlock();
234 BasicBlockRecycler.Deallocate(Allocator, MBB);
237 /// CreateMachineMemOperand - Allocate a new MachineMemOperand. Use this
238 /// instead of `new MachineMemOperand'.
241 MachineFunction::CreateMachineMemOperand(const MachineMemOperand &MMO) {
242 return new (MemOperandRecycler.Allocate<MachineMemOperand>(Allocator))
243 MachineMemOperand(MMO);
246 /// DeleteMachineMemOperand - Delete the given MachineMemOperand.
249 MachineFunction::DeleteMachineMemOperand(MachineMemOperand *MO) {
250 MO->~MachineMemOperand();
251 MemOperandRecycler.Deallocate(Allocator, MO);
254 void MachineFunction::dump() const {
255 print(*cerr.stream());
258 void MachineFunction::print(std::ostream &OS) const {
259 OS << "# Machine code for " << Fn->getName () << "():\n";
261 // Print Frame Information
262 FrameInfo->print(*this, OS);
264 // Print JumpTable Information
265 JumpTableInfo->print(OS);
267 // Print Constant Pool
268 ConstantPool->print(OS);
270 const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
272 if (!RegInfo->livein_empty()) {
274 for (MachineRegisterInfo::livein_iterator
275 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
277 OS << " " << TRI->getName(I->first);
279 OS << " Reg #" << I->first;
282 OS << " in VR#" << I->second << " ";
286 if (!RegInfo->liveout_empty()) {
288 for (MachineRegisterInfo::liveout_iterator
289 I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I)
291 OS << " " << TRI->getName(*I);
293 OS << " Reg #" << *I;
297 for (const_iterator BB = begin(); BB != end(); ++BB)
300 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
303 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
304 /// prints out the contents of basic blocks or not. This is acceptable because
305 /// this code is only really used for debugging purposes.
307 static bool CFGOnly = false;
311 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
312 static std::string getGraphName(const MachineFunction *F) {
313 return "CFG for '" + F->getFunction()->getName() + "' function";
316 static std::string getNodeLabel(const MachineBasicBlock *Node,
317 const MachineFunction *Graph) {
318 if (CFGOnly && Node->getBasicBlock() &&
319 !Node->getBasicBlock()->getName().empty())
320 return Node->getBasicBlock()->getName() + ":";
322 std::ostringstream Out;
324 Out << Node->getNumber() << ':';
330 std::string OutStr = Out.str();
331 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
333 // Process string output to make it nicer...
334 for (unsigned i = 0; i != OutStr.length(); ++i)
335 if (OutStr[i] == '\n') { // Left justify
337 OutStr.insert(OutStr.begin()+i+1, 'l');
344 void MachineFunction::viewCFG() const
347 ViewGraph(this, "mf" + getFunction()->getName());
349 cerr << "SelectionDAG::viewGraph is only available in debug builds on "
350 << "systems with Graphviz or gv!\n";
354 void MachineFunction::viewCFGOnly() const
361 // The next two methods are used to construct and to retrieve
362 // the MachineCodeForFunction object for the given function.
363 // construct() -- Allocates and initializes for a given function and target
364 // get() -- Returns a handle to the object.
365 // This should not be called before "construct()"
366 // for a given Function.
369 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
371 assert(Fn->getAnnotation(MF_AID) == 0 &&
372 "Object already exists for this function!");
373 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
374 Fn->addAnnotation(mcInfo);
378 void MachineFunction::destruct(const Function *Fn) {
379 bool Deleted = Fn->deleteAnnotation(MF_AID);
380 assert(Deleted && "Machine code did not exist for function!");
381 Deleted = Deleted; // silence warning when no assertions.
384 MachineFunction& MachineFunction::get(const Function *F)
386 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
387 assert(mc && "Call construct() method first to allocate the object");
391 //===----------------------------------------------------------------------===//
392 // MachineFrameInfo implementation
393 //===----------------------------------------------------------------------===//
395 /// CreateFixedObject - Create a new object at a fixed location on the stack.
396 /// All fixed objects should be created before other objects are created for
397 /// efficiency. By default, fixed objects are immutable. This returns an
398 /// index with a negative value.
400 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
402 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
403 Objects.insert(Objects.begin(), StackObject(Size, 1, SPOffset, Immutable));
404 return -++NumFixedObjects;
408 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
409 int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
411 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
412 const StackObject &SO = Objects[i];
413 OS << " <fi #" << (int)(i-NumFixedObjects) << ">: ";
414 if (SO.Size == ~0ULL) {
419 OS << "variable sized";
421 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
422 OS << " alignment is " << SO.Alignment << " byte"
423 << (SO.Alignment != 1 ? "s," : ",");
425 if (i < NumFixedObjects)
427 if (i < NumFixedObjects || SO.SPOffset != -1) {
428 int64_t Off = SO.SPOffset - ValOffset;
429 OS << " at location [SP";
439 if (HasVarSizedObjects)
440 OS << " Stack frame contains variable sized objects\n";
443 void MachineFrameInfo::dump(const MachineFunction &MF) const {
444 print(MF, *cerr.stream());
448 //===----------------------------------------------------------------------===//
449 // MachineJumpTableInfo implementation
450 //===----------------------------------------------------------------------===//
452 /// getJumpTableIndex - Create a new jump table entry in the jump table info
453 /// or return an existing one.
455 unsigned MachineJumpTableInfo::getJumpTableIndex(
456 const std::vector<MachineBasicBlock*> &DestBBs) {
457 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
458 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
459 if (JumpTables[i].MBBs == DestBBs)
462 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
463 return JumpTables.size()-1;
467 void MachineJumpTableInfo::print(std::ostream &OS) const {
468 // FIXME: this is lame, maybe we could print out the MBB numbers or something
469 // like {1, 2, 4, 5, 3, 0}
470 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
471 OS << " <jt #" << i << "> has " << JumpTables[i].MBBs.size()
476 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
479 //===----------------------------------------------------------------------===//
480 // MachineConstantPool implementation
481 //===----------------------------------------------------------------------===//
483 const Type *MachineConstantPoolEntry::getType() const {
484 if (isMachineConstantPoolEntry())
485 return Val.MachineCPVal->getType();
486 return Val.ConstVal->getType();
489 MachineConstantPool::~MachineConstantPool() {
490 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
491 if (Constants[i].isMachineConstantPoolEntry())
492 delete Constants[i].Val.MachineCPVal;
495 /// getConstantPoolIndex - Create a new entry in the constant pool or return
496 /// an existing one. User must specify an alignment in bytes for the object.
498 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
499 unsigned Alignment) {
500 assert(Alignment && "Alignment must be specified!");
501 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
503 // Check to see if we already have this constant.
505 // FIXME, this could be made much more efficient for large constant pools.
506 unsigned AlignMask = (1 << Alignment)-1;
507 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
508 if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
512 if (!Constants.empty()) {
513 Offset = Constants.back().getOffset();
514 Offset += TD->getABITypeSize(Constants.back().getType());
515 Offset = (Offset+AlignMask)&~AlignMask;
518 Constants.push_back(MachineConstantPoolEntry(C, Offset));
519 return Constants.size()-1;
522 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
523 unsigned Alignment) {
524 assert(Alignment && "Alignment must be specified!");
525 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
527 // Check to see if we already have this constant.
529 // FIXME, this could be made much more efficient for large constant pools.
530 unsigned AlignMask = (1 << Alignment)-1;
531 int Idx = V->getExistingMachineCPValue(this, Alignment);
533 return (unsigned)Idx;
536 if (!Constants.empty()) {
537 Offset = Constants.back().getOffset();
538 Offset += TD->getABITypeSize(Constants.back().getType());
539 Offset = (Offset+AlignMask)&~AlignMask;
542 Constants.push_back(MachineConstantPoolEntry(V, Offset));
543 return Constants.size()-1;
547 void MachineConstantPool::print(std::ostream &OS) const {
548 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
549 OS << " <cp #" << i << "> is";
550 if (Constants[i].isMachineConstantPoolEntry())
551 Constants[i].Val.MachineCPVal->print(OS);
553 OS << *(Value*)Constants[i].Val.ConstVal;
554 OS << " , offset=" << Constants[i].getOffset();
559 void MachineConstantPool::dump() const { print(*cerr.stream()); }