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