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 &) LLVM_DELETED_FUNCTION;
131  void operator=(const MachineFunction&) LLVM_DELETED_FUNCTION;
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  /// getName - Return the name of the corresponding LLVM function.
147  ///
148  StringRef getName() const;
149
150  /// getFunctionNumber - Return a unique ID for the current function.
151  ///
152  unsigned getFunctionNumber() const { return FunctionNumber; }
153
154  /// getTarget - Return the target machine this machine code is compiled with
155  ///
156  const TargetMachine &getTarget() const { return Target; }
157
158  /// getRegInfo - Return information about the registers currently in use.
159  ///
160  MachineRegisterInfo &getRegInfo() { return *RegInfo; }
161  const MachineRegisterInfo &getRegInfo() const { return *RegInfo; }
162
163  /// getFrameInfo - Return the frame info object for the current function.
164  /// This object contains information about objects allocated on the stack
165  /// frame of the current function in an abstract way.
166  ///
167  MachineFrameInfo *getFrameInfo() { return FrameInfo; }
168  const MachineFrameInfo *getFrameInfo() const { return FrameInfo; }
169
170  /// getJumpTableInfo - Return the jump table info object for the current
171  /// function.  This object contains information about jump tables in the
172  /// current function.  If the current function has no jump tables, this will
173  /// return null.
174  const MachineJumpTableInfo *getJumpTableInfo() const { return JumpTableInfo; }
175  MachineJumpTableInfo *getJumpTableInfo() { return JumpTableInfo; }
176
177  /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
178  /// does already exist, allocate one.
179  MachineJumpTableInfo *getOrCreateJumpTableInfo(unsigned JTEntryKind);
180
181
182  /// getConstantPool - Return the constant pool object for the current
183  /// function.
184  ///
185  MachineConstantPool *getConstantPool() { return ConstantPool; }
186  const MachineConstantPool *getConstantPool() const { return ConstantPool; }
187
188  /// getAlignment - Return the alignment (log2, not bytes) of the function.
189  ///
190  unsigned getAlignment() const { return Alignment; }
191
192  /// setAlignment - Set the alignment (log2, not bytes) of the function.
193  ///
194  void setAlignment(unsigned A) { Alignment = A; }
195
196  /// ensureAlignment - Make sure the function is at least 1 << A bytes aligned.
197  void ensureAlignment(unsigned A) {
198    if (Alignment < A) Alignment = A;
199  }
200
201  /// exposesReturnsTwice - Returns true if the function calls setjmp or
202  /// any other similar functions with attribute "returns twice" without
203  /// having the attribute itself.
204  bool exposesReturnsTwice() const {
205    return ExposesReturnsTwice;
206  }
207
208  /// setCallsSetJmp - Set a flag that indicates if there's a call to
209  /// a "returns twice" function.
210  void setExposesReturnsTwice(bool B) {
211    ExposesReturnsTwice = B;
212  }
213
214  /// getInfo - Keep track of various per-function pieces of information for
215  /// backends that would like to do so.
216  ///
217  template<typename Ty>
218  Ty *getInfo() {
219    if (!MFInfo) {
220        // This should be just `new (Allocator.Allocate<Ty>()) Ty(*this)', but
221        // that apparently breaks GCC 3.3.
222        Ty *Loc = static_cast<Ty*>(Allocator.Allocate(sizeof(Ty),
223                                                      AlignOf<Ty>::Alignment));
224        MFInfo = new (Loc) Ty(*this);
225    }
226    return static_cast<Ty*>(MFInfo);
227  }
228
229  template<typename Ty>
230  const Ty *getInfo() const {
231     return const_cast<MachineFunction*>(this)->getInfo<Ty>();
232  }
233
234  /// getBlockNumbered - MachineBasicBlocks are automatically numbered when they
235  /// are inserted into the machine function.  The block number for a machine
236  /// basic block can be found by using the MBB::getBlockNumber method, this
237  /// method provides the inverse mapping.
238  ///
239  MachineBasicBlock *getBlockNumbered(unsigned N) const {
240    assert(N < MBBNumbering.size() && "Illegal block number");
241    assert(MBBNumbering[N] && "Block was removed from the machine function!");
242    return MBBNumbering[N];
243  }
244
245  /// getNumBlockIDs - Return the number of MBB ID's allocated.
246  ///
247  unsigned getNumBlockIDs() const { return (unsigned)MBBNumbering.size(); }
248
249  /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
250  /// recomputes them.  This guarantees that the MBB numbers are sequential,
251  /// dense, and match the ordering of the blocks within the function.  If a
252  /// specific MachineBasicBlock is specified, only that block and those after
253  /// it are renumbered.
254  void RenumberBlocks(MachineBasicBlock *MBBFrom = 0);
255
256  /// print - Print out the MachineFunction in a format suitable for debugging
257  /// to the specified stream.
258  ///
259  void print(raw_ostream &OS, SlotIndexes* = 0) const;
260
261  /// viewCFG - This function is meant for use from the debugger.  You can just
262  /// say 'call F->viewCFG()' and a ghostview window should pop up from the
263  /// program, displaying the CFG of the current function with the code for each
264  /// basic block inside.  This depends on there being a 'dot' and 'gv' program
265  /// in your path.
266  ///
267  void viewCFG() const;
268
269  /// viewCFGOnly - This function is meant for use from the debugger.  It works
270  /// just like viewCFG, but it does not include the contents of basic blocks
271  /// into the nodes, just the label.  If you are only interested in the CFG
272  /// this can make the graph smaller.
273  ///
274  void viewCFGOnly() const;
275
276  /// dump - Print the current MachineFunction to cerr, useful for debugger use.
277  ///
278  void dump() const;
279
280  /// verify - Run the current MachineFunction through the machine code
281  /// verifier, useful for debugger use.
282  void verify(Pass *p = NULL, const char *Banner = NULL) const;
283
284  // Provide accessors for the MachineBasicBlock list...
285  typedef BasicBlockListType::iterator iterator;
286  typedef BasicBlockListType::const_iterator const_iterator;
287  typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
288  typedef std::reverse_iterator<iterator>             reverse_iterator;
289
290  /// addLiveIn - Add the specified physical register as a live-in value and
291  /// create a corresponding virtual register for it.
292  unsigned addLiveIn(unsigned PReg, const TargetRegisterClass *RC);
293
294  //===--------------------------------------------------------------------===//
295  // BasicBlock accessor functions.
296  //
297  iterator                 begin()       { return BasicBlocks.begin(); }
298  const_iterator           begin() const { return BasicBlocks.begin(); }
299  iterator                 end  ()       { return BasicBlocks.end();   }
300  const_iterator           end  () const { return BasicBlocks.end();   }
301
302  reverse_iterator        rbegin()       { return BasicBlocks.rbegin(); }
303  const_reverse_iterator  rbegin() const { return BasicBlocks.rbegin(); }
304  reverse_iterator        rend  ()       { return BasicBlocks.rend();   }
305  const_reverse_iterator  rend  () const { return BasicBlocks.rend();   }
306
307  unsigned                  size() const { return (unsigned)BasicBlocks.size();}
308  bool                     empty() const { return BasicBlocks.empty(); }
309  const MachineBasicBlock &front() const { return BasicBlocks.front(); }
310        MachineBasicBlock &front()       { return BasicBlocks.front(); }
311  const MachineBasicBlock & back() const { return BasicBlocks.back(); }
312        MachineBasicBlock & back()       { return BasicBlocks.back(); }
313
314  void push_back (MachineBasicBlock *MBB) { BasicBlocks.push_back (MBB); }
315  void push_front(MachineBasicBlock *MBB) { BasicBlocks.push_front(MBB); }
316  void insert(iterator MBBI, MachineBasicBlock *MBB) {
317    BasicBlocks.insert(MBBI, MBB);
318  }
319  void splice(iterator InsertPt, iterator MBBI) {
320    BasicBlocks.splice(InsertPt, BasicBlocks, MBBI);
321  }
322  void splice(iterator InsertPt, iterator MBBI, iterator MBBE) {
323    BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
324  }
325
326  void remove(iterator MBBI) {
327    BasicBlocks.remove(MBBI);
328  }
329  void erase(iterator MBBI) {
330    BasicBlocks.erase(MBBI);
331  }
332
333  //===--------------------------------------------------------------------===//
334  // Internal functions used to automatically number MachineBasicBlocks
335  //
336
337  /// getNextMBBNumber - Returns the next unique number to be assigned
338  /// to a MachineBasicBlock in this MachineFunction.
339  ///
340  unsigned addToMBBNumbering(MachineBasicBlock *MBB) {
341    MBBNumbering.push_back(MBB);
342    return (unsigned)MBBNumbering.size()-1;
343  }
344
345  /// removeFromMBBNumbering - Remove the specific machine basic block from our
346  /// tracker, this is only really to be used by the MachineBasicBlock
347  /// implementation.
348  void removeFromMBBNumbering(unsigned N) {
349    assert(N < MBBNumbering.size() && "Illegal basic block #");
350    MBBNumbering[N] = 0;
351  }
352
353  /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
354  /// of `new MachineInstr'.
355  ///
356  MachineInstr *CreateMachineInstr(const MCInstrDesc &MCID,
357                                   DebugLoc DL,
358                                   bool NoImp = false);
359
360  /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
361  /// 'Orig' instruction, identical in all ways except the instruction
362  /// has no parent, prev, or next.
363  ///
364  /// See also TargetInstrInfo::duplicate() for target-specific fixes to cloned
365  /// instructions.
366  MachineInstr *CloneMachineInstr(const MachineInstr *Orig);
367
368  /// DeleteMachineInstr - Delete the given MachineInstr.
369  ///
370  void DeleteMachineInstr(MachineInstr *MI);
371
372  /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
373  /// instead of `new MachineBasicBlock'.
374  ///
375  MachineBasicBlock *CreateMachineBasicBlock(const BasicBlock *bb = 0);
376
377  /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
378  ///
379  void DeleteMachineBasicBlock(MachineBasicBlock *MBB);
380
381  /// getMachineMemOperand - Allocate a new MachineMemOperand.
382  /// MachineMemOperands are owned by the MachineFunction and need not be
383  /// explicitly deallocated.
384  MachineMemOperand *getMachineMemOperand(MachinePointerInfo PtrInfo,
385                                          unsigned f, uint64_t s,
386                                          unsigned base_alignment,
387                                          const MDNode *TBAAInfo = 0,
388                                          const MDNode *Ranges = 0);
389
390  /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
391  /// an existing one, adjusting by an offset and using the given size.
392  /// MachineMemOperands are owned by the MachineFunction and need not be
393  /// explicitly deallocated.
394  MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
395                                          int64_t Offset, uint64_t Size);
396
397  /// allocateMemRefsArray - Allocate an array to hold MachineMemOperand
398  /// pointers.  This array is owned by the MachineFunction.
399  MachineInstr::mmo_iterator allocateMemRefsArray(unsigned long Num);
400
401  /// extractLoadMemRefs - Allocate an array and populate it with just the
402  /// load information from the given MachineMemOperand sequence.
403  std::pair<MachineInstr::mmo_iterator,
404            MachineInstr::mmo_iterator>
405    extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
406                       MachineInstr::mmo_iterator End);
407
408  /// extractStoreMemRefs - Allocate an array and populate it with just the
409  /// store information from the given MachineMemOperand sequence.
410  std::pair<MachineInstr::mmo_iterator,
411            MachineInstr::mmo_iterator>
412    extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
413                        MachineInstr::mmo_iterator End);
414
415  //===--------------------------------------------------------------------===//
416  // Label Manipulation.
417  //
418
419  /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
420  /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
421  /// normal 'L' label is returned.
422  MCSymbol *getJTISymbol(unsigned JTI, MCContext &Ctx,
423                         bool isLinkerPrivate = false) const;
424
425  /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
426  /// base.
427  MCSymbol *getPICBaseSymbol() const;
428};
429
430//===--------------------------------------------------------------------===//
431// GraphTraits specializations for function basic block graphs (CFGs)
432//===--------------------------------------------------------------------===//
433
434// Provide specializations of GraphTraits to be able to treat a
435// machine function as a graph of machine basic blocks... these are
436// the same as the machine basic block iterators, except that the root
437// node is implicitly the first node of the function.
438//
439template <> struct GraphTraits<MachineFunction*> :
440  public GraphTraits<MachineBasicBlock*> {
441  static NodeType *getEntryNode(MachineFunction *F) {
442    return &F->front();
443  }
444
445  // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
446  typedef MachineFunction::iterator nodes_iterator;
447  static nodes_iterator nodes_begin(MachineFunction *F) { return F->begin(); }
448  static nodes_iterator nodes_end  (MachineFunction *F) { return F->end(); }
449  static unsigned       size       (MachineFunction *F) { return F->size(); }
450};
451template <> struct GraphTraits<const MachineFunction*> :
452  public GraphTraits<const MachineBasicBlock*> {
453  static NodeType *getEntryNode(const MachineFunction *F) {
454    return &F->front();
455  }
456
457  // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
458  typedef MachineFunction::const_iterator nodes_iterator;
459  static nodes_iterator nodes_begin(const MachineFunction *F) {
460    return F->begin();
461  }
462  static nodes_iterator nodes_end  (const MachineFunction *F) {
463    return F->end();
464  }
465  static unsigned       size       (const MachineFunction *F)  {
466    return F->size();
467  }
468};
469
470
471// Provide specializations of GraphTraits to be able to treat a function as a
472// graph of basic blocks... and to walk it in inverse order.  Inverse order for
473// a function is considered to be when traversing the predecessor edges of a BB
474// instead of the successor edges.
475//
476template <> struct GraphTraits<Inverse<MachineFunction*> > :
477  public GraphTraits<Inverse<MachineBasicBlock*> > {
478  static NodeType *getEntryNode(Inverse<MachineFunction*> G) {
479    return &G.Graph->front();
480  }
481};
482template <> struct GraphTraits<Inverse<const MachineFunction*> > :
483  public GraphTraits<Inverse<const MachineBasicBlock*> > {
484  static NodeType *getEntryNode(Inverse<const MachineFunction *> G) {
485    return &G.Graph->front();
486  }
487};
488
489} // End llvm namespace
490
491#endif
492