MachineFunction.cpp revision 2a610c7387664bc557a35ce3bb4c0d4df56e4755
1//===-- MachineFunction.cpp -----------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Collect native machine code information for a function.  This allows
11// target-specific information about the generated code to be stored with each
12// function.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/DerivedTypes.h"
17#include "llvm/Function.h"
18#include "llvm/Instructions.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/Config/config.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineInstr.h"
26#include "llvm/CodeGen/MachineJumpTableInfo.h"
27#include "llvm/CodeGen/MachineRegisterInfo.h"
28#include "llvm/CodeGen/Passes.h"
29#include "llvm/Target/TargetData.h"
30#include "llvm/Target/TargetLowering.h"
31#include "llvm/Target/TargetMachine.h"
32#include "llvm/Target/TargetFrameInfo.h"
33#include "llvm/Support/Compiler.h"
34#include "llvm/Support/GraphWriter.h"
35#include "llvm/Support/raw_ostream.h"
36using namespace llvm;
37
38namespace {
39  struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
40    static char ID;
41
42    raw_ostream &OS;
43    const std::string Banner;
44
45    Printer(raw_ostream &os, const std::string &banner)
46      : MachineFunctionPass(&ID), OS(os), Banner(banner) {}
47
48    const char *getPassName() const { return "MachineFunction Printer"; }
49
50    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51      AU.setPreservesAll();
52      MachineFunctionPass::getAnalysisUsage(AU);
53    }
54
55    bool runOnMachineFunction(MachineFunction &MF) {
56      OS << Banner;
57      MF.print(OS);
58      return false;
59    }
60  };
61  char Printer::ID = 0;
62}
63
64/// Returns a newly-created MachineFunction Printer pass. The default banner is
65/// empty.
66///
67FunctionPass *llvm::createMachineFunctionPrinterPass(raw_ostream &OS,
68                                                     const std::string &Banner){
69  return new Printer(OS, Banner);
70}
71
72//===---------------------------------------------------------------------===//
73// MachineFunction implementation
74//===---------------------------------------------------------------------===//
75
76void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
77  MBB->getParent()->DeleteMachineBasicBlock(MBB);
78}
79
80MachineFunction::MachineFunction(Function *F,
81                                 const TargetMachine &TM)
82  : Fn(F), Target(TM) {
83  if (TM.getRegisterInfo())
84    RegInfo = new (Allocator.Allocate<MachineRegisterInfo>())
85                  MachineRegisterInfo(*TM.getRegisterInfo());
86  else
87    RegInfo = 0;
88  MFInfo = 0;
89  FrameInfo = new (Allocator.Allocate<MachineFrameInfo>())
90                  MachineFrameInfo(*TM.getFrameInfo());
91  ConstantPool = new (Allocator.Allocate<MachineConstantPool>())
92                     MachineConstantPool(TM.getTargetData());
93  Alignment = TM.getTargetLowering()->getFunctionAlignment(F);
94
95  // Set up jump table.
96  const TargetData &TD = *TM.getTargetData();
97  bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
98  unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
99  unsigned TyAlignment = IsPic ?
100                       TD.getABITypeAlignment(Type::getInt32Ty(F->getContext()))
101                               : TD.getPointerABIAlignment();
102  JumpTableInfo = new (Allocator.Allocate<MachineJumpTableInfo>())
103                      MachineJumpTableInfo(EntrySize, TyAlignment);
104}
105
106MachineFunction::~MachineFunction() {
107  BasicBlocks.clear();
108  InstructionRecycler.clear(Allocator);
109  BasicBlockRecycler.clear(Allocator);
110  if (RegInfo) {
111    RegInfo->~MachineRegisterInfo();
112    Allocator.Deallocate(RegInfo);
113  }
114  if (MFInfo) {
115    MFInfo->~MachineFunctionInfo();
116    Allocator.Deallocate(MFInfo);
117  }
118  FrameInfo->~MachineFrameInfo();         Allocator.Deallocate(FrameInfo);
119  ConstantPool->~MachineConstantPool();   Allocator.Deallocate(ConstantPool);
120  JumpTableInfo->~MachineJumpTableInfo(); Allocator.Deallocate(JumpTableInfo);
121}
122
123
124/// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
125/// recomputes them.  This guarantees that the MBB numbers are sequential,
126/// dense, and match the ordering of the blocks within the function.  If a
127/// specific MachineBasicBlock is specified, only that block and those after
128/// it are renumbered.
129void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
130  if (empty()) { MBBNumbering.clear(); return; }
131  MachineFunction::iterator MBBI, E = end();
132  if (MBB == 0)
133    MBBI = begin();
134  else
135    MBBI = MBB;
136
137  // Figure out the block number this should have.
138  unsigned BlockNo = 0;
139  if (MBBI != begin())
140    BlockNo = prior(MBBI)->getNumber()+1;
141
142  for (; MBBI != E; ++MBBI, ++BlockNo) {
143    if (MBBI->getNumber() != (int)BlockNo) {
144      // Remove use of the old number.
145      if (MBBI->getNumber() != -1) {
146        assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
147               "MBB number mismatch!");
148        MBBNumbering[MBBI->getNumber()] = 0;
149      }
150
151      // If BlockNo is already taken, set that block's number to -1.
152      if (MBBNumbering[BlockNo])
153        MBBNumbering[BlockNo]->setNumber(-1);
154
155      MBBNumbering[BlockNo] = MBBI;
156      MBBI->setNumber(BlockNo);
157    }
158  }
159
160  // Okay, all the blocks are renumbered.  If we have compactified the block
161  // numbering, shrink MBBNumbering now.
162  assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
163  MBBNumbering.resize(BlockNo);
164}
165
166/// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
167/// of `new MachineInstr'.
168///
169MachineInstr *
170MachineFunction::CreateMachineInstr(const TargetInstrDesc &TID,
171                                    DebugLoc DL, bool NoImp) {
172  return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
173    MachineInstr(TID, DL, NoImp);
174}
175
176/// CloneMachineInstr - Create a new MachineInstr which is a copy of the
177/// 'Orig' instruction, identical in all ways except the the instruction
178/// has no parent, prev, or next.
179///
180MachineInstr *
181MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
182  return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
183             MachineInstr(*this, *Orig);
184}
185
186/// DeleteMachineInstr - Delete the given MachineInstr.
187///
188void
189MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
190  // Clear the instructions memoperands. This must be done manually because
191  // the instruction's parent pointer is now null, so it can't properly
192  // deallocate them on its own.
193  MI->clearMemOperands(*this);
194
195  MI->~MachineInstr();
196  InstructionRecycler.Deallocate(Allocator, MI);
197}
198
199/// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
200/// instead of `new MachineBasicBlock'.
201///
202MachineBasicBlock *
203MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
204  return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
205             MachineBasicBlock(*this, bb);
206}
207
208/// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
209///
210void
211MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
212  assert(MBB->getParent() == this && "MBB parent mismatch!");
213  MBB->~MachineBasicBlock();
214  BasicBlockRecycler.Deallocate(Allocator, MBB);
215}
216
217void MachineFunction::dump() const {
218  print(errs());
219}
220
221void MachineFunction::print(raw_ostream &OS) const {
222  OS << "# Machine code for " << Fn->getName() << "():\n";
223
224  // Print Frame Information
225  FrameInfo->print(*this, OS);
226
227  // Print JumpTable Information
228  JumpTableInfo->print(OS);
229
230  // Print Constant Pool
231  ConstantPool->print(OS);
232
233  const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
234
235  if (RegInfo && !RegInfo->livein_empty()) {
236    OS << "Live Ins:";
237    for (MachineRegisterInfo::livein_iterator
238         I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
239      if (TRI)
240        OS << " " << TRI->getName(I->first);
241      else
242        OS << " Reg #" << I->first;
243
244      if (I->second)
245        OS << " in VR#" << I->second << ' ';
246    }
247    OS << '\n';
248  }
249  if (RegInfo && !RegInfo->liveout_empty()) {
250    OS << "Live Outs:";
251    for (MachineRegisterInfo::liveout_iterator
252         I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I)
253      if (TRI)
254        OS << ' ' << TRI->getName(*I);
255      else
256        OS << " Reg #" << *I;
257    OS << '\n';
258  }
259
260  for (const_iterator BB = begin(), E = end(); BB != E; ++BB)
261    BB->print(OS);
262
263  OS << "\n# End machine code for " << Fn->getName() << "().\n\n";
264}
265
266namespace llvm {
267  template<>
268  struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
269    static std::string getGraphName(const MachineFunction *F) {
270      return "CFG for '" + F->getFunction()->getNameStr() + "' function";
271    }
272
273    static std::string getNodeLabel(const MachineBasicBlock *Node,
274                                    const MachineFunction *Graph,
275                                    bool ShortNames) {
276      if (ShortNames && Node->getBasicBlock() &&
277          !Node->getBasicBlock()->getName().empty())
278        return Node->getBasicBlock()->getNameStr() + ":";
279
280      std::string OutStr;
281      {
282        raw_string_ostream OSS(OutStr);
283
284        if (ShortNames)
285          OSS << Node->getNumber() << ':';
286        else
287          Node->print(OSS);
288      }
289
290      if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
291
292      // Process string output to make it nicer...
293      for (unsigned i = 0; i != OutStr.length(); ++i)
294        if (OutStr[i] == '\n') {                            // Left justify
295          OutStr[i] = '\\';
296          OutStr.insert(OutStr.begin()+i+1, 'l');
297        }
298      return OutStr;
299    }
300  };
301}
302
303void MachineFunction::viewCFG() const
304{
305#ifndef NDEBUG
306  ViewGraph(this, "mf" + getFunction()->getNameStr());
307#else
308  errs() << "SelectionDAG::viewGraph is only available in debug builds on "
309         << "systems with Graphviz or gv!\n";
310#endif // NDEBUG
311}
312
313void MachineFunction::viewCFGOnly() const
314{
315#ifndef NDEBUG
316  ViewGraph(this, "mf" + getFunction()->getNameStr(), true);
317#else
318  errs() << "SelectionDAG::viewGraph is only available in debug builds on "
319         << "systems with Graphviz or gv!\n";
320#endif // NDEBUG
321}
322
323/// addLiveIn - Add the specified physical register as a live-in value and
324/// create a corresponding virtual register for it.
325unsigned MachineFunction::addLiveIn(unsigned PReg,
326                                    const TargetRegisterClass *RC) {
327  assert(RC->contains(PReg) && "Not the correct regclass!");
328  unsigned VReg = getRegInfo().createVirtualRegister(RC);
329  getRegInfo().addLiveIn(PReg, VReg);
330  return VReg;
331}
332
333/// getOrCreateDebugLocID - Look up the DebugLocTuple index with the given
334/// source file, line, and column. If none currently exists, create a new
335/// DebugLocTuple, and insert it into the DebugIdMap.
336unsigned MachineFunction::getOrCreateDebugLocID(MDNode *CompileUnit,
337                                                unsigned Line, unsigned Col) {
338  DebugLocTuple Tuple(CompileUnit, Line, Col);
339  DenseMap<DebugLocTuple, unsigned>::iterator II
340    = DebugLocInfo.DebugIdMap.find(Tuple);
341  if (II != DebugLocInfo.DebugIdMap.end())
342    return II->second;
343  // Add a new tuple.
344  unsigned Id = DebugLocInfo.DebugLocations.size();
345  DebugLocInfo.DebugLocations.push_back(Tuple);
346  DebugLocInfo.DebugIdMap[Tuple] = Id;
347  return Id;
348}
349
350/// getDebugLocTuple - Get the DebugLocTuple for a given DebugLoc object.
351DebugLocTuple MachineFunction::getDebugLocTuple(DebugLoc DL) const {
352  unsigned Idx = DL.getIndex();
353  assert(Idx < DebugLocInfo.DebugLocations.size() &&
354         "Invalid index into debug locations!");
355  return DebugLocInfo.DebugLocations[Idx];
356}
357
358//===----------------------------------------------------------------------===//
359//  MachineFrameInfo implementation
360//===----------------------------------------------------------------------===//
361
362/// CreateFixedObject - Create a new object at a fixed location on the stack.
363/// All fixed objects should be created before other objects are created for
364/// efficiency. By default, fixed objects are immutable. This returns an
365/// index with a negative value.
366///
367int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
368                                        bool Immutable) {
369  assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
370  Objects.insert(Objects.begin(), StackObject(Size, 1, SPOffset, Immutable));
371  return -++NumFixedObjects;
372}
373
374
375BitVector
376MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
377  assert(MBB && "MBB must be valid");
378  const MachineFunction *MF = MBB->getParent();
379  assert(MF && "MBB must be part of a MachineFunction");
380  const TargetMachine &TM = MF->getTarget();
381  const TargetRegisterInfo *TRI = TM.getRegisterInfo();
382  BitVector BV(TRI->getNumRegs());
383
384  // Before CSI is calculated, no registers are considered pristine. They can be
385  // freely used and PEI will make sure they are saved.
386  if (!isCalleeSavedInfoValid())
387    return BV;
388
389  for (const unsigned *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
390    BV.set(*CSR);
391
392  // The entry MBB always has all CSRs pristine.
393  if (MBB == &MF->front())
394    return BV;
395
396  // On other MBBs the saved CSRs are not pristine.
397  const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
398  for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
399         E = CSI.end(); I != E; ++I)
400    BV.reset(I->getReg());
401
402  return BV;
403}
404
405
406void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
407  const TargetFrameInfo *FI = MF.getTarget().getFrameInfo();
408  int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
409
410  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
411    const StackObject &SO = Objects[i];
412    OS << "  <fi#" << (int)(i-NumFixedObjects) << ">: ";
413    if (SO.Size == ~0ULL) {
414      OS << "dead\n";
415      continue;
416    }
417    if (SO.Size == 0)
418      OS << "variable sized";
419    else
420      OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
421    OS << " alignment is " << SO.Alignment << " byte"
422       << (SO.Alignment != 1 ? "s," : ",");
423
424    if (i < NumFixedObjects)
425      OS << " fixed";
426    if (i < NumFixedObjects || SO.SPOffset != -1) {
427      int64_t Off = SO.SPOffset - ValOffset;
428      OS << " at location [SP";
429      if (Off > 0)
430        OS << "+" << Off;
431      else if (Off < 0)
432        OS << Off;
433      OS << "]";
434    }
435    OS << "\n";
436  }
437
438  if (HasVarSizedObjects)
439    OS << "  Stack frame contains variable sized objects\n";
440}
441
442void MachineFrameInfo::dump(const MachineFunction &MF) const {
443  print(MF, errs());
444}
445
446//===----------------------------------------------------------------------===//
447//  MachineJumpTableInfo implementation
448//===----------------------------------------------------------------------===//
449
450/// getJumpTableIndex - Create a new jump table entry in the jump table info
451/// or return an existing one.
452///
453unsigned MachineJumpTableInfo::getJumpTableIndex(
454                               const std::vector<MachineBasicBlock*> &DestBBs) {
455  assert(!DestBBs.empty() && "Cannot create an empty jump table!");
456  for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
457    if (JumpTables[i].MBBs == DestBBs)
458      return i;
459
460  JumpTables.push_back(MachineJumpTableEntry(DestBBs));
461  return JumpTables.size()-1;
462}
463
464/// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
465/// the jump tables to branch to New instead.
466bool
467MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
468                                             MachineBasicBlock *New) {
469  assert(Old != New && "Not making a change?");
470  bool MadeChange = false;
471  for (size_t i = 0, e = JumpTables.size(); i != e; ++i) {
472    MachineJumpTableEntry &JTE = JumpTables[i];
473    for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
474      if (JTE.MBBs[j] == Old) {
475        JTE.MBBs[j] = New;
476        MadeChange = true;
477      }
478  }
479  return MadeChange;
480}
481
482void MachineJumpTableInfo::print(raw_ostream &OS) const {
483  // FIXME: this is lame, maybe we could print out the MBB numbers or something
484  // like {1, 2, 4, 5, 3, 0}
485  for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
486    OS << "  <jt#" << i << "> has " << JumpTables[i].MBBs.size()
487       << " entries\n";
488  }
489}
490
491void MachineJumpTableInfo::dump() const { print(errs()); }
492
493
494//===----------------------------------------------------------------------===//
495//  MachineConstantPool implementation
496//===----------------------------------------------------------------------===//
497
498const Type *MachineConstantPoolEntry::getType() const {
499  if (isMachineConstantPoolEntry())
500    return Val.MachineCPVal->getType();
501  return Val.ConstVal->getType();
502}
503
504
505unsigned MachineConstantPoolEntry::getRelocationInfo() const {
506  if (isMachineConstantPoolEntry())
507    return Val.MachineCPVal->getRelocationInfo();
508  return Val.ConstVal->getRelocationInfo();
509}
510
511MachineConstantPool::~MachineConstantPool() {
512  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
513    if (Constants[i].isMachineConstantPoolEntry())
514      delete Constants[i].Val.MachineCPVal;
515}
516
517/// getConstantPoolIndex - Create a new entry in the constant pool or return
518/// an existing one.  User must specify the log2 of the minimum required
519/// alignment for the object.
520///
521unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
522                                                   unsigned Alignment) {
523  assert(Alignment && "Alignment must be specified!");
524  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
525
526  // Check to see if we already have this constant.
527  //
528  // FIXME, this could be made much more efficient for large constant pools.
529  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
530    if (Constants[i].Val.ConstVal == C &&
531        (Constants[i].getAlignment() & (Alignment - 1)) == 0)
532      return i;
533
534  Constants.push_back(MachineConstantPoolEntry(C, Alignment));
535  return Constants.size()-1;
536}
537
538unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
539                                                   unsigned Alignment) {
540  assert(Alignment && "Alignment must be specified!");
541  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
542
543  // Check to see if we already have this constant.
544  //
545  // FIXME, this could be made much more efficient for large constant pools.
546  int Idx = V->getExistingMachineCPValue(this, Alignment);
547  if (Idx != -1)
548    return (unsigned)Idx;
549
550  Constants.push_back(MachineConstantPoolEntry(V, Alignment));
551  return Constants.size()-1;
552}
553
554void MachineConstantPool::print(raw_ostream &OS) const {
555  for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
556    OS << "  <cp#" << i << "> is";
557    if (Constants[i].isMachineConstantPoolEntry())
558      Constants[i].Val.MachineCPVal->print(OS);
559    else
560      OS << *(Value*)Constants[i].Val.ConstVal;
561    OS << " , alignment=" << Constants[i].getAlignment();
562    OS << "\n";
563  }
564}
565
566void MachineConstantPool::dump() const { print(errs()); }
567