1//===-- llvm/CodeGen/MachineFunction.h --------------------------*- C++ -*-===//
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 for a function.  This class contains a list of
11// MachineBasicBlock instances that make up the current compiled function.
12//
13// This class also contains pointers to various classes which hold
14// target-specific information about the generated code.
15//
16//===----------------------------------------------------------------------===//
17
18#ifndef LLVM_CODEGEN_MACHINEFUNCTION_H
19#define LLVM_CODEGEN_MACHINEFUNCTION_H
20
21#include "llvm/CodeGen/MachineBasicBlock.h"
22#include "llvm/ADT/ilist.h"
23#include "llvm/Support/DebugLoc.h"
24#include "llvm/Support/Allocator.h"
25#include "llvm/Support/Recycler.h"
26
27namespace llvm {
28
29class Value;
30class Function;
31class GCModuleInfo;
32class MachineRegisterInfo;
33class MachineFrameInfo;
34class MachineConstantPool;
35class MachineJumpTableInfo;
36class MachineModuleInfo;
37class MCContext;
38class Pass;
39class TargetMachine;
40class TargetRegisterClass;
41struct MachinePointerInfo;
42
43template <>
44struct ilist_traits<MachineBasicBlock>
45    : public ilist_default_traits<MachineBasicBlock> {
46  mutable ilist_half_node<MachineBasicBlock> Sentinel;
47public:
48  MachineBasicBlock *createSentinel() const {
49    return static_cast<MachineBasicBlock*>(&Sentinel);
50  }
51  void destroySentinel(MachineBasicBlock *) const {}
52
53  MachineBasicBlock *provideInitialHead() const { return createSentinel(); }
54  MachineBasicBlock *ensureHead(MachineBasicBlock*) const {
55    return createSentinel();
56  }
57  static void noteHead(MachineBasicBlock*, MachineBasicBlock*) {}
58
59  void addNodeToList(MachineBasicBlock* MBB);
60  void removeNodeFromList(MachineBasicBlock* MBB);
61  void deleteNode(MachineBasicBlock *MBB);
62private:
63  void createNode(const MachineBasicBlock &);
64};
65
66/// MachineFunctionInfo - This class can be derived from and used by targets to
67/// hold private target-specific information for each MachineFunction.  Objects
68/// of type are accessed/created with MF::getInfo and destroyed when the
69/// MachineFunction is destroyed.
70struct MachineFunctionInfo {
71  virtual ~MachineFunctionInfo();
72};
73
74class MachineFunction {
75  const Function *Fn;
76  const TargetMachine &Target;
77  MCContext &Ctx;
78  MachineModuleInfo &MMI;
79  GCModuleInfo *GMI;
80
81  // RegInfo - Information about each register in use in the function.
82  MachineRegisterInfo *RegInfo;
83
84  // Used to keep track of target-specific per-machine function information for
85  // the target implementation.
86  MachineFunctionInfo *MFInfo;
87
88  // Keep track of objects allocated on the stack.
89  MachineFrameInfo *FrameInfo;
90
91  // Keep track of constants which are spilled to memory
92  MachineConstantPool *ConstantPool;
93
94  // Keep track of jump tables for switch instructions
95  MachineJumpTableInfo *JumpTableInfo;
96
97  // Function-level unique numbering for MachineBasicBlocks.  When a
98  // MachineBasicBlock is inserted into a MachineFunction is it automatically
99  // numbered and this vector keeps track of the mapping from ID's to MBB's.
100  std::vector<MachineBasicBlock*> MBBNumbering;
101
102  // Pool-allocate MachineFunction-lifetime and IR objects.
103  BumpPtrAllocator Allocator;
104
105  // Allocation management for instructions in function.
106  Recycler<MachineInstr> InstructionRecycler;
107
108  // Allocation management for basic blocks in function.
109  Recycler<MachineBasicBlock> BasicBlockRecycler;
110
111  // List of machine basic blocks in function
112  typedef ilist<MachineBasicBlock> BasicBlockListType;
113  BasicBlockListType BasicBlocks;
114
115  /// FunctionNumber - This provides a unique ID for each function emitted in
116  /// this translation unit.
117  ///
118  unsigned FunctionNumber;
119
120  /// Alignment - The alignment of the function.
121  unsigned Alignment;
122
123  /// ExposesReturnsTwice - True if the function calls setjmp or related
124  /// functions with attribute "returns twice", but doesn't have
125  /// the attribute itself.
126  /// This is used to limit optimizations which cannot reason
127  /// about the control flow of such functions.
128  bool ExposesReturnsTwice;
129
130  MachineFunction(const MachineFunction &); // DO NOT IMPLEMENT
131  void operator=(const MachineFunction&);   // DO NOT IMPLEMENT
132public:
133  MachineFunction(const Function *Fn, const TargetMachine &TM,
134                  unsigned FunctionNum, MachineModuleInfo &MMI,
135                  GCModuleInfo* GMI);
136  ~MachineFunction();
137
138  MachineModuleInfo &getMMI() const { return MMI; }
139  GCModuleInfo *getGMI() const { return GMI; }
140  MCContext &getContext() const { return Ctx; }
141
142  /// getFunction - Return the LLVM function that this machine code represents
143  ///
144  const Function *getFunction() const { return Fn; }
145
146  /// getFunctionNumber - Return a unique ID for the current function.
147  ///
148  unsigned getFunctionNumber() const { return FunctionNumber; }
149
150  /// getTarget - Return the target machine this machine code is compiled with
151  ///
152  const TargetMachine &getTarget() const { return Target; }
153
154  /// getRegInfo - Return information about the registers currently in use.
155  ///
156  MachineRegisterInfo &getRegInfo() { return *RegInfo; }
157  const MachineRegisterInfo &getRegInfo() const { return *RegInfo; }
158
159  /// getFrameInfo - Return the frame info object for the current function.
160  /// This object contains information about objects allocated on the stack
161  /// frame of the current function in an abstract way.
162  ///
163  MachineFrameInfo *getFrameInfo() { return FrameInfo; }
164  const MachineFrameInfo *getFrameInfo() const { return FrameInfo; }
165
166  /// getJumpTableInfo - Return the jump table info object for the current
167  /// function.  This object contains information about jump tables in the
168  /// current function.  If the current function has no jump tables, this will
169  /// return null.
170  const MachineJumpTableInfo *getJumpTableInfo() const { return JumpTableInfo; }
171  MachineJumpTableInfo *getJumpTableInfo() { return JumpTableInfo; }
172
173  /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
174  /// does already exist, allocate one.
175  MachineJumpTableInfo *getOrCreateJumpTableInfo(unsigned JTEntryKind);
176
177
178  /// getConstantPool - Return the constant pool object for the current
179  /// function.
180  ///
181  MachineConstantPool *getConstantPool() { return ConstantPool; }
182  const MachineConstantPool *getConstantPool() const { return ConstantPool; }
183
184  /// getAlignment - Return the alignment (log2, not bytes) of the function.
185  ///
186  unsigned getAlignment() const { return Alignment; }
187
188  /// setAlignment - Set the alignment (log2, not bytes) of the function.
189  ///
190  void setAlignment(unsigned A) { Alignment = A; }
191
192  /// EnsureAlignment - Make sure the function is at least 1 << A bytes aligned.
193  void EnsureAlignment(unsigned A) {
194    if (Alignment < A) Alignment = A;
195  }
196
197  /// exposesReturnsTwice - Returns true if the function calls setjmp or
198  /// any other similar functions with attribute "returns twice" without
199  /// having the attribute itself.
200  bool exposesReturnsTwice() const {
201    return ExposesReturnsTwice;
202  }
203
204  /// setCallsSetJmp - Set a flag that indicates if there's a call to
205  /// a "returns twice" function.
206  void setExposesReturnsTwice(bool B) {
207    ExposesReturnsTwice = B;
208  }
209
210  /// getInfo - Keep track of various per-function pieces of information for
211  /// backends that would like to do so.
212  ///
213  template<typename Ty>
214  Ty *getInfo() {
215    if (!MFInfo) {
216        // This should be just `new (Allocator.Allocate<Ty>()) Ty(*this)', but
217        // that apparently breaks GCC 3.3.
218        Ty *Loc = static_cast<Ty*>(Allocator.Allocate(sizeof(Ty),
219                                                      AlignOf<Ty>::Alignment));
220        MFInfo = new (Loc) Ty(*this);
221    }
222    return static_cast<Ty*>(MFInfo);
223  }
224
225  template<typename Ty>
226  const Ty *getInfo() const {
227     return const_cast<MachineFunction*>(this)->getInfo<Ty>();
228  }
229
230  /// getBlockNumbered - MachineBasicBlocks are automatically numbered when they
231  /// are inserted into the machine function.  The block number for a machine
232  /// basic block can be found by using the MBB::getBlockNumber method, this
233  /// method provides the inverse mapping.
234  ///
235  MachineBasicBlock *getBlockNumbered(unsigned N) const {
236    assert(N < MBBNumbering.size() && "Illegal block number");
237    assert(MBBNumbering[N] && "Block was removed from the machine function!");
238    return MBBNumbering[N];
239  }
240
241  /// getNumBlockIDs - Return the number of MBB ID's allocated.
242  ///
243  unsigned getNumBlockIDs() const { return (unsigned)MBBNumbering.size(); }
244
245  /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
246  /// recomputes them.  This guarantees that the MBB numbers are sequential,
247  /// dense, and match the ordering of the blocks within the function.  If a
248  /// specific MachineBasicBlock is specified, only that block and those after
249  /// it are renumbered.
250  void RenumberBlocks(MachineBasicBlock *MBBFrom = 0);
251
252  /// print - Print out the MachineFunction in a format suitable for debugging
253  /// to the specified stream.
254  ///
255  void print(raw_ostream &OS, SlotIndexes* = 0) const;
256
257  /// viewCFG - This function is meant for use from the debugger.  You can just
258  /// say 'call F->viewCFG()' and a ghostview window should pop up from the
259  /// program, displaying the CFG of the current function with the code for each
260  /// basic block inside.  This depends on there being a 'dot' and 'gv' program
261  /// in your path.
262  ///
263  void viewCFG() const;
264
265  /// viewCFGOnly - This function is meant for use from the debugger.  It works
266  /// just like viewCFG, but it does not include the contents of basic blocks
267  /// into the nodes, just the label.  If you are only interested in the CFG
268  /// this can make the graph smaller.
269  ///
270  void viewCFGOnly() const;
271
272  /// dump - Print the current MachineFunction to cerr, useful for debugger use.
273  ///
274  void dump() const;
275
276  /// verify - Run the current MachineFunction through the machine code
277  /// verifier, useful for debugger use.
278  void verify(Pass *p = NULL, const char *Banner = NULL) const;
279
280  // Provide accessors for the MachineBasicBlock list...
281  typedef BasicBlockListType::iterator iterator;
282  typedef BasicBlockListType::const_iterator const_iterator;
283  typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
284  typedef std::reverse_iterator<iterator>             reverse_iterator;
285
286  /// addLiveIn - Add the specified physical register as a live-in value and
287  /// create a corresponding virtual register for it.
288  unsigned addLiveIn(unsigned PReg, const TargetRegisterClass *RC);
289
290  //===--------------------------------------------------------------------===//
291  // BasicBlock accessor functions.
292  //
293  iterator                 begin()       { return BasicBlocks.begin(); }
294  const_iterator           begin() const { return BasicBlocks.begin(); }
295  iterator                 end  ()       { return BasicBlocks.end();   }
296  const_iterator           end  () const { return BasicBlocks.end();   }
297
298  reverse_iterator        rbegin()       { return BasicBlocks.rbegin(); }
299  const_reverse_iterator  rbegin() const { return BasicBlocks.rbegin(); }
300  reverse_iterator        rend  ()       { return BasicBlocks.rend();   }
301  const_reverse_iterator  rend  () const { return BasicBlocks.rend();   }
302
303  unsigned                  size() const { return (unsigned)BasicBlocks.size();}
304  bool                     empty() const { return BasicBlocks.empty(); }
305  const MachineBasicBlock &front() const { return BasicBlocks.front(); }
306        MachineBasicBlock &front()       { return BasicBlocks.front(); }
307  const MachineBasicBlock & back() const { return BasicBlocks.back(); }
308        MachineBasicBlock & back()       { return BasicBlocks.back(); }
309
310  void push_back (MachineBasicBlock *MBB) { BasicBlocks.push_back (MBB); }
311  void push_front(MachineBasicBlock *MBB) { BasicBlocks.push_front(MBB); }
312  void insert(iterator MBBI, MachineBasicBlock *MBB) {
313    BasicBlocks.insert(MBBI, MBB);
314  }
315  void splice(iterator InsertPt, iterator MBBI) {
316    BasicBlocks.splice(InsertPt, BasicBlocks, MBBI);
317  }
318  void splice(iterator InsertPt, iterator MBBI, iterator MBBE) {
319    BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
320  }
321
322  void remove(iterator MBBI) {
323    BasicBlocks.remove(MBBI);
324  }
325  void erase(iterator MBBI) {
326    BasicBlocks.erase(MBBI);
327  }
328
329  //===--------------------------------------------------------------------===//
330  // Internal functions used to automatically number MachineBasicBlocks
331  //
332
333  /// getNextMBBNumber - Returns the next unique number to be assigned
334  /// to a MachineBasicBlock in this MachineFunction.
335  ///
336  unsigned addToMBBNumbering(MachineBasicBlock *MBB) {
337    MBBNumbering.push_back(MBB);
338    return (unsigned)MBBNumbering.size()-1;
339  }
340
341  /// removeFromMBBNumbering - Remove the specific machine basic block from our
342  /// tracker, this is only really to be used by the MachineBasicBlock
343  /// implementation.
344  void removeFromMBBNumbering(unsigned N) {
345    assert(N < MBBNumbering.size() && "Illegal basic block #");
346    MBBNumbering[N] = 0;
347  }
348
349  /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
350  /// of `new MachineInstr'.
351  ///
352  MachineInstr *CreateMachineInstr(const MCInstrDesc &MCID,
353                                   DebugLoc DL,
354                                   bool NoImp = false);
355
356  /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
357  /// 'Orig' instruction, identical in all ways except the instruction
358  /// has no parent, prev, or next.
359  ///
360  /// See also TargetInstrInfo::duplicate() for target-specific fixes to cloned
361  /// instructions.
362  MachineInstr *CloneMachineInstr(const MachineInstr *Orig);
363
364  /// DeleteMachineInstr - Delete the given MachineInstr.
365  ///
366  void DeleteMachineInstr(MachineInstr *MI);
367
368  /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
369  /// instead of `new MachineBasicBlock'.
370  ///
371  MachineBasicBlock *CreateMachineBasicBlock(const BasicBlock *bb = 0);
372
373  /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
374  ///
375  void DeleteMachineBasicBlock(MachineBasicBlock *MBB);
376
377  /// getMachineMemOperand - Allocate a new MachineMemOperand.
378  /// MachineMemOperands are owned by the MachineFunction and need not be
379  /// explicitly deallocated.
380  MachineMemOperand *getMachineMemOperand(MachinePointerInfo PtrInfo,
381                                          unsigned f, uint64_t s,
382                                          unsigned base_alignment,
383                                          const MDNode *TBAAInfo = 0,
384                                          const MDNode *Ranges = 0);
385
386  /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
387  /// an existing one, adjusting by an offset and using the given size.
388  /// MachineMemOperands are owned by the MachineFunction and need not be
389  /// explicitly deallocated.
390  MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
391                                          int64_t Offset, uint64_t Size);
392
393  /// allocateMemRefsArray - Allocate an array to hold MachineMemOperand
394  /// pointers.  This array is owned by the MachineFunction.
395  MachineInstr::mmo_iterator allocateMemRefsArray(unsigned long Num);
396
397  /// extractLoadMemRefs - Allocate an array and populate it with just the
398  /// load information from the given MachineMemOperand sequence.
399  std::pair<MachineInstr::mmo_iterator,
400            MachineInstr::mmo_iterator>
401    extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
402                       MachineInstr::mmo_iterator End);
403
404  /// extractStoreMemRefs - Allocate an array and populate it with just the
405  /// store information from the given MachineMemOperand sequence.
406  std::pair<MachineInstr::mmo_iterator,
407            MachineInstr::mmo_iterator>
408    extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
409                        MachineInstr::mmo_iterator End);
410
411  //===--------------------------------------------------------------------===//
412  // Label Manipulation.
413  //
414
415  /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
416  /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
417  /// normal 'L' label is returned.
418  MCSymbol *getJTISymbol(unsigned JTI, MCContext &Ctx,
419                         bool isLinkerPrivate = false) const;
420
421  /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
422  /// base.
423  MCSymbol *getPICBaseSymbol() const;
424};
425
426//===--------------------------------------------------------------------===//
427// GraphTraits specializations for function basic block graphs (CFGs)
428//===--------------------------------------------------------------------===//
429
430// Provide specializations of GraphTraits to be able to treat a
431// machine function as a graph of machine basic blocks... these are
432// the same as the machine basic block iterators, except that the root
433// node is implicitly the first node of the function.
434//
435template <> struct GraphTraits<MachineFunction*> :
436  public GraphTraits<MachineBasicBlock*> {
437  static NodeType *getEntryNode(MachineFunction *F) {
438    return &F->front();
439  }
440
441  // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
442  typedef MachineFunction::iterator nodes_iterator;
443  static nodes_iterator nodes_begin(MachineFunction *F) { return F->begin(); }
444  static nodes_iterator nodes_end  (MachineFunction *F) { return F->end(); }
445  static unsigned       size       (MachineFunction *F) { return F->size(); }
446};
447template <> struct GraphTraits<const MachineFunction*> :
448  public GraphTraits<const MachineBasicBlock*> {
449  static NodeType *getEntryNode(const MachineFunction *F) {
450    return &F->front();
451  }
452
453  // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
454  typedef MachineFunction::const_iterator nodes_iterator;
455  static nodes_iterator nodes_begin(const MachineFunction *F) {
456    return F->begin();
457  }
458  static nodes_iterator nodes_end  (const MachineFunction *F) {
459    return F->end();
460  }
461  static unsigned       size       (const MachineFunction *F)  {
462    return F->size();
463  }
464};
465
466
467// Provide specializations of GraphTraits to be able to treat a function as a
468// graph of basic blocks... and to walk it in inverse order.  Inverse order for
469// a function is considered to be when traversing the predecessor edges of a BB
470// instead of the successor edges.
471//
472template <> struct GraphTraits<Inverse<MachineFunction*> > :
473  public GraphTraits<Inverse<MachineBasicBlock*> > {
474  static NodeType *getEntryNode(Inverse<MachineFunction*> G) {
475    return &G.Graph->front();
476  }
477};
478template <> struct GraphTraits<Inverse<const MachineFunction*> > :
479  public GraphTraits<Inverse<const MachineBasicBlock*> > {
480  static NodeType *getEntryNode(Inverse<const MachineFunction *> G) {
481    return &G.Graph->front();
482  }
483};
484
485} // End llvm namespace
486
487#endif
488