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/Support/raw_ostream.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 {
49 const std::string Banner;
51 Printer (std::ostream *os, const std::string &banner)
52 : MachineFunctionPass(&ID), OS(os), Banner(banner) {}
54 const char *getPassName() const { return "MachineFunction Printer"; }
56 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60 bool runOnMachineFunction(MachineFunction &MF) {
69 /// Returns a newly-created MachineFunction Printer pass. The default output
70 /// stream is std::cerr; the default banner is empty.
72 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
73 const std::string &Banner){
74 return new Printer(OS, Banner);
78 struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
80 Deleter() : MachineFunctionPass(&ID) {}
82 const char *getPassName() const { return "Machine Code Deleter"; }
84 bool runOnMachineFunction(MachineFunction &MF) {
85 // Delete the annotation from the function now.
86 MachineFunction::destruct(MF.getFunction());
93 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
94 /// the current function, which should happen after the function has been
95 /// emitted to a .s file or to memory.
96 FunctionPass *llvm::createMachineCodeDeleter() {
102 //===---------------------------------------------------------------------===//
103 // MachineFunction implementation
104 //===---------------------------------------------------------------------===//
106 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
107 MBB->getParent()->DeleteMachineBasicBlock(MBB);
110 MachineFunction::MachineFunction(const Function *F,
111 const TargetMachine &TM)
112 : Annotation(MF_AID), Fn(F), Target(TM) {
113 if (TM.getRegisterInfo())
114 RegInfo = new (Allocator.Allocate<MachineRegisterInfo>())
115 MachineRegisterInfo(*TM.getRegisterInfo());
119 FrameInfo = new (Allocator.Allocate<MachineFrameInfo>())
120 MachineFrameInfo(*TM.getFrameInfo());
121 ConstantPool = new (Allocator.Allocate<MachineConstantPool>())
122 MachineConstantPool(TM.getTargetData());
124 // Set up jump table.
125 const TargetData &TD = *TM.getTargetData();
126 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
127 unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
128 unsigned Alignment = IsPic ? TD.getABITypeAlignment(Type::Int32Ty)
129 : TD.getPointerABIAlignment();
130 JumpTableInfo = new (Allocator.Allocate<MachineJumpTableInfo>())
131 MachineJumpTableInfo(EntrySize, Alignment);
134 MachineFunction::~MachineFunction() {
136 InstructionRecycler.clear(Allocator);
137 BasicBlockRecycler.clear(Allocator);
139 RegInfo->~MachineRegisterInfo(); Allocator.Deallocate(RegInfo);
141 MFInfo->~MachineFunctionInfo(); Allocator.Deallocate(MFInfo);
143 FrameInfo->~MachineFrameInfo(); Allocator.Deallocate(FrameInfo);
144 ConstantPool->~MachineConstantPool(); Allocator.Deallocate(ConstantPool);
145 JumpTableInfo->~MachineJumpTableInfo(); Allocator.Deallocate(JumpTableInfo);
149 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
150 /// recomputes them. This guarantees that the MBB numbers are sequential,
151 /// dense, and match the ordering of the blocks within the function. If a
152 /// specific MachineBasicBlock is specified, only that block and those after
153 /// it are renumbered.
154 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
155 if (empty()) { MBBNumbering.clear(); return; }
156 MachineFunction::iterator MBBI, E = end();
162 // Figure out the block number this should have.
163 unsigned BlockNo = 0;
165 BlockNo = prior(MBBI)->getNumber()+1;
167 for (; MBBI != E; ++MBBI, ++BlockNo) {
168 if (MBBI->getNumber() != (int)BlockNo) {
169 // Remove use of the old number.
170 if (MBBI->getNumber() != -1) {
171 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
172 "MBB number mismatch!");
173 MBBNumbering[MBBI->getNumber()] = 0;
176 // If BlockNo is already taken, set that block's number to -1.
177 if (MBBNumbering[BlockNo])
178 MBBNumbering[BlockNo]->setNumber(-1);
180 MBBNumbering[BlockNo] = MBBI;
181 MBBI->setNumber(BlockNo);
185 // Okay, all the blocks are renumbered. If we have compactified the block
186 // numbering, shrink MBBNumbering now.
187 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
188 MBBNumbering.resize(BlockNo);
191 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
192 /// of `new MachineInstr'.
195 MachineFunction::CreateMachineInstr(const TargetInstrDesc &TID,
196 DebugLoc DL, bool NoImp) {
197 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
198 MachineInstr(TID, DL, NoImp);
201 /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
202 /// 'Orig' instruction, identical in all ways except the the instruction
203 /// has no parent, prev, or next.
206 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
207 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
208 MachineInstr(*this, *Orig);
211 /// DeleteMachineInstr - Delete the given MachineInstr.
214 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
215 // Clear the instructions memoperands. This must be done manually because
216 // the instruction's parent pointer is now null, so it can't properly
217 // deallocate them on its own.
218 MI->clearMemOperands(*this);
221 InstructionRecycler.Deallocate(Allocator, MI);
224 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
225 /// instead of `new MachineBasicBlock'.
228 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
229 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
230 MachineBasicBlock(*this, bb);
233 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
236 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
237 assert(MBB->getParent() == this && "MBB parent mismatch!");
238 MBB->~MachineBasicBlock();
239 BasicBlockRecycler.Deallocate(Allocator, MBB);
242 void MachineFunction::dump() const {
243 print(*cerr.stream());
246 void MachineFunction::print(std::ostream &OS) const {
247 OS << "# Machine code for " << Fn->getName () << "():\n";
249 // Print Frame Information
250 FrameInfo->print(*this, OS);
252 // Print JumpTable Information
253 JumpTableInfo->print(OS);
255 // Print Constant Pool
257 raw_os_ostream OSS(OS);
258 ConstantPool->print(OSS);
261 const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
263 if (RegInfo && !RegInfo->livein_empty()) {
265 for (MachineRegisterInfo::livein_iterator
266 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
268 OS << " " << TRI->getName(I->first);
270 OS << " Reg #" << I->first;
273 OS << " in VR#" << I->second << " ";
277 if (RegInfo && !RegInfo->liveout_empty()) {
279 for (MachineRegisterInfo::liveout_iterator
280 I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I)
282 OS << " " << TRI->getName(*I);
284 OS << " Reg #" << *I;
288 for (const_iterator BB = begin(); BB != end(); ++BB)
291 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
294 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
295 /// prints out the contents of basic blocks or not. This is acceptable because
296 /// this code is only really used for debugging purposes.
298 static bool CFGOnly = false;
302 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
303 static std::string getGraphName(const MachineFunction *F) {
304 return "CFG for '" + F->getFunction()->getName() + "' function";
307 static std::string getNodeLabel(const MachineBasicBlock *Node,
308 const MachineFunction *Graph) {
309 if (CFGOnly && Node->getBasicBlock() &&
310 !Node->getBasicBlock()->getName().empty())
311 return Node->getBasicBlock()->getName() + ":";
313 std::ostringstream Out;
315 Out << Node->getNumber() << ':';
321 std::string OutStr = Out.str();
322 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
324 // Process string output to make it nicer...
325 for (unsigned i = 0; i != OutStr.length(); ++i)
326 if (OutStr[i] == '\n') { // Left justify
328 OutStr.insert(OutStr.begin()+i+1, 'l');
335 void MachineFunction::viewCFG() const
338 ViewGraph(this, "mf" + getFunction()->getName());
340 cerr << "SelectionDAG::viewGraph is only available in debug builds on "
341 << "systems with Graphviz or gv!\n";
345 void MachineFunction::viewCFGOnly() const
352 // The next two methods are used to construct and to retrieve
353 // the MachineCodeForFunction object for the given function.
354 // construct() -- Allocates and initializes for a given function and target
355 // get() -- Returns a handle to the object.
356 // This should not be called before "construct()"
357 // for a given Function.
360 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
362 assert(Fn->getAnnotation(MF_AID) == 0 &&
363 "Object already exists for this function!");
364 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
365 Fn->addAnnotation(mcInfo);
369 void MachineFunction::destruct(const Function *Fn) {
370 bool Deleted = Fn->deleteAnnotation(MF_AID);
371 assert(Deleted && "Machine code did not exist for function!");
372 Deleted = Deleted; // silence warning when no assertions.
375 MachineFunction& MachineFunction::get(const Function *F)
377 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
378 assert(mc && "Call construct() method first to allocate the object");
382 /// getOrCreateDebugLocID - Look up the DebugLocTuple index with the given
383 /// source file, line, and column. If none currently exists, create a new
384 /// DebugLocTuple, and insert it into the DebugIdMap.
385 unsigned MachineFunction::getOrCreateDebugLocID(unsigned Src, unsigned Line,
387 DebugLocTuple Tuple(Src, Line, Col);
388 DenseMap<DebugLocTuple, unsigned>::iterator II
389 = DebugLocInfo.DebugIdMap.find(Tuple);
390 if (II != DebugLocInfo.DebugIdMap.end())
393 unsigned Id = DebugLocInfo.DebugLocations.size();
394 DebugLocInfo.DebugLocations.push_back(Tuple);
395 DebugLocInfo.DebugIdMap[Tuple] = Id;
399 /// getDebugLocTuple - Get the DebugLocTuple for a given DebugLoc object.
400 DebugLocTuple MachineFunction::getDebugLocTuple(DebugLoc DL) const {
401 unsigned Idx = DL.getIndex();
402 assert(Idx < DebugLocInfo.DebugLocations.size() &&
403 "Invalid index into debug locations!");
404 return DebugLocInfo.DebugLocations[Idx];
407 //===----------------------------------------------------------------------===//
408 // MachineFrameInfo implementation
409 //===----------------------------------------------------------------------===//
411 /// CreateFixedObject - Create a new object at a fixed location on the stack.
412 /// All fixed objects should be created before other objects are created for
413 /// efficiency. By default, fixed objects are immutable. This returns an
414 /// index with a negative value.
416 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
418 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
419 Objects.insert(Objects.begin(), StackObject(Size, 1, SPOffset, Immutable));
420 return -++NumFixedObjects;
424 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
425 const TargetFrameInfo *FI = MF.getTarget().getFrameInfo();
426 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
428 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
429 const StackObject &SO = Objects[i];
430 OS << " <fi#" << (int)(i-NumFixedObjects) << ">: ";
431 if (SO.Size == ~0ULL) {
436 OS << "variable sized";
438 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
439 OS << " alignment is " << SO.Alignment << " byte"
440 << (SO.Alignment != 1 ? "s," : ",");
442 if (i < NumFixedObjects)
444 if (i < NumFixedObjects || SO.SPOffset != -1) {
445 int64_t Off = SO.SPOffset - ValOffset;
446 OS << " at location [SP";
456 if (HasVarSizedObjects)
457 OS << " Stack frame contains variable sized objects\n";
460 void MachineFrameInfo::dump(const MachineFunction &MF) const {
461 print(MF, *cerr.stream());
465 //===----------------------------------------------------------------------===//
466 // MachineJumpTableInfo implementation
467 //===----------------------------------------------------------------------===//
469 /// getJumpTableIndex - Create a new jump table entry in the jump table info
470 /// or return an existing one.
472 unsigned MachineJumpTableInfo::getJumpTableIndex(
473 const std::vector<MachineBasicBlock*> &DestBBs) {
474 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
475 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
476 if (JumpTables[i].MBBs == DestBBs)
479 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
480 return JumpTables.size()-1;
484 void MachineJumpTableInfo::print(std::ostream &OS) const {
485 // FIXME: this is lame, maybe we could print out the MBB numbers or something
486 // like {1, 2, 4, 5, 3, 0}
487 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
488 OS << " <jt#" << i << "> has " << JumpTables[i].MBBs.size()
493 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
496 //===----------------------------------------------------------------------===//
497 // MachineConstantPool implementation
498 //===----------------------------------------------------------------------===//
500 const Type *MachineConstantPoolEntry::getType() const {
501 if (isMachineConstantPoolEntry())
502 return Val.MachineCPVal->getType();
503 return Val.ConstVal->getType();
506 MachineConstantPool::~MachineConstantPool() {
507 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
508 if (Constants[i].isMachineConstantPoolEntry())
509 delete Constants[i].Val.MachineCPVal;
512 /// getConstantPoolIndex - Create a new entry in the constant pool or return
513 /// an existing one. User must specify the log2 of the minimum required
514 /// alignment for the object.
516 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
517 unsigned Alignment) {
518 assert(Alignment && "Alignment must be specified!");
519 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
521 // Check to see if we already have this constant.
523 // FIXME, this could be made much more efficient for large constant pools.
524 unsigned AlignMask = (1 << Alignment)-1;
525 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
526 if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
530 if (!Constants.empty()) {
531 Offset = Constants.back().getOffset();
532 Offset += TD->getTypePaddedSize(Constants.back().getType());
533 Offset = (Offset+AlignMask)&~AlignMask;
536 Constants.push_back(MachineConstantPoolEntry(C, Offset));
537 return Constants.size()-1;
540 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
541 unsigned Alignment) {
542 assert(Alignment && "Alignment must be specified!");
543 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
545 // Check to see if we already have this constant.
547 // FIXME, this could be made much more efficient for large constant pools.
548 unsigned AlignMask = (1 << Alignment)-1;
549 int Idx = V->getExistingMachineCPValue(this, Alignment);
551 return (unsigned)Idx;
554 if (!Constants.empty()) {
555 Offset = Constants.back().getOffset();
556 Offset += TD->getTypePaddedSize(Constants.back().getType());
557 Offset = (Offset+AlignMask)&~AlignMask;
560 Constants.push_back(MachineConstantPoolEntry(V, Offset));
561 return Constants.size()-1;
564 void MachineConstantPool::print(raw_ostream &OS) const {
565 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
566 OS << " <cp#" << i << "> is";
567 if (Constants[i].isMachineConstantPoolEntry())
568 Constants[i].Val.MachineCPVal->print(OS);
570 OS << *(Value*)Constants[i].Val.ConstVal;
571 OS << " , offset=" << Constants[i].getOffset();
576 void MachineConstantPool::dump() const { print(errs()); errs().flush(); }