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 bool MachineFunctionPass::runOnFunction(Function &F) {
39 // Do not codegen any 'available_externally' functions at all, they have
40 // definitions outside the translation unit.
41 if (F.hasAvailableExternallyLinkage())
44 return runOnMachineFunction(MachineFunction::get(&F));
48 struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
52 const std::string Banner;
54 Printer (std::ostream *os, const std::string &banner)
55 : MachineFunctionPass(&ID), OS(os), Banner(banner) {}
57 const char *getPassName() const { return "MachineFunction Printer"; }
59 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63 bool runOnMachineFunction(MachineFunction &MF) {
72 /// Returns a newly-created MachineFunction Printer pass. The default output
73 /// stream is std::cerr; the default banner is empty.
75 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
76 const std::string &Banner){
77 return new Printer(OS, Banner);
81 struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
83 Deleter() : MachineFunctionPass(&ID) {}
85 const char *getPassName() const { return "Machine Code Deleter"; }
87 bool runOnMachineFunction(MachineFunction &MF) {
88 // Delete the annotation from the function now.
89 MachineFunction::destruct(MF.getFunction());
96 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
97 /// the current function, which should happen after the function has been
98 /// emitted to a .s file or to memory.
99 FunctionPass *llvm::createMachineCodeDeleter() {
100 return new Deleter();
105 //===---------------------------------------------------------------------===//
106 // MachineFunction implementation
107 //===---------------------------------------------------------------------===//
109 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
110 MBB->getParent()->DeleteMachineBasicBlock(MBB);
113 MachineFunction::MachineFunction(const Function *F,
114 const TargetMachine &TM)
115 : Annotation(AnnotationManager::getID("CodeGen::MachineCodeForFunction")),
117 if (TM.getRegisterInfo())
118 RegInfo = new (Allocator.Allocate<MachineRegisterInfo>())
119 MachineRegisterInfo(*TM.getRegisterInfo());
123 FrameInfo = new (Allocator.Allocate<MachineFrameInfo>())
124 MachineFrameInfo(*TM.getFrameInfo());
125 ConstantPool = new (Allocator.Allocate<MachineConstantPool>())
126 MachineConstantPool(TM.getTargetData());
128 // Set up jump table.
129 const TargetData &TD = *TM.getTargetData();
130 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
131 unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
132 unsigned Alignment = IsPic ? TD.getABITypeAlignment(Type::Int32Ty)
133 : TD.getPointerABIAlignment();
134 JumpTableInfo = new (Allocator.Allocate<MachineJumpTableInfo>())
135 MachineJumpTableInfo(EntrySize, Alignment);
138 MachineFunction::~MachineFunction() {
140 InstructionRecycler.clear(Allocator);
141 BasicBlockRecycler.clear(Allocator);
143 RegInfo->~MachineRegisterInfo(); Allocator.Deallocate(RegInfo);
145 MFInfo->~MachineFunctionInfo(); Allocator.Deallocate(MFInfo);
147 FrameInfo->~MachineFrameInfo(); Allocator.Deallocate(FrameInfo);
148 ConstantPool->~MachineConstantPool(); Allocator.Deallocate(ConstantPool);
149 JumpTableInfo->~MachineJumpTableInfo(); Allocator.Deallocate(JumpTableInfo);
153 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
154 /// recomputes them. This guarantees that the MBB numbers are sequential,
155 /// dense, and match the ordering of the blocks within the function. If a
156 /// specific MachineBasicBlock is specified, only that block and those after
157 /// it are renumbered.
158 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
159 if (empty()) { MBBNumbering.clear(); return; }
160 MachineFunction::iterator MBBI, E = end();
166 // Figure out the block number this should have.
167 unsigned BlockNo = 0;
169 BlockNo = prior(MBBI)->getNumber()+1;
171 for (; MBBI != E; ++MBBI, ++BlockNo) {
172 if (MBBI->getNumber() != (int)BlockNo) {
173 // Remove use of the old number.
174 if (MBBI->getNumber() != -1) {
175 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
176 "MBB number mismatch!");
177 MBBNumbering[MBBI->getNumber()] = 0;
180 // If BlockNo is already taken, set that block's number to -1.
181 if (MBBNumbering[BlockNo])
182 MBBNumbering[BlockNo]->setNumber(-1);
184 MBBNumbering[BlockNo] = MBBI;
185 MBBI->setNumber(BlockNo);
189 // Okay, all the blocks are renumbered. If we have compactified the block
190 // numbering, shrink MBBNumbering now.
191 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
192 MBBNumbering.resize(BlockNo);
195 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
196 /// of `new MachineInstr'.
199 MachineFunction::CreateMachineInstr(const TargetInstrDesc &TID,
200 DebugLoc DL, bool NoImp) {
201 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
202 MachineInstr(TID, DL, NoImp);
205 /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
206 /// 'Orig' instruction, identical in all ways except the the instruction
207 /// has no parent, prev, or next.
210 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
211 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
212 MachineInstr(*this, *Orig);
215 /// DeleteMachineInstr - Delete the given MachineInstr.
218 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
219 // Clear the instructions memoperands. This must be done manually because
220 // the instruction's parent pointer is now null, so it can't properly
221 // deallocate them on its own.
222 MI->clearMemOperands(*this);
225 InstructionRecycler.Deallocate(Allocator, MI);
228 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
229 /// instead of `new MachineBasicBlock'.
232 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
233 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
234 MachineBasicBlock(*this, bb);
237 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
240 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
241 assert(MBB->getParent() == this && "MBB parent mismatch!");
242 MBB->~MachineBasicBlock();
243 BasicBlockRecycler.Deallocate(Allocator, MBB);
246 void MachineFunction::dump() const {
247 print(*cerr.stream());
250 void MachineFunction::print(std::ostream &OS) const {
251 OS << "# Machine code for " << Fn->getName () << "():\n";
253 // Print Frame Information
254 FrameInfo->print(*this, OS);
256 // Print JumpTable Information
257 JumpTableInfo->print(OS);
259 // Print Constant Pool
261 raw_os_ostream OSS(OS);
262 ConstantPool->print(OSS);
265 const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
267 if (RegInfo && !RegInfo->livein_empty()) {
269 for (MachineRegisterInfo::livein_iterator
270 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
272 OS << " " << TRI->getName(I->first);
274 OS << " Reg #" << I->first;
277 OS << " in VR#" << I->second << " ";
281 if (RegInfo && !RegInfo->liveout_empty()) {
283 for (MachineRegisterInfo::liveout_iterator
284 I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I)
286 OS << " " << TRI->getName(*I);
288 OS << " Reg #" << *I;
292 for (const_iterator BB = begin(); BB != end(); ++BB)
295 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
300 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
301 static std::string getGraphName(const MachineFunction *F) {
302 return "CFG for '" + F->getFunction()->getName() + "' function";
305 static std::string getNodeLabel(const MachineBasicBlock *Node,
306 const MachineFunction *Graph,
308 if (ShortNames && Node->getBasicBlock() &&
309 !Node->getBasicBlock()->getName().empty())
310 return Node->getBasicBlock()->getName() + ":";
312 std::ostringstream Out;
314 Out << Node->getNumber() << ':';
320 std::string OutStr = Out.str();
321 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
323 // Process string output to make it nicer...
324 for (unsigned i = 0; i != OutStr.length(); ++i)
325 if (OutStr[i] == '\n') { // Left justify
327 OutStr.insert(OutStr.begin()+i+1, 'l');
334 void MachineFunction::viewCFG() const
337 ViewGraph(this, "mf" + getFunction()->getName());
339 cerr << "SelectionDAG::viewGraph is only available in debug builds on "
340 << "systems with Graphviz or gv!\n";
344 void MachineFunction::viewCFGOnly() const
347 ViewGraph(this, "mf" + getFunction()->getName(), true);
349 cerr << "SelectionDAG::viewGraph is only available in debug builds on "
350 << "systems with Graphviz or gv!\n";
354 // The next two methods are used to construct and to retrieve
355 // the MachineCodeForFunction object for the given function.
356 // construct() -- Allocates and initializes for a given function and target
357 // get() -- Returns a handle to the object.
358 // This should not be called before "construct()"
359 // for a given Function.
362 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
364 AnnotationID MF_AID =
365 AnnotationManager::getID("CodeGen::MachineCodeForFunction");
366 assert(Fn->getAnnotation(MF_AID) == 0 &&
367 "Object already exists for this function!");
368 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
369 Fn->addAnnotation(mcInfo);
373 void MachineFunction::destruct(const Function *Fn) {
374 AnnotationID MF_AID =
375 AnnotationManager::getID("CodeGen::MachineCodeForFunction");
376 bool Deleted = Fn->deleteAnnotation(MF_AID);
377 assert(Deleted && "Machine code did not exist for function!");
378 Deleted = Deleted; // silence warning when no assertions.
381 MachineFunction& MachineFunction::get(const Function *F)
383 AnnotationID MF_AID =
384 AnnotationManager::getID("CodeGen::MachineCodeForFunction");
385 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
386 assert(mc && "Call construct() method first to allocate the object");
390 /// addLiveIn - Add the specified physical register as a live-in value and
391 /// create a corresponding virtual register for it.
392 unsigned MachineFunction::addLiveIn(unsigned PReg,
393 const TargetRegisterClass *RC) {
394 assert(RC->contains(PReg) && "Not the correct regclass!");
395 unsigned VReg = getRegInfo().createVirtualRegister(RC);
396 getRegInfo().addLiveIn(PReg, VReg);
400 /// getOrCreateDebugLocID - Look up the DebugLocTuple index with the given
401 /// source file, line, and column. If none currently exists, create a new
402 /// DebugLocTuple, and insert it into the DebugIdMap.
403 unsigned MachineFunction::getOrCreateDebugLocID(GlobalVariable *CompileUnit,
404 unsigned Line, unsigned Col) {
405 DebugLocTuple Tuple(CompileUnit, Line, Col);
406 DenseMap<DebugLocTuple, unsigned>::iterator II
407 = DebugLocInfo.DebugIdMap.find(Tuple);
408 if (II != DebugLocInfo.DebugIdMap.end())
411 unsigned Id = DebugLocInfo.DebugLocations.size();
412 DebugLocInfo.DebugLocations.push_back(Tuple);
413 DebugLocInfo.DebugIdMap[Tuple] = Id;
417 /// getDebugLocTuple - Get the DebugLocTuple for a given DebugLoc object.
418 DebugLocTuple MachineFunction::getDebugLocTuple(DebugLoc DL) const {
419 unsigned Idx = DL.getIndex();
420 assert(Idx < DebugLocInfo.DebugLocations.size() &&
421 "Invalid index into debug locations!");
422 return DebugLocInfo.DebugLocations[Idx];
425 //===----------------------------------------------------------------------===//
426 // MachineFrameInfo implementation
427 //===----------------------------------------------------------------------===//
429 /// CreateFixedObject - Create a new object at a fixed location on the stack.
430 /// All fixed objects should be created before other objects are created for
431 /// efficiency. By default, fixed objects are immutable. This returns an
432 /// index with a negative value.
434 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
436 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
437 Objects.insert(Objects.begin(), StackObject(Size, 1, SPOffset, Immutable));
438 return -++NumFixedObjects;
442 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
443 const TargetFrameInfo *FI = MF.getTarget().getFrameInfo();
444 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
446 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
447 const StackObject &SO = Objects[i];
448 OS << " <fi#" << (int)(i-NumFixedObjects) << ">: ";
449 if (SO.Size == ~0ULL) {
454 OS << "variable sized";
456 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
457 OS << " alignment is " << SO.Alignment << " byte"
458 << (SO.Alignment != 1 ? "s," : ",");
460 if (i < NumFixedObjects)
462 if (i < NumFixedObjects || SO.SPOffset != -1) {
463 int64_t Off = SO.SPOffset - ValOffset;
464 OS << " at location [SP";
474 if (HasVarSizedObjects)
475 OS << " Stack frame contains variable sized objects\n";
478 void MachineFrameInfo::dump(const MachineFunction &MF) const {
479 print(MF, *cerr.stream());
483 //===----------------------------------------------------------------------===//
484 // MachineJumpTableInfo implementation
485 //===----------------------------------------------------------------------===//
487 /// getJumpTableIndex - Create a new jump table entry in the jump table info
488 /// or return an existing one.
490 unsigned MachineJumpTableInfo::getJumpTableIndex(
491 const std::vector<MachineBasicBlock*> &DestBBs) {
492 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
493 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
494 if (JumpTables[i].MBBs == DestBBs)
497 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
498 return JumpTables.size()-1;
501 /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
502 /// the jump tables to branch to New instead.
504 MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
505 MachineBasicBlock *New) {
506 assert(Old != New && "Not making a change?");
507 bool MadeChange = false;
508 for (size_t i = 0, e = JumpTables.size(); i != e; ++i) {
509 MachineJumpTableEntry &JTE = JumpTables[i];
510 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
511 if (JTE.MBBs[j] == Old) {
519 void MachineJumpTableInfo::print(std::ostream &OS) const {
520 // FIXME: this is lame, maybe we could print out the MBB numbers or something
521 // like {1, 2, 4, 5, 3, 0}
522 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
523 OS << " <jt#" << i << "> has " << JumpTables[i].MBBs.size()
528 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
531 //===----------------------------------------------------------------------===//
532 // MachineConstantPool implementation
533 //===----------------------------------------------------------------------===//
535 const Type *MachineConstantPoolEntry::getType() const {
536 if (isMachineConstantPoolEntry())
537 return Val.MachineCPVal->getType();
538 return Val.ConstVal->getType();
541 MachineConstantPool::~MachineConstantPool() {
542 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
543 if (Constants[i].isMachineConstantPoolEntry())
544 delete Constants[i].Val.MachineCPVal;
547 /// getConstantPoolIndex - Create a new entry in the constant pool or return
548 /// an existing one. User must specify the log2 of the minimum required
549 /// alignment for the object.
551 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
552 unsigned Alignment) {
553 assert(Alignment && "Alignment must be specified!");
554 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
556 // Check to see if we already have this constant.
558 // FIXME, this could be made much more efficient for large constant pools.
559 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
560 if (Constants[i].Val.ConstVal == C &&
561 (Constants[i].getAlignment() & (Alignment - 1)) == 0)
564 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
565 return Constants.size()-1;
568 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
569 unsigned Alignment) {
570 assert(Alignment && "Alignment must be specified!");
571 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
573 // Check to see if we already have this constant.
575 // FIXME, this could be made much more efficient for large constant pools.
576 int Idx = V->getExistingMachineCPValue(this, Alignment);
578 return (unsigned)Idx;
580 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
581 return Constants.size()-1;
584 void MachineConstantPool::print(raw_ostream &OS) const {
585 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
586 OS << " <cp#" << i << "> is";
587 if (Constants[i].isMachineConstantPoolEntry())
588 Constants[i].Val.MachineCPVal->print(OS);
590 OS << *(Value*)Constants[i].Val.ConstVal;
591 OS << " , alignment=" << Constants[i].getAlignment();
596 void MachineConstantPool::dump() const { print(errs()); }