Factor out LiveIntervalAnalysis' code to determine whether an instruction
[oota-llvm.git] / lib / CodeGen / TargetInstrInfoImpl.cpp
1 //===-- TargetInstrInfoImpl.cpp - Target Instruction Information ----------===//
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 // This file implements the TargetInstrInfoImpl class, it just provides default
11 // implementations of various methods.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Target/TargetInstrInfo.h"
16 #include "llvm/Target/TargetMachine.h"
17 #include "llvm/Target/TargetRegisterInfo.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineMemOperand.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace llvm;
28
29 // commuteInstruction - The default implementation of this method just exchanges
30 // the two operands returned by findCommutedOpIndices.
31 MachineInstr *TargetInstrInfoImpl::commuteInstruction(MachineInstr *MI,
32                                                       bool NewMI) const {
33   const TargetInstrDesc &TID = MI->getDesc();
34   bool HasDef = TID.getNumDefs();
35   if (HasDef && !MI->getOperand(0).isReg())
36     // No idea how to commute this instruction. Target should implement its own.
37     return 0;
38   unsigned Idx1, Idx2;
39   if (!findCommutedOpIndices(MI, Idx1, Idx2)) {
40     std::string msg;
41     raw_string_ostream Msg(msg);
42     Msg << "Don't know how to commute: " << *MI;
43     llvm_report_error(Msg.str());
44   }
45
46   assert(MI->getOperand(Idx1).isReg() && MI->getOperand(Idx2).isReg() &&
47          "This only knows how to commute register operands so far");
48   unsigned Reg1 = MI->getOperand(Idx1).getReg();
49   unsigned Reg2 = MI->getOperand(Idx2).getReg();
50   bool Reg1IsKill = MI->getOperand(Idx1).isKill();
51   bool Reg2IsKill = MI->getOperand(Idx2).isKill();
52   bool ChangeReg0 = false;
53   if (HasDef && MI->getOperand(0).getReg() == Reg1) {
54     // Must be two address instruction!
55     assert(MI->getDesc().getOperandConstraint(0, TOI::TIED_TO) &&
56            "Expecting a two-address instruction!");
57     Reg2IsKill = false;
58     ChangeReg0 = true;
59   }
60
61   if (NewMI) {
62     // Create a new instruction.
63     unsigned Reg0 = HasDef
64       ? (ChangeReg0 ? Reg2 : MI->getOperand(0).getReg()) : 0;
65     bool Reg0IsDead = HasDef ? MI->getOperand(0).isDead() : false;
66     MachineFunction &MF = *MI->getParent()->getParent();
67     if (HasDef)
68       return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
69         .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
70         .addReg(Reg2, getKillRegState(Reg2IsKill))
71         .addReg(Reg1, getKillRegState(Reg2IsKill));
72     else
73       return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
74         .addReg(Reg2, getKillRegState(Reg2IsKill))
75         .addReg(Reg1, getKillRegState(Reg2IsKill));
76   }
77
78   if (ChangeReg0)
79     MI->getOperand(0).setReg(Reg2);
80   MI->getOperand(Idx2).setReg(Reg1);
81   MI->getOperand(Idx1).setReg(Reg2);
82   MI->getOperand(Idx2).setIsKill(Reg1IsKill);
83   MI->getOperand(Idx1).setIsKill(Reg2IsKill);
84   return MI;
85 }
86
87 /// findCommutedOpIndices - If specified MI is commutable, return the two
88 /// operand indices that would swap value. Return true if the instruction
89 /// is not in a form which this routine understands.
90 bool TargetInstrInfoImpl::findCommutedOpIndices(MachineInstr *MI,
91                                                 unsigned &SrcOpIdx1,
92                                                 unsigned &SrcOpIdx2) const {
93   const TargetInstrDesc &TID = MI->getDesc();
94   if (!TID.isCommutable())
95     return false;
96   // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
97   // is not true, then the target must implement this.
98   SrcOpIdx1 = TID.getNumDefs();
99   SrcOpIdx2 = SrcOpIdx1 + 1;
100   if (!MI->getOperand(SrcOpIdx1).isReg() ||
101       !MI->getOperand(SrcOpIdx2).isReg())
102     // No idea.
103     return false;
104   return true;
105 }
106
107
108 bool TargetInstrInfoImpl::PredicateInstruction(MachineInstr *MI,
109                             const SmallVectorImpl<MachineOperand> &Pred) const {
110   bool MadeChange = false;
111   const TargetInstrDesc &TID = MI->getDesc();
112   if (!TID.isPredicable())
113     return false;
114   
115   for (unsigned j = 0, i = 0, e = MI->getNumOperands(); i != e; ++i) {
116     if (TID.OpInfo[i].isPredicate()) {
117       MachineOperand &MO = MI->getOperand(i);
118       if (MO.isReg()) {
119         MO.setReg(Pred[j].getReg());
120         MadeChange = true;
121       } else if (MO.isImm()) {
122         MO.setImm(Pred[j].getImm());
123         MadeChange = true;
124       } else if (MO.isMBB()) {
125         MO.setMBB(Pred[j].getMBB());
126         MadeChange = true;
127       }
128       ++j;
129     }
130   }
131   return MadeChange;
132 }
133
134 void TargetInstrInfoImpl::reMaterialize(MachineBasicBlock &MBB,
135                                         MachineBasicBlock::iterator I,
136                                         unsigned DestReg,
137                                         unsigned SubIdx,
138                                         const MachineInstr *Orig) const {
139   MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
140   MachineOperand &MO = MI->getOperand(0);
141   MO.setReg(DestReg);
142   MO.setSubReg(SubIdx);
143   MBB.insert(I, MI);
144 }
145
146 bool TargetInstrInfoImpl::isDeadInstruction(const MachineInstr *MI) const {
147   const TargetInstrDesc &TID = MI->getDesc();
148   if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
149       TID.isCall() || TID.isBarrier() || TID.isReturn() ||
150       TID.hasUnmodeledSideEffects())
151     return false;
152   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
153     const MachineOperand &MO = MI->getOperand(i);
154     if (!MO.isReg() || !MO.getReg())
155       continue;
156     if (MO.isDef() && !MO.isDead())
157       return false;
158     if (MO.isUse() && MO.isKill())
159       // FIXME: We can't remove kill markers or else the scavenger will assert.
160       // An alternative is to add a ADD pseudo instruction to replace kill
161       // markers.
162       return false;
163   }
164   return true;
165 }
166
167 unsigned
168 TargetInstrInfoImpl::GetFunctionSizeInBytes(const MachineFunction &MF) const {
169   unsigned FnSize = 0;
170   for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
171        MBBI != E; ++MBBI) {
172     const MachineBasicBlock &MBB = *MBBI;
173     for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
174          I != E; ++I)
175       FnSize += GetInstSizeInBytes(I);
176   }
177   return FnSize;
178 }
179
180 /// foldMemoryOperand - Attempt to fold a load or store of the specified stack
181 /// slot into the specified machine instruction for the specified operand(s).
182 /// If this is possible, a new instruction is returned with the specified
183 /// operand folded, otherwise NULL is returned. The client is responsible for
184 /// removing the old instruction and adding the new one in the instruction
185 /// stream.
186 MachineInstr*
187 TargetInstrInfo::foldMemoryOperand(MachineFunction &MF,
188                                    MachineInstr* MI,
189                                    const SmallVectorImpl<unsigned> &Ops,
190                                    int FrameIndex) const {
191   unsigned Flags = 0;
192   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
193     if (MI->getOperand(Ops[i]).isDef())
194       Flags |= MachineMemOperand::MOStore;
195     else
196       Flags |= MachineMemOperand::MOLoad;
197
198   // Ask the target to do the actual folding.
199   MachineInstr *NewMI = foldMemoryOperandImpl(MF, MI, Ops, FrameIndex);
200   if (!NewMI) return 0;
201
202   assert((!(Flags & MachineMemOperand::MOStore) ||
203           NewMI->getDesc().mayStore()) &&
204          "Folded a def to a non-store!");
205   assert((!(Flags & MachineMemOperand::MOLoad) ||
206           NewMI->getDesc().mayLoad()) &&
207          "Folded a use to a non-load!");
208   const MachineFrameInfo &MFI = *MF.getFrameInfo();
209   assert(MFI.getObjectOffset(FrameIndex) != -1);
210   MachineMemOperand *MMO =
211     MF.getMachineMemOperand(PseudoSourceValue::getFixedStack(FrameIndex),
212                             Flags, /*Offset=*/0,
213                             MFI.getObjectSize(FrameIndex),
214                             MFI.getObjectAlignment(FrameIndex));
215   NewMI->addMemOperand(MF, MMO);
216
217   return NewMI;
218 }
219
220 /// foldMemoryOperand - Same as the previous version except it allows folding
221 /// of any load and store from / to any address, not just from a specific
222 /// stack slot.
223 MachineInstr*
224 TargetInstrInfo::foldMemoryOperand(MachineFunction &MF,
225                                    MachineInstr* MI,
226                                    const SmallVectorImpl<unsigned> &Ops,
227                                    MachineInstr* LoadMI) const {
228   assert(LoadMI->getDesc().canFoldAsLoad() && "LoadMI isn't foldable!");
229 #ifndef NDEBUG
230   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
231     assert(MI->getOperand(Ops[i]).isUse() && "Folding load into def!");
232 #endif
233
234   // Ask the target to do the actual folding.
235   MachineInstr *NewMI = foldMemoryOperandImpl(MF, MI, Ops, LoadMI);
236   if (!NewMI) return 0;
237
238   // Copy the memoperands from the load to the folded instruction.
239   NewMI->setMemRefs(LoadMI->memoperands_begin(),
240                     LoadMI->memoperands_end());
241
242   return NewMI;
243 }
244
245 bool
246 TargetInstrInfo::isReallyTriviallyReMaterializableGeneric(const MachineInstr *
247                                                             MI,
248                                                           AliasAnalysis *
249                                                             AA) const {
250   const MachineFunction &MF = *MI->getParent()->getParent();
251   const MachineRegisterInfo &MRI = MF.getRegInfo();
252   const TargetMachine &TM = MF.getTarget();
253   const TargetInstrInfo &TII = *TM.getInstrInfo();
254   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
255
256   // A load from a fixed stack slot can be rematerialized. This may be
257   // redundant with subsequent checks, but it's target-independent,
258   // simple, and a common case.
259   int FrameIdx = 0;
260   if (TII.isLoadFromStackSlot(MI, FrameIdx) &&
261       MF.getFrameInfo()->isImmutableObjectIndex(FrameIdx))
262     return true;
263
264   const TargetInstrDesc &TID = MI->getDesc();
265
266   // Avoid instructions obviously unsafe for remat.
267   if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable() ||
268       TID.mayStore())
269     return false;
270
271   // Avoid instructions which load from potentially varying memory.
272   if (TID.mayLoad() && !MI->isInvariantLoad(AA))
273     return false;
274
275   // If any of the registers accessed are non-constant, conservatively assume
276   // the instruction is not rematerializable.
277   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
278     const MachineOperand &MO = MI->getOperand(i);
279     if (!MO.isReg()) continue;
280     unsigned Reg = MO.getReg();
281     if (Reg == 0)
282       continue;
283
284     // Check for a well-behaved physical register.
285     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
286       if (MO.isUse()) {
287         // If the physreg has no defs anywhere, it's just an ambient register
288         // and we can freely move its uses. Alternatively, if it's allocatable,
289         // it could get allocated to something with a def during allocation.
290         if (!MRI.def_empty(Reg))
291           return false;
292         BitVector AllocatableRegs = TRI.getAllocatableSet(MF, 0);
293         if (AllocatableRegs.test(Reg))
294           return false;
295         // Check for a def among the register's aliases too.
296         for (const unsigned *Alias = TRI.getAliasSet(Reg); *Alias; ++Alias) {
297           unsigned AliasReg = *Alias;
298           if (!MRI.def_empty(AliasReg))
299             return false;
300           if (AllocatableRegs.test(AliasReg))
301             return false;
302         }
303       } else {
304         // A physreg def. We can't remat it.
305         return false;
306       }
307       continue;
308     }
309
310     // Only allow one virtual-register def, and that in the first operand.
311     if (MO.isDef() != (i == 0))
312       return false;
313
314     // For the def, it should be the only def of that register.
315     if (MO.isDef() && (next(MRI.def_begin(Reg)) != MRI.def_end() ||
316                        MRI.isLiveIn(Reg)))
317       return false;
318
319     // Don't allow any virtual-register uses. Rematting an instruction with
320     // virtual register uses would length the live ranges of the uses, which
321     // is not necessarily a good idea, certainly not "trivial".
322     if (MO.isUse())
323       return false;
324   }
325
326   // Everything checked out.
327   return true;
328 }