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