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