Reduce indentation and fix the count of how many PHIs we have inserted.
[oota-llvm.git] / lib / CodeGen / MachineInstr.cpp
1 //===-- lib/CodeGen/MachineInstr.cpp --------------------------------------===//
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 // Methods common to all machine instructions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Function.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Metadata.h"
20 #include "llvm/Module.h"
21 #include "llvm/Type.h"
22 #include "llvm/Value.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineMemOperand.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/DebugInfo.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/LeakDetector.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/ADT/FoldingSet.h"
43 using namespace llvm;
44
45 //===----------------------------------------------------------------------===//
46 // MachineOperand Implementation
47 //===----------------------------------------------------------------------===//
48
49 /// AddRegOperandToRegInfo - Add this register operand to the specified
50 /// MachineRegisterInfo.  If it is null, then the next/prev fields should be
51 /// explicitly nulled out.
52 void MachineOperand::AddRegOperandToRegInfo(MachineRegisterInfo *RegInfo) {
53   assert(isReg() && "Can only add reg operand to use lists");
54   
55   // If the reginfo pointer is null, just explicitly null out or next/prev
56   // pointers, to ensure they are not garbage.
57   if (RegInfo == 0) {
58     Contents.Reg.Prev = 0;
59     Contents.Reg.Next = 0;
60     return;
61   }
62   
63   // Otherwise, add this operand to the head of the registers use/def list.
64   MachineOperand **Head = &RegInfo->getRegUseDefListHead(getReg());
65   
66   // For SSA values, we prefer to keep the definition at the start of the list.
67   // we do this by skipping over the definition if it is at the head of the
68   // list.
69   if (*Head && (*Head)->isDef())
70     Head = &(*Head)->Contents.Reg.Next;
71   
72   Contents.Reg.Next = *Head;
73   if (Contents.Reg.Next) {
74     assert(getReg() == Contents.Reg.Next->getReg() &&
75            "Different regs on the same list!");
76     Contents.Reg.Next->Contents.Reg.Prev = &Contents.Reg.Next;
77   }
78   
79   Contents.Reg.Prev = Head;
80   *Head = this;
81 }
82
83 /// RemoveRegOperandFromRegInfo - Remove this register operand from the
84 /// MachineRegisterInfo it is linked with.
85 void MachineOperand::RemoveRegOperandFromRegInfo() {
86   assert(isOnRegUseList() && "Reg operand is not on a use list");
87   // Unlink this from the doubly linked list of operands.
88   MachineOperand *NextOp = Contents.Reg.Next;
89   *Contents.Reg.Prev = NextOp; 
90   if (NextOp) {
91     assert(NextOp->getReg() == getReg() && "Corrupt reg use/def chain!");
92     NextOp->Contents.Reg.Prev = Contents.Reg.Prev;
93   }
94   Contents.Reg.Prev = 0;
95   Contents.Reg.Next = 0;
96 }
97
98 void MachineOperand::setReg(unsigned Reg) {
99   if (getReg() == Reg) return; // No change.
100   
101   // Otherwise, we have to change the register.  If this operand is embedded
102   // into a machine function, we need to update the old and new register's
103   // use/def lists.
104   if (MachineInstr *MI = getParent())
105     if (MachineBasicBlock *MBB = MI->getParent())
106       if (MachineFunction *MF = MBB->getParent()) {
107         RemoveRegOperandFromRegInfo();
108         SmallContents.RegNo = Reg;
109         AddRegOperandToRegInfo(&MF->getRegInfo());
110         return;
111       }
112         
113   // Otherwise, just change the register, no problem.  :)
114   SmallContents.RegNo = Reg;
115 }
116
117 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
118                                   const TargetRegisterInfo &TRI) {
119   assert(TargetRegisterInfo::isVirtualRegister(Reg));
120   if (SubIdx && getSubReg())
121     SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
122   setReg(Reg);
123   if (SubIdx)
124     setSubReg(SubIdx);
125 }
126
127 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
128   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
129   if (getSubReg()) {
130     Reg = TRI.getSubReg(Reg, getSubReg());
131     // Note that getSubReg() may return 0 if the sub-register doesn't exist.
132     // That won't happen in legal code.
133     setSubReg(0);
134   }
135   setReg(Reg);
136 }
137
138 /// ChangeToImmediate - Replace this operand with a new immediate operand of
139 /// the specified value.  If an operand is known to be an immediate already,
140 /// the setImm method should be used.
141 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
142   // If this operand is currently a register operand, and if this is in a
143   // function, deregister the operand from the register's use/def list.
144   if (isReg() && getParent() && getParent()->getParent() &&
145       getParent()->getParent()->getParent())
146     RemoveRegOperandFromRegInfo();
147   
148   OpKind = MO_Immediate;
149   Contents.ImmVal = ImmVal;
150 }
151
152 /// ChangeToRegister - Replace this operand with a new register operand of
153 /// the specified value.  If an operand is known to be an register already,
154 /// the setReg method should be used.
155 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
156                                       bool isKill, bool isDead, bool isUndef,
157                                       bool isDebug) {
158   // If this operand is already a register operand, use setReg to update the 
159   // register's use/def lists.
160   if (isReg()) {
161     assert(!isEarlyClobber());
162     setReg(Reg);
163   } else {
164     // Otherwise, change this to a register and set the reg#.
165     OpKind = MO_Register;
166     SmallContents.RegNo = Reg;
167
168     // If this operand is embedded in a function, add the operand to the
169     // register's use/def list.
170     if (MachineInstr *MI = getParent())
171       if (MachineBasicBlock *MBB = MI->getParent())
172         if (MachineFunction *MF = MBB->getParent())
173           AddRegOperandToRegInfo(&MF->getRegInfo());
174   }
175
176   IsDef = isDef;
177   IsImp = isImp;
178   IsKill = isKill;
179   IsDead = isDead;
180   IsUndef = isUndef;
181   IsEarlyClobber = false;
182   IsDebug = isDebug;
183   SubReg = 0;
184 }
185
186 /// isIdenticalTo - Return true if this operand is identical to the specified
187 /// operand.
188 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
189   if (getType() != Other.getType() ||
190       getTargetFlags() != Other.getTargetFlags())
191     return false;
192   
193   switch (getType()) {
194   default: llvm_unreachable("Unrecognized operand type");
195   case MachineOperand::MO_Register:
196     return getReg() == Other.getReg() && isDef() == Other.isDef() &&
197            getSubReg() == Other.getSubReg();
198   case MachineOperand::MO_Immediate:
199     return getImm() == Other.getImm();
200   case MachineOperand::MO_CImmediate:
201     return getCImm() == Other.getCImm();
202   case MachineOperand::MO_FPImmediate:
203     return getFPImm() == Other.getFPImm();
204   case MachineOperand::MO_MachineBasicBlock:
205     return getMBB() == Other.getMBB();
206   case MachineOperand::MO_FrameIndex:
207     return getIndex() == Other.getIndex();
208   case MachineOperand::MO_ConstantPoolIndex:
209     return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
210   case MachineOperand::MO_JumpTableIndex:
211     return getIndex() == Other.getIndex();
212   case MachineOperand::MO_GlobalAddress:
213     return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
214   case MachineOperand::MO_ExternalSymbol:
215     return !strcmp(getSymbolName(), Other.getSymbolName()) &&
216            getOffset() == Other.getOffset();
217   case MachineOperand::MO_BlockAddress:
218     return getBlockAddress() == Other.getBlockAddress();
219   case MachineOperand::MO_MCSymbol:
220     return getMCSymbol() == Other.getMCSymbol();
221   case MachineOperand::MO_Metadata:
222     return getMetadata() == Other.getMetadata();
223   }
224 }
225
226 /// print - Print the specified machine operand.
227 ///
228 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
229   // If the instruction is embedded into a basic block, we can find the
230   // target info for the instruction.
231   if (!TM)
232     if (const MachineInstr *MI = getParent())
233       if (const MachineBasicBlock *MBB = MI->getParent())
234         if (const MachineFunction *MF = MBB->getParent())
235           TM = &MF->getTarget();
236   const TargetRegisterInfo *TRI = TM ? TM->getRegisterInfo() : 0;
237
238   switch (getType()) {
239   case MachineOperand::MO_Register:
240     OS << PrintReg(getReg(), TRI, getSubReg());
241
242     if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
243         isEarlyClobber()) {
244       OS << '<';
245       bool NeedComma = false;
246       if (isDef()) {
247         if (NeedComma) OS << ',';
248         if (isEarlyClobber())
249           OS << "earlyclobber,";
250         if (isImplicit())
251           OS << "imp-";
252         OS << "def";
253         NeedComma = true;
254       } else if (isImplicit()) {
255           OS << "imp-use";
256           NeedComma = true;
257       }
258
259       if (isKill() || isDead() || isUndef()) {
260         if (NeedComma) OS << ',';
261         if (isKill())  OS << "kill";
262         if (isDead())  OS << "dead";
263         if (isUndef()) {
264           if (isKill() || isDead())
265             OS << ',';
266           OS << "undef";
267         }
268       }
269       OS << '>';
270     }
271     break;
272   case MachineOperand::MO_Immediate:
273     OS << getImm();
274     break;
275   case MachineOperand::MO_CImmediate:
276     getCImm()->getValue().print(OS, false);
277     break;
278   case MachineOperand::MO_FPImmediate:
279     if (getFPImm()->getType()->isFloatTy())
280       OS << getFPImm()->getValueAPF().convertToFloat();
281     else
282       OS << getFPImm()->getValueAPF().convertToDouble();
283     break;
284   case MachineOperand::MO_MachineBasicBlock:
285     OS << "<BB#" << getMBB()->getNumber() << ">";
286     break;
287   case MachineOperand::MO_FrameIndex:
288     OS << "<fi#" << getIndex() << '>';
289     break;
290   case MachineOperand::MO_ConstantPoolIndex:
291     OS << "<cp#" << getIndex();
292     if (getOffset()) OS << "+" << getOffset();
293     OS << '>';
294     break;
295   case MachineOperand::MO_JumpTableIndex:
296     OS << "<jt#" << getIndex() << '>';
297     break;
298   case MachineOperand::MO_GlobalAddress:
299     OS << "<ga:";
300     WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
301     if (getOffset()) OS << "+" << getOffset();
302     OS << '>';
303     break;
304   case MachineOperand::MO_ExternalSymbol:
305     OS << "<es:" << getSymbolName();
306     if (getOffset()) OS << "+" << getOffset();
307     OS << '>';
308     break;
309   case MachineOperand::MO_BlockAddress:
310     OS << '<';
311     WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
312     OS << '>';
313     break;
314   case MachineOperand::MO_Metadata:
315     OS << '<';
316     WriteAsOperand(OS, getMetadata(), /*PrintType=*/false);
317     OS << '>';
318     break;
319   case MachineOperand::MO_MCSymbol:
320     OS << "<MCSym=" << *getMCSymbol() << '>';
321     break;
322   default:
323     llvm_unreachable("Unrecognized operand type");
324   }
325   
326   if (unsigned TF = getTargetFlags())
327     OS << "[TF=" << TF << ']';
328 }
329
330 //===----------------------------------------------------------------------===//
331 // MachineMemOperand Implementation
332 //===----------------------------------------------------------------------===//
333
334 /// getAddrSpace - Return the LLVM IR address space number that this pointer
335 /// points into.
336 unsigned MachinePointerInfo::getAddrSpace() const {
337   if (V == 0) return 0;
338   return cast<PointerType>(V->getType())->getAddressSpace();
339 }
340
341 /// getConstantPool - Return a MachinePointerInfo record that refers to the
342 /// constant pool.
343 MachinePointerInfo MachinePointerInfo::getConstantPool() {
344   return MachinePointerInfo(PseudoSourceValue::getConstantPool());
345 }
346
347 /// getFixedStack - Return a MachinePointerInfo record that refers to the
348 /// the specified FrameIndex.
349 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
350   return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
351 }
352
353 MachinePointerInfo MachinePointerInfo::getJumpTable() {
354   return MachinePointerInfo(PseudoSourceValue::getJumpTable());
355 }
356
357 MachinePointerInfo MachinePointerInfo::getGOT() {
358   return MachinePointerInfo(PseudoSourceValue::getGOT());
359 }
360
361 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
362   return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
363 }
364
365 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
366                                      uint64_t s, unsigned int a,
367                                      const MDNode *TBAAInfo)
368   : PtrInfo(ptrinfo), Size(s),
369     Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
370     TBAAInfo(TBAAInfo) {
371   assert((PtrInfo.V == 0 || isa<PointerType>(PtrInfo.V->getType())) &&
372          "invalid pointer value");
373   assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
374   assert((isLoad() || isStore()) && "Not a load/store!");
375 }
376
377 /// Profile - Gather unique data for the object.
378 ///
379 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
380   ID.AddInteger(getOffset());
381   ID.AddInteger(Size);
382   ID.AddPointer(getValue());
383   ID.AddInteger(Flags);
384 }
385
386 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
387   // The Value and Offset may differ due to CSE. But the flags and size
388   // should be the same.
389   assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
390   assert(MMO->getSize() == getSize() && "Size mismatch!");
391
392   if (MMO->getBaseAlignment() >= getBaseAlignment()) {
393     // Update the alignment value.
394     Flags = (Flags & ((1 << MOMaxBits) - 1)) |
395       ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
396     // Also update the base and offset, because the new alignment may
397     // not be applicable with the old ones.
398     PtrInfo = MMO->PtrInfo;
399   }
400 }
401
402 /// getAlignment - Return the minimum known alignment in bytes of the
403 /// actual memory reference.
404 uint64_t MachineMemOperand::getAlignment() const {
405   return MinAlign(getBaseAlignment(), getOffset());
406 }
407
408 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
409   assert((MMO.isLoad() || MMO.isStore()) &&
410          "SV has to be a load, store or both.");
411   
412   if (MMO.isVolatile())
413     OS << "Volatile ";
414
415   if (MMO.isLoad())
416     OS << "LD";
417   if (MMO.isStore())
418     OS << "ST";
419   OS << MMO.getSize();
420   
421   // Print the address information.
422   OS << "[";
423   if (!MMO.getValue())
424     OS << "<unknown>";
425   else
426     WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
427
428   // If the alignment of the memory reference itself differs from the alignment
429   // of the base pointer, print the base alignment explicitly, next to the base
430   // pointer.
431   if (MMO.getBaseAlignment() != MMO.getAlignment())
432     OS << "(align=" << MMO.getBaseAlignment() << ")";
433
434   if (MMO.getOffset() != 0)
435     OS << "+" << MMO.getOffset();
436   OS << "]";
437
438   // Print the alignment of the reference.
439   if (MMO.getBaseAlignment() != MMO.getAlignment() ||
440       MMO.getBaseAlignment() != MMO.getSize())
441     OS << "(align=" << MMO.getAlignment() << ")";
442
443   // Print TBAA info.
444   if (const MDNode *TBAAInfo = MMO.getTBAAInfo()) {
445     OS << "(tbaa=";
446     if (TBAAInfo->getNumOperands() > 0)
447       WriteAsOperand(OS, TBAAInfo->getOperand(0), /*PrintType=*/false);
448     else
449       OS << "<unknown>";
450     OS << ")";
451   }
452
453   // Print nontemporal info.
454   if (MMO.isNonTemporal())
455     OS << "(nontemporal)";
456
457   return OS;
458 }
459
460 //===----------------------------------------------------------------------===//
461 // MachineInstr Implementation
462 //===----------------------------------------------------------------------===//
463
464 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
465 /// MCID NULL and no operands.
466 MachineInstr::MachineInstr()
467   : MCID(0), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
468     MemRefs(0), MemRefsEnd(0),
469     Parent(0) {
470   // Make sure that we get added to a machine basicblock
471   LeakDetector::addGarbageObject(this);
472 }
473
474 void MachineInstr::addImplicitDefUseOperands() {
475   if (MCID->ImplicitDefs)
476     for (const unsigned *ImpDefs = MCID->ImplicitDefs; *ImpDefs; ++ImpDefs)
477       addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
478   if (MCID->ImplicitUses)
479     for (const unsigned *ImpUses = MCID->ImplicitUses; *ImpUses; ++ImpUses)
480       addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
481 }
482
483 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
484 /// implicit operands. It reserves space for the number of operands specified by
485 /// the MCInstrDesc.
486 MachineInstr::MachineInstr(const MCInstrDesc &tid, bool NoImp)
487   : MCID(&tid), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
488     MemRefs(0), MemRefsEnd(0), Parent(0) {
489   if (!NoImp)
490     NumImplicitOps = MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
491   Operands.reserve(NumImplicitOps + MCID->getNumOperands());
492   if (!NoImp)
493     addImplicitDefUseOperands();
494   // Make sure that we get added to a machine basicblock
495   LeakDetector::addGarbageObject(this);
496 }
497
498 /// MachineInstr ctor - As above, but with a DebugLoc.
499 MachineInstr::MachineInstr(const MCInstrDesc &tid, const DebugLoc dl,
500                            bool NoImp)
501   : MCID(&tid), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
502     MemRefs(0), MemRefsEnd(0), Parent(0), debugLoc(dl) {
503   if (!NoImp)
504     NumImplicitOps = MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
505   Operands.reserve(NumImplicitOps + MCID->getNumOperands());
506   if (!NoImp)
507     addImplicitDefUseOperands();
508   // Make sure that we get added to a machine basicblock
509   LeakDetector::addGarbageObject(this);
510 }
511
512 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
513 /// that the MachineInstr is created and added to the end of the specified 
514 /// basic block.
515 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const MCInstrDesc &tid)
516   : MCID(&tid), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
517     MemRefs(0), MemRefsEnd(0), Parent(0) {
518   assert(MBB && "Cannot use inserting ctor with null basic block!");
519   NumImplicitOps = MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
520   Operands.reserve(NumImplicitOps + MCID->getNumOperands());
521   addImplicitDefUseOperands();
522   // Make sure that we get added to a machine basicblock
523   LeakDetector::addGarbageObject(this);
524   MBB->push_back(this);  // Add instruction to end of basic block!
525 }
526
527 /// MachineInstr ctor - As above, but with a DebugLoc.
528 ///
529 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
530                            const MCInstrDesc &tid)
531   : MCID(&tid), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
532     MemRefs(0), MemRefsEnd(0), Parent(0), debugLoc(dl) {
533   assert(MBB && "Cannot use inserting ctor with null basic block!");
534   NumImplicitOps = MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
535   Operands.reserve(NumImplicitOps + MCID->getNumOperands());
536   addImplicitDefUseOperands();
537   // Make sure that we get added to a machine basicblock
538   LeakDetector::addGarbageObject(this);
539   MBB->push_back(this);  // Add instruction to end of basic block!
540 }
541
542 /// MachineInstr ctor - Copies MachineInstr arg exactly
543 ///
544 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
545   : MCID(&MI.getDesc()), NumImplicitOps(0), Flags(0), AsmPrinterFlags(0),
546     MemRefs(MI.MemRefs), MemRefsEnd(MI.MemRefsEnd),
547     Parent(0), debugLoc(MI.getDebugLoc()) {
548   Operands.reserve(MI.getNumOperands());
549
550   // Add operands
551   for (unsigned i = 0; i != MI.getNumOperands(); ++i)
552     addOperand(MI.getOperand(i));
553   NumImplicitOps = MI.NumImplicitOps;
554
555   // Copy all the flags.
556   Flags = MI.Flags;
557
558   // Set parent to null.
559   Parent = 0;
560
561   LeakDetector::addGarbageObject(this);
562 }
563
564 MachineInstr::~MachineInstr() {
565   LeakDetector::removeGarbageObject(this);
566 #ifndef NDEBUG
567   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
568     assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
569     assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
570            "Reg operand def/use list corrupted");
571   }
572 #endif
573 }
574
575 /// getRegInfo - If this instruction is embedded into a MachineFunction,
576 /// return the MachineRegisterInfo object for the current function, otherwise
577 /// return null.
578 MachineRegisterInfo *MachineInstr::getRegInfo() {
579   if (MachineBasicBlock *MBB = getParent())
580     return &MBB->getParent()->getRegInfo();
581   return 0;
582 }
583
584 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
585 /// this instruction from their respective use lists.  This requires that the
586 /// operands already be on their use lists.
587 void MachineInstr::RemoveRegOperandsFromUseLists() {
588   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
589     if (Operands[i].isReg())
590       Operands[i].RemoveRegOperandFromRegInfo();
591   }
592 }
593
594 /// AddRegOperandsToUseLists - Add all of the register operands in
595 /// this instruction from their respective use lists.  This requires that the
596 /// operands not be on their use lists yet.
597 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
598   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
599     if (Operands[i].isReg())
600       Operands[i].AddRegOperandToRegInfo(&RegInfo);
601   }
602 }
603
604
605 /// addOperand - Add the specified operand to the instruction.  If it is an
606 /// implicit operand, it is added to the end of the operand list.  If it is
607 /// an explicit operand it is added at the end of the explicit operand list
608 /// (before the first implicit operand). 
609 void MachineInstr::addOperand(const MachineOperand &Op) {
610   bool isImpReg = Op.isReg() && Op.isImplicit();
611   assert((isImpReg || !OperandsComplete()) &&
612          "Trying to add an operand to a machine instr that is already done!");
613
614   MachineRegisterInfo *RegInfo = getRegInfo();
615
616   // If we are adding the operand to the end of the list, our job is simpler.
617   // This is true most of the time, so this is a reasonable optimization.
618   if (isImpReg || NumImplicitOps == 0) {
619     // We can only do this optimization if we know that the operand list won't
620     // reallocate.
621     if (Operands.empty() || Operands.size()+1 <= Operands.capacity()) {
622       Operands.push_back(Op);
623     
624       // Set the parent of the operand.
625       Operands.back().ParentMI = this;
626   
627       // If the operand is a register, update the operand's use list.
628       if (Op.isReg()) {
629         Operands.back().AddRegOperandToRegInfo(RegInfo);
630         // If the register operand is flagged as early, mark the operand as such
631         unsigned OpNo = Operands.size() - 1;
632         if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
633           Operands[OpNo].setIsEarlyClobber(true);
634       }
635       return;
636     }
637   }
638   
639   // Otherwise, we have to insert a real operand before any implicit ones.
640   unsigned OpNo = Operands.size()-NumImplicitOps;
641
642   // If this instruction isn't embedded into a function, then we don't need to
643   // update any operand lists.
644   if (RegInfo == 0) {
645     // Simple insertion, no reginfo update needed for other register operands.
646     Operands.insert(Operands.begin()+OpNo, Op);
647     Operands[OpNo].ParentMI = this;
648
649     // Do explicitly set the reginfo for this operand though, to ensure the
650     // next/prev fields are properly nulled out.
651     if (Operands[OpNo].isReg()) {
652       Operands[OpNo].AddRegOperandToRegInfo(0);
653       // If the register operand is flagged as early, mark the operand as such
654       if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
655         Operands[OpNo].setIsEarlyClobber(true);
656     }
657
658   } else if (Operands.size()+1 <= Operands.capacity()) {
659     // Otherwise, we have to remove register operands from their register use
660     // list, add the operand, then add the register operands back to their use
661     // list.  This also must handle the case when the operand list reallocates
662     // to somewhere else.
663   
664     // If insertion of this operand won't cause reallocation of the operand
665     // list, just remove the implicit operands, add the operand, then re-add all
666     // the rest of the operands.
667     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
668       assert(Operands[i].isReg() && "Should only be an implicit reg!");
669       Operands[i].RemoveRegOperandFromRegInfo();
670     }
671     
672     // Add the operand.  If it is a register, add it to the reg list.
673     Operands.insert(Operands.begin()+OpNo, Op);
674     Operands[OpNo].ParentMI = this;
675
676     if (Operands[OpNo].isReg()) {
677       Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
678       // If the register operand is flagged as early, mark the operand as such
679       if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
680         Operands[OpNo].setIsEarlyClobber(true);
681     }
682     
683     // Re-add all the implicit ops.
684     for (unsigned i = OpNo+1, e = Operands.size(); i != e; ++i) {
685       assert(Operands[i].isReg() && "Should only be an implicit reg!");
686       Operands[i].AddRegOperandToRegInfo(RegInfo);
687     }
688   } else {
689     // Otherwise, we will be reallocating the operand list.  Remove all reg
690     // operands from their list, then readd them after the operand list is
691     // reallocated.
692     RemoveRegOperandsFromUseLists();
693     
694     Operands.insert(Operands.begin()+OpNo, Op);
695     Operands[OpNo].ParentMI = this;
696   
697     // Re-add all the operands.
698     AddRegOperandsToUseLists(*RegInfo);
699
700       // If the register operand is flagged as early, mark the operand as such
701     if (Operands[OpNo].isReg()
702         && MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
703       Operands[OpNo].setIsEarlyClobber(true);
704   }
705 }
706
707 /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
708 /// fewer operand than it started with.
709 ///
710 void MachineInstr::RemoveOperand(unsigned OpNo) {
711   assert(OpNo < Operands.size() && "Invalid operand number");
712   
713   // Special case removing the last one.
714   if (OpNo == Operands.size()-1) {
715     // If needed, remove from the reg def/use list.
716     if (Operands.back().isReg() && Operands.back().isOnRegUseList())
717       Operands.back().RemoveRegOperandFromRegInfo();
718     
719     Operands.pop_back();
720     return;
721   }
722
723   // Otherwise, we are removing an interior operand.  If we have reginfo to
724   // update, remove all operands that will be shifted down from their reg lists,
725   // move everything down, then re-add them.
726   MachineRegisterInfo *RegInfo = getRegInfo();
727   if (RegInfo) {
728     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
729       if (Operands[i].isReg())
730         Operands[i].RemoveRegOperandFromRegInfo();
731     }
732   }
733   
734   Operands.erase(Operands.begin()+OpNo);
735
736   if (RegInfo) {
737     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
738       if (Operands[i].isReg())
739         Operands[i].AddRegOperandToRegInfo(RegInfo);
740     }
741   }
742 }
743
744 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
745 /// This function should be used only occasionally. The setMemRefs function
746 /// is the primary method for setting up a MachineInstr's MemRefs list.
747 void MachineInstr::addMemOperand(MachineFunction &MF,
748                                  MachineMemOperand *MO) {
749   mmo_iterator OldMemRefs = MemRefs;
750   mmo_iterator OldMemRefsEnd = MemRefsEnd;
751
752   size_t NewNum = (MemRefsEnd - MemRefs) + 1;
753   mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
754   mmo_iterator NewMemRefsEnd = NewMemRefs + NewNum;
755
756   std::copy(OldMemRefs, OldMemRefsEnd, NewMemRefs);
757   NewMemRefs[NewNum - 1] = MO;
758
759   MemRefs = NewMemRefs;
760   MemRefsEnd = NewMemRefsEnd;
761 }
762
763 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
764                                  MICheckType Check) const {
765   // If opcodes or number of operands are not the same then the two
766   // instructions are obviously not identical.
767   if (Other->getOpcode() != getOpcode() ||
768       Other->getNumOperands() != getNumOperands())
769     return false;
770
771   // Check operands to make sure they match.
772   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
773     const MachineOperand &MO = getOperand(i);
774     const MachineOperand &OMO = Other->getOperand(i);
775     if (!MO.isReg()) {
776       if (!MO.isIdenticalTo(OMO))
777         return false;
778       continue;
779     }
780
781     // Clients may or may not want to ignore defs when testing for equality.
782     // For example, machine CSE pass only cares about finding common
783     // subexpressions, so it's safe to ignore virtual register defs.
784     if (MO.isDef()) {
785       if (Check == IgnoreDefs)
786         continue;
787       else if (Check == IgnoreVRegDefs) {
788         if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
789             TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
790           if (MO.getReg() != OMO.getReg())
791             return false;
792       } else {
793         if (!MO.isIdenticalTo(OMO))
794           return false;
795         if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
796           return false;
797       }
798     } else {
799       if (!MO.isIdenticalTo(OMO))
800         return false;
801       if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
802         return false;
803     }
804   }
805   return true;
806 }
807
808 /// removeFromParent - This method unlinks 'this' from the containing basic
809 /// block, and returns it, but does not delete it.
810 MachineInstr *MachineInstr::removeFromParent() {
811   assert(getParent() && "Not embedded in a basic block!");
812   getParent()->remove(this);
813   return this;
814 }
815
816
817 /// eraseFromParent - This method unlinks 'this' from the containing basic
818 /// block, and deletes it.
819 void MachineInstr::eraseFromParent() {
820   assert(getParent() && "Not embedded in a basic block!");
821   getParent()->erase(this);
822 }
823
824
825 /// OperandComplete - Return true if it's illegal to add a new operand
826 ///
827 bool MachineInstr::OperandsComplete() const {
828   unsigned short NumOperands = MCID->getNumOperands();
829   if (!MCID->isVariadic() && getNumOperands()-NumImplicitOps >= NumOperands)
830     return true;  // Broken: we have all the operands of this instruction!
831   return false;
832 }
833
834 /// getNumExplicitOperands - Returns the number of non-implicit operands.
835 ///
836 unsigned MachineInstr::getNumExplicitOperands() const {
837   unsigned NumOperands = MCID->getNumOperands();
838   if (!MCID->isVariadic())
839     return NumOperands;
840
841   for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
842     const MachineOperand &MO = getOperand(i);
843     if (!MO.isReg() || !MO.isImplicit())
844       NumOperands++;
845   }
846   return NumOperands;
847 }
848
849 bool MachineInstr::isStackAligningInlineAsm() const {
850   if (isInlineAsm()) {
851     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
852     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
853       return true;
854   }
855   return false;
856 }
857
858 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
859 /// the specific register or -1 if it is not found. It further tightens
860 /// the search criteria to a use that kills the register if isKill is true.
861 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
862                                           const TargetRegisterInfo *TRI) const {
863   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
864     const MachineOperand &MO = getOperand(i);
865     if (!MO.isReg() || !MO.isUse())
866       continue;
867     unsigned MOReg = MO.getReg();
868     if (!MOReg)
869       continue;
870     if (MOReg == Reg ||
871         (TRI &&
872          TargetRegisterInfo::isPhysicalRegister(MOReg) &&
873          TargetRegisterInfo::isPhysicalRegister(Reg) &&
874          TRI->isSubRegister(MOReg, Reg)))
875       if (!isKill || MO.isKill())
876         return i;
877   }
878   return -1;
879 }
880
881 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
882 /// indicating if this instruction reads or writes Reg. This also considers
883 /// partial defines.
884 std::pair<bool,bool>
885 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
886                                          SmallVectorImpl<unsigned> *Ops) const {
887   bool PartDef = false; // Partial redefine.
888   bool FullDef = false; // Full define.
889   bool Use = false;
890
891   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
892     const MachineOperand &MO = getOperand(i);
893     if (!MO.isReg() || MO.getReg() != Reg)
894       continue;
895     if (Ops)
896       Ops->push_back(i);
897     if (MO.isUse())
898       Use |= !MO.isUndef();
899     else if (MO.getSubReg())
900       PartDef = true;
901     else
902       FullDef = true;
903   }
904   // A partial redefine uses Reg unless there is also a full define.
905   return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
906 }
907
908 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
909 /// the specified register or -1 if it is not found. If isDead is true, defs
910 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
911 /// also checks if there is a def of a super-register.
912 int
913 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
914                                         const TargetRegisterInfo *TRI) const {
915   bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
916   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
917     const MachineOperand &MO = getOperand(i);
918     if (!MO.isReg() || !MO.isDef())
919       continue;
920     unsigned MOReg = MO.getReg();
921     bool Found = (MOReg == Reg);
922     if (!Found && TRI && isPhys &&
923         TargetRegisterInfo::isPhysicalRegister(MOReg)) {
924       if (Overlap)
925         Found = TRI->regsOverlap(MOReg, Reg);
926       else
927         Found = TRI->isSubRegister(MOReg, Reg);
928     }
929     if (Found && (!isDead || MO.isDead()))
930       return i;
931   }
932   return -1;
933 }
934
935 /// findFirstPredOperandIdx() - Find the index of the first operand in the
936 /// operand list that is used to represent the predicate. It returns -1 if
937 /// none is found.
938 int MachineInstr::findFirstPredOperandIdx() const {
939   const MCInstrDesc &MCID = getDesc();
940   if (MCID.isPredicable()) {
941     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
942       if (MCID.OpInfo[i].isPredicate())
943         return i;
944   }
945
946   return -1;
947 }
948   
949 /// isRegTiedToUseOperand - Given the index of a register def operand,
950 /// check if the register def is tied to a source operand, due to either
951 /// two-address elimination or inline assembly constraints. Returns the
952 /// first tied use operand index by reference is UseOpIdx is not null.
953 bool MachineInstr::
954 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
955   if (isInlineAsm()) {
956     assert(DefOpIdx > InlineAsm::MIOp_FirstOperand);
957     const MachineOperand &MO = getOperand(DefOpIdx);
958     if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
959       return false;
960     // Determine the actual operand index that corresponds to this index.
961     unsigned DefNo = 0;
962     unsigned DefPart = 0;
963     for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands();
964          i < e; ) {
965       const MachineOperand &FMO = getOperand(i);
966       // After the normal asm operands there may be additional imp-def regs.
967       if (!FMO.isImm())
968         return false;
969       // Skip over this def.
970       unsigned NumOps = InlineAsm::getNumOperandRegisters(FMO.getImm());
971       unsigned PrevDef = i + 1;
972       i = PrevDef + NumOps;
973       if (i > DefOpIdx) {
974         DefPart = DefOpIdx - PrevDef;
975         break;
976       }
977       ++DefNo;
978     }
979     for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands();
980          i != e; ++i) {
981       const MachineOperand &FMO = getOperand(i);
982       if (!FMO.isImm())
983         continue;
984       if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
985         continue;
986       unsigned Idx;
987       if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
988           Idx == DefNo) {
989         if (UseOpIdx)
990           *UseOpIdx = (unsigned)i + 1 + DefPart;
991         return true;
992       }
993     }
994     return false;
995   }
996
997   assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
998   const MCInstrDesc &MCID = getDesc();
999   for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
1000     const MachineOperand &MO = getOperand(i);
1001     if (MO.isReg() && MO.isUse() &&
1002         MCID.getOperandConstraint(i, MCOI::TIED_TO) == (int)DefOpIdx) {
1003       if (UseOpIdx)
1004         *UseOpIdx = (unsigned)i;
1005       return true;
1006     }
1007   }
1008   return false;
1009 }
1010
1011 /// isRegTiedToDefOperand - Return true if the operand of the specified index
1012 /// is a register use and it is tied to an def operand. It also returns the def
1013 /// operand index by reference.
1014 bool MachineInstr::
1015 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
1016   if (isInlineAsm()) {
1017     const MachineOperand &MO = getOperand(UseOpIdx);
1018     if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
1019       return false;
1020
1021     // Find the flag operand corresponding to UseOpIdx
1022     unsigned FlagIdx, NumOps=0;
1023     for (FlagIdx = InlineAsm::MIOp_FirstOperand;
1024          FlagIdx < UseOpIdx; FlagIdx += NumOps+1) {
1025       const MachineOperand &UFMO = getOperand(FlagIdx);
1026       // After the normal asm operands there may be additional imp-def regs.
1027       if (!UFMO.isImm())
1028         return false;
1029       NumOps = InlineAsm::getNumOperandRegisters(UFMO.getImm());
1030       assert(NumOps < getNumOperands() && "Invalid inline asm flag");
1031       if (UseOpIdx < FlagIdx+NumOps+1)
1032         break;
1033     }
1034     if (FlagIdx >= UseOpIdx)
1035       return false;
1036     const MachineOperand &UFMO = getOperand(FlagIdx);
1037     unsigned DefNo;
1038     if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
1039       if (!DefOpIdx)
1040         return true;
1041
1042       unsigned DefIdx = InlineAsm::MIOp_FirstOperand;
1043       // Remember to adjust the index. First operand is asm string, second is
1044       // the HasSideEffects and AlignStack bits, then there is a flag for each.
1045       while (DefNo) {
1046         const MachineOperand &FMO = getOperand(DefIdx);
1047         assert(FMO.isImm());
1048         // Skip over this def.
1049         DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
1050         --DefNo;
1051       }
1052       *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
1053       return true;
1054     }
1055     return false;
1056   }
1057
1058   const MCInstrDesc &MCID = getDesc();
1059   if (UseOpIdx >= MCID.getNumOperands())
1060     return false;
1061   const MachineOperand &MO = getOperand(UseOpIdx);
1062   if (!MO.isReg() || !MO.isUse())
1063     return false;
1064   int DefIdx = MCID.getOperandConstraint(UseOpIdx, MCOI::TIED_TO);
1065   if (DefIdx == -1)
1066     return false;
1067   if (DefOpIdx)
1068     *DefOpIdx = (unsigned)DefIdx;
1069   return true;
1070 }
1071
1072 /// clearKillInfo - Clears kill flags on all operands.
1073 ///
1074 void MachineInstr::clearKillInfo() {
1075   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1076     MachineOperand &MO = getOperand(i);
1077     if (MO.isReg() && MO.isUse())
1078       MO.setIsKill(false);
1079   }
1080 }
1081
1082 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
1083 ///
1084 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
1085   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1086     const MachineOperand &MO = MI->getOperand(i);
1087     if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
1088       continue;
1089     for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
1090       MachineOperand &MOp = getOperand(j);
1091       if (!MOp.isIdenticalTo(MO))
1092         continue;
1093       if (MO.isKill())
1094         MOp.setIsKill();
1095       else
1096         MOp.setIsDead();
1097       break;
1098     }
1099   }
1100 }
1101
1102 /// copyPredicates - Copies predicate operand(s) from MI.
1103 void MachineInstr::copyPredicates(const MachineInstr *MI) {
1104   const MCInstrDesc &MCID = MI->getDesc();
1105   if (!MCID.isPredicable())
1106     return;
1107   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1108     if (MCID.OpInfo[i].isPredicate()) {
1109       // Predicated operands must be last operands.
1110       addOperand(MI->getOperand(i));
1111     }
1112   }
1113 }
1114
1115 void MachineInstr::substituteRegister(unsigned FromReg,
1116                                       unsigned ToReg,
1117                                       unsigned SubIdx,
1118                                       const TargetRegisterInfo &RegInfo) {
1119   if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1120     if (SubIdx)
1121       ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1122     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1123       MachineOperand &MO = getOperand(i);
1124       if (!MO.isReg() || MO.getReg() != FromReg)
1125         continue;
1126       MO.substPhysReg(ToReg, RegInfo);
1127     }
1128   } else {
1129     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1130       MachineOperand &MO = getOperand(i);
1131       if (!MO.isReg() || MO.getReg() != FromReg)
1132         continue;
1133       MO.substVirtReg(ToReg, SubIdx, RegInfo);
1134     }
1135   }
1136 }
1137
1138 /// isSafeToMove - Return true if it is safe to move this instruction. If
1139 /// SawStore is set to true, it means that there is a store (or call) between
1140 /// the instruction's location and its intended destination.
1141 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1142                                 AliasAnalysis *AA,
1143                                 bool &SawStore) const {
1144   // Ignore stuff that we obviously can't move.
1145   if (MCID->mayStore() || MCID->isCall()) {
1146     SawStore = true;
1147     return false;
1148   }
1149
1150   if (isLabel() || isDebugValue() ||
1151       MCID->isTerminator() || hasUnmodeledSideEffects())
1152     return false;
1153
1154   // See if this instruction does a load.  If so, we have to guarantee that the
1155   // loaded value doesn't change between the load and the its intended
1156   // destination. The check for isInvariantLoad gives the targe the chance to
1157   // classify the load as always returning a constant, e.g. a constant pool
1158   // load.
1159   if (MCID->mayLoad() && !isInvariantLoad(AA))
1160     // Otherwise, this is a real load.  If there is a store between the load and
1161     // end of block, or if the load is volatile, we can't move it.
1162     return !SawStore && !hasVolatileMemoryRef();
1163
1164   return true;
1165 }
1166
1167 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
1168 /// instruction which defined the specified register instead of copying it.
1169 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
1170                                  AliasAnalysis *AA,
1171                                  unsigned DstReg) const {
1172   bool SawStore = false;
1173   if (!TII->isTriviallyReMaterializable(this, AA) ||
1174       !isSafeToMove(TII, AA, SawStore))
1175     return false;
1176   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1177     const MachineOperand &MO = getOperand(i);
1178     if (!MO.isReg())
1179       continue;
1180     // FIXME: For now, do not remat any instruction with register operands.
1181     // Later on, we can loosen the restriction is the register operands have
1182     // not been modified between the def and use. Note, this is different from
1183     // MachineSink because the code is no longer in two-address form (at least
1184     // partially).
1185     if (MO.isUse())
1186       return false;
1187     else if (!MO.isDead() && MO.getReg() != DstReg)
1188       return false;
1189   }
1190   return true;
1191 }
1192
1193 /// hasVolatileMemoryRef - Return true if this instruction may have a
1194 /// volatile memory reference, or if the information describing the
1195 /// memory reference is not available. Return false if it is known to
1196 /// have no volatile memory references.
1197 bool MachineInstr::hasVolatileMemoryRef() const {
1198   // An instruction known never to access memory won't have a volatile access.
1199   if (!MCID->mayStore() &&
1200       !MCID->mayLoad() &&
1201       !MCID->isCall() &&
1202       !hasUnmodeledSideEffects())
1203     return false;
1204
1205   // Otherwise, if the instruction has no memory reference information,
1206   // conservatively assume it wasn't preserved.
1207   if (memoperands_empty())
1208     return true;
1209   
1210   // Check the memory reference information for volatile references.
1211   for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1212     if ((*I)->isVolatile())
1213       return true;
1214
1215   return false;
1216 }
1217
1218 /// isInvariantLoad - Return true if this instruction is loading from a
1219 /// location whose value is invariant across the function.  For example,
1220 /// loading a value from the constant pool or from the argument area
1221 /// of a function if it does not change.  This should only return true of
1222 /// *all* loads the instruction does are invariant (if it does multiple loads).
1223 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1224   // If the instruction doesn't load at all, it isn't an invariant load.
1225   if (!MCID->mayLoad())
1226     return false;
1227
1228   // If the instruction has lost its memoperands, conservatively assume that
1229   // it may not be an invariant load.
1230   if (memoperands_empty())
1231     return false;
1232
1233   const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1234
1235   for (mmo_iterator I = memoperands_begin(),
1236        E = memoperands_end(); I != E; ++I) {
1237     if ((*I)->isVolatile()) return false;
1238     if ((*I)->isStore()) return false;
1239
1240     if (const Value *V = (*I)->getValue()) {
1241       // A load from a constant PseudoSourceValue is invariant.
1242       if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1243         if (PSV->isConstant(MFI))
1244           continue;
1245       // If we have an AliasAnalysis, ask it whether the memory is constant.
1246       if (AA && AA->pointsToConstantMemory(
1247                       AliasAnalysis::Location(V, (*I)->getSize(),
1248                                               (*I)->getTBAAInfo())))
1249         continue;
1250     }
1251
1252     // Otherwise assume conservatively.
1253     return false;
1254   }
1255
1256   // Everything checks out.
1257   return true;
1258 }
1259
1260 /// isConstantValuePHI - If the specified instruction is a PHI that always
1261 /// merges together the same virtual register, return the register, otherwise
1262 /// return 0.
1263 unsigned MachineInstr::isConstantValuePHI() const {
1264   if (!isPHI())
1265     return 0;
1266   assert(getNumOperands() >= 3 &&
1267          "It's illegal to have a PHI without source operands");
1268
1269   unsigned Reg = getOperand(1).getReg();
1270   for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1271     if (getOperand(i).getReg() != Reg)
1272       return 0;
1273   return Reg;
1274 }
1275
1276 bool MachineInstr::hasUnmodeledSideEffects() const {
1277   if (getDesc().hasUnmodeledSideEffects())
1278     return true;
1279   if (isInlineAsm()) {
1280     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1281     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1282       return true;
1283   }
1284
1285   return false;
1286 }
1287
1288 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1289 ///
1290 bool MachineInstr::allDefsAreDead() const {
1291   for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1292     const MachineOperand &MO = getOperand(i);
1293     if (!MO.isReg() || MO.isUse())
1294       continue;
1295     if (!MO.isDead())
1296       return false;
1297   }
1298   return true;
1299 }
1300
1301 /// copyImplicitOps - Copy implicit register operands from specified
1302 /// instruction to this instruction.
1303 void MachineInstr::copyImplicitOps(const MachineInstr *MI) {
1304   for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1305        i != e; ++i) {
1306     const MachineOperand &MO = MI->getOperand(i);
1307     if (MO.isReg() && MO.isImplicit())
1308       addOperand(MO);
1309   }
1310 }
1311
1312 void MachineInstr::dump() const {
1313   dbgs() << "  " << *this;
1314 }
1315
1316 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF, 
1317                          raw_ostream &CommentOS) {
1318   const LLVMContext &Ctx = MF->getFunction()->getContext();
1319   if (!DL.isUnknown()) {          // Print source line info.
1320     DIScope Scope(DL.getScope(Ctx));
1321     // Omit the directory, because it's likely to be long and uninteresting.
1322     if (Scope.Verify())
1323       CommentOS << Scope.getFilename();
1324     else
1325       CommentOS << "<unknown>";
1326     CommentOS << ':' << DL.getLine();
1327     if (DL.getCol() != 0)
1328       CommentOS << ':' << DL.getCol();
1329     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1330     if (!InlinedAtDL.isUnknown()) {
1331       CommentOS << " @[ ";
1332       printDebugLoc(InlinedAtDL, MF, CommentOS);
1333       CommentOS << " ]";
1334     }
1335   }
1336 }
1337
1338 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1339   // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1340   const MachineFunction *MF = 0;
1341   const MachineRegisterInfo *MRI = 0;
1342   if (const MachineBasicBlock *MBB = getParent()) {
1343     MF = MBB->getParent();
1344     if (!TM && MF)
1345       TM = &MF->getTarget();
1346     if (MF)
1347       MRI = &MF->getRegInfo();
1348   }
1349
1350   // Save a list of virtual registers.
1351   SmallVector<unsigned, 8> VirtRegs;
1352
1353   // Print explicitly defined operands on the left of an assignment syntax.
1354   unsigned StartOp = 0, e = getNumOperands();
1355   for (; StartOp < e && getOperand(StartOp).isReg() &&
1356          getOperand(StartOp).isDef() &&
1357          !getOperand(StartOp).isImplicit();
1358        ++StartOp) {
1359     if (StartOp != 0) OS << ", ";
1360     getOperand(StartOp).print(OS, TM);
1361     unsigned Reg = getOperand(StartOp).getReg();
1362     if (TargetRegisterInfo::isVirtualRegister(Reg))
1363       VirtRegs.push_back(Reg);
1364   }
1365
1366   if (StartOp != 0)
1367     OS << " = ";
1368
1369   // Print the opcode name.
1370   OS << getDesc().getName();
1371
1372   // Print the rest of the operands.
1373   bool OmittedAnyCallClobbers = false;
1374   bool FirstOp = true;
1375   unsigned AsmDescOp = ~0u;
1376   unsigned AsmOpCount = 0;
1377
1378   if (isInlineAsm()) {
1379     // Print asm string.
1380     OS << " ";
1381     getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
1382
1383     // Print HasSideEffects, IsAlignStack
1384     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1385     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1386       OS << " [sideeffect]";
1387     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1388       OS << " [alignstack]";
1389
1390     StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1391     FirstOp = false;
1392   }
1393
1394
1395   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1396     const MachineOperand &MO = getOperand(i);
1397
1398     if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1399       VirtRegs.push_back(MO.getReg());
1400
1401     // Omit call-clobbered registers which aren't used anywhere. This makes
1402     // call instructions much less noisy on targets where calls clobber lots
1403     // of registers. Don't rely on MO.isDead() because we may be called before
1404     // LiveVariables is run, or we may be looking at a non-allocatable reg.
1405     if (MF && getDesc().isCall() &&
1406         MO.isReg() && MO.isImplicit() && MO.isDef()) {
1407       unsigned Reg = MO.getReg();
1408       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1409         const MachineRegisterInfo &MRI = MF->getRegInfo();
1410         if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
1411           bool HasAliasLive = false;
1412           for (const unsigned *Alias = TM->getRegisterInfo()->getAliasSet(Reg);
1413                unsigned AliasReg = *Alias; ++Alias)
1414             if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
1415               HasAliasLive = true;
1416               break;
1417             }
1418           if (!HasAliasLive) {
1419             OmittedAnyCallClobbers = true;
1420             continue;
1421           }
1422         }
1423       }
1424     }
1425
1426     if (FirstOp) FirstOp = false; else OS << ",";
1427     OS << " ";
1428     if (i < getDesc().NumOperands) {
1429       const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1430       if (MCOI.isPredicate())
1431         OS << "pred:";
1432       if (MCOI.isOptionalDef())
1433         OS << "opt:";
1434     }
1435     if (isDebugValue() && MO.isMetadata()) {
1436       // Pretty print DBG_VALUE instructions.
1437       const MDNode *MD = MO.getMetadata();
1438       if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
1439         OS << "!\"" << MDS->getString() << '\"';
1440       else
1441         MO.print(OS, TM);
1442     } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1443       OS << TM->getRegisterInfo()->getSubRegIndexName(MO.getImm());
1444     } else if (i == AsmDescOp && MO.isImm()) {
1445       // Pretty print the inline asm operand descriptor.
1446       OS << '$' << AsmOpCount++;
1447       unsigned Flag = MO.getImm();
1448       switch (InlineAsm::getKind(Flag)) {
1449       case InlineAsm::Kind_RegUse:             OS << ":[reguse]"; break;
1450       case InlineAsm::Kind_RegDef:             OS << ":[regdef]"; break;
1451       case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec]"; break;
1452       case InlineAsm::Kind_Clobber:            OS << ":[clobber]"; break;
1453       case InlineAsm::Kind_Imm:                OS << ":[imm]"; break;
1454       case InlineAsm::Kind_Mem:                OS << ":[mem]"; break;
1455       default: OS << ":[??" << InlineAsm::getKind(Flag) << ']'; break;
1456       }
1457
1458       unsigned TiedTo = 0;
1459       if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1460         OS << " [tiedto:$" << TiedTo << ']';
1461
1462       // Compute the index of the next operand descriptor.
1463       AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1464     } else
1465       MO.print(OS, TM);
1466   }
1467
1468   // Briefly indicate whether any call clobbers were omitted.
1469   if (OmittedAnyCallClobbers) {
1470     if (!FirstOp) OS << ",";
1471     OS << " ...";
1472   }
1473
1474   bool HaveSemi = false;
1475   if (Flags) {
1476     if (!HaveSemi) OS << ";"; HaveSemi = true;
1477     OS << " flags: ";
1478
1479     if (Flags & FrameSetup)
1480       OS << "FrameSetup";
1481   }
1482
1483   if (!memoperands_empty()) {
1484     if (!HaveSemi) OS << ";"; HaveSemi = true;
1485
1486     OS << " mem:";
1487     for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1488          i != e; ++i) {
1489       OS << **i;
1490       if (llvm::next(i) != e)
1491         OS << " ";
1492     }
1493   }
1494
1495   // Print the regclass of any virtual registers encountered.
1496   if (MRI && !VirtRegs.empty()) {
1497     if (!HaveSemi) OS << ";"; HaveSemi = true;
1498     for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1499       const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1500       OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
1501       for (unsigned j = i+1; j != VirtRegs.size();) {
1502         if (MRI->getRegClass(VirtRegs[j]) != RC) {
1503           ++j;
1504           continue;
1505         }
1506         if (VirtRegs[i] != VirtRegs[j])
1507           OS << "," << PrintReg(VirtRegs[j]);
1508         VirtRegs.erase(VirtRegs.begin()+j);
1509       }
1510     }
1511   }
1512
1513   // Print debug location information.
1514   if (!debugLoc.isUnknown() && MF) {
1515     if (!HaveSemi) OS << ";"; HaveSemi = true;
1516     OS << " dbg:";
1517     printDebugLoc(debugLoc, MF, OS);
1518   }
1519
1520   OS << '\n';
1521 }
1522
1523 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1524                                      const TargetRegisterInfo *RegInfo,
1525                                      bool AddIfNotFound) {
1526   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1527   bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1528   bool Found = false;
1529   SmallVector<unsigned,4> DeadOps;
1530   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1531     MachineOperand &MO = getOperand(i);
1532     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1533       continue;
1534     unsigned Reg = MO.getReg();
1535     if (!Reg)
1536       continue;
1537
1538     if (Reg == IncomingReg) {
1539       if (!Found) {
1540         if (MO.isKill())
1541           // The register is already marked kill.
1542           return true;
1543         if (isPhysReg && isRegTiedToDefOperand(i))
1544           // Two-address uses of physregs must not be marked kill.
1545           return true;
1546         MO.setIsKill();
1547         Found = true;
1548       }
1549     } else if (hasAliases && MO.isKill() &&
1550                TargetRegisterInfo::isPhysicalRegister(Reg)) {
1551       // A super-register kill already exists.
1552       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1553         return true;
1554       if (RegInfo->isSubRegister(IncomingReg, Reg))
1555         DeadOps.push_back(i);
1556     }
1557   }
1558
1559   // Trim unneeded kill operands.
1560   while (!DeadOps.empty()) {
1561     unsigned OpIdx = DeadOps.back();
1562     if (getOperand(OpIdx).isImplicit())
1563       RemoveOperand(OpIdx);
1564     else
1565       getOperand(OpIdx).setIsKill(false);
1566     DeadOps.pop_back();
1567   }
1568
1569   // If not found, this means an alias of one of the operands is killed. Add a
1570   // new implicit operand if required.
1571   if (!Found && AddIfNotFound) {
1572     addOperand(MachineOperand::CreateReg(IncomingReg,
1573                                          false /*IsDef*/,
1574                                          true  /*IsImp*/,
1575                                          true  /*IsKill*/));
1576     return true;
1577   }
1578   return Found;
1579 }
1580
1581 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1582                                    const TargetRegisterInfo *RegInfo,
1583                                    bool AddIfNotFound) {
1584   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1585   bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1586   bool Found = false;
1587   SmallVector<unsigned,4> DeadOps;
1588   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1589     MachineOperand &MO = getOperand(i);
1590     if (!MO.isReg() || !MO.isDef())
1591       continue;
1592     unsigned Reg = MO.getReg();
1593     if (!Reg)
1594       continue;
1595
1596     if (Reg == IncomingReg) {
1597       MO.setIsDead();
1598       Found = true;
1599     } else if (hasAliases && MO.isDead() &&
1600                TargetRegisterInfo::isPhysicalRegister(Reg)) {
1601       // There exists a super-register that's marked dead.
1602       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1603         return true;
1604       if (RegInfo->getSubRegisters(IncomingReg) &&
1605           RegInfo->getSuperRegisters(Reg) &&
1606           RegInfo->isSubRegister(IncomingReg, Reg))
1607         DeadOps.push_back(i);
1608     }
1609   }
1610
1611   // Trim unneeded dead operands.
1612   while (!DeadOps.empty()) {
1613     unsigned OpIdx = DeadOps.back();
1614     if (getOperand(OpIdx).isImplicit())
1615       RemoveOperand(OpIdx);
1616     else
1617       getOperand(OpIdx).setIsDead(false);
1618     DeadOps.pop_back();
1619   }
1620
1621   // If not found, this means an alias of one of the operands is dead. Add a
1622   // new implicit operand if required.
1623   if (Found || !AddIfNotFound)
1624     return Found;
1625     
1626   addOperand(MachineOperand::CreateReg(IncomingReg,
1627                                        true  /*IsDef*/,
1628                                        true  /*IsImp*/,
1629                                        false /*IsKill*/,
1630                                        true  /*IsDead*/));
1631   return true;
1632 }
1633
1634 void MachineInstr::addRegisterDefined(unsigned IncomingReg,
1635                                       const TargetRegisterInfo *RegInfo) {
1636   if (TargetRegisterInfo::isPhysicalRegister(IncomingReg)) {
1637     MachineOperand *MO = findRegisterDefOperand(IncomingReg, false, RegInfo);
1638     if (MO)
1639       return;
1640   } else {
1641     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1642       const MachineOperand &MO = getOperand(i);
1643       if (MO.isReg() && MO.getReg() == IncomingReg && MO.isDef() &&
1644           MO.getSubReg() == 0)
1645         return;
1646     }
1647   }
1648   addOperand(MachineOperand::CreateReg(IncomingReg,
1649                                        true  /*IsDef*/,
1650                                        true  /*IsImp*/));
1651 }
1652
1653 void MachineInstr::setPhysRegsDeadExcept(const SmallVectorImpl<unsigned> &UsedRegs,
1654                                          const TargetRegisterInfo &TRI) {
1655   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1656     MachineOperand &MO = getOperand(i);
1657     if (!MO.isReg() || !MO.isDef()) continue;
1658     unsigned Reg = MO.getReg();
1659     if (Reg == 0) continue;
1660     bool Dead = true;
1661     for (SmallVectorImpl<unsigned>::const_iterator I = UsedRegs.begin(),
1662          E = UsedRegs.end(); I != E; ++I)
1663       if (TRI.regsOverlap(*I, Reg)) {
1664         Dead = false;
1665         break;
1666       }
1667     // If there are no uses, including partial uses, the def is dead.
1668     if (Dead) MO.setIsDead();
1669   }
1670 }
1671
1672 unsigned
1673 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1674   unsigned Hash = MI->getOpcode() * 37;
1675   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1676     const MachineOperand &MO = MI->getOperand(i);
1677     uint64_t Key = (uint64_t)MO.getType() << 32;
1678     switch (MO.getType()) {
1679     default: break;
1680     case MachineOperand::MO_Register:
1681       if (MO.isDef() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1682         continue;  // Skip virtual register defs.
1683       Key |= MO.getReg();
1684       break;
1685     case MachineOperand::MO_Immediate:
1686       Key |= MO.getImm();
1687       break;
1688     case MachineOperand::MO_FrameIndex:
1689     case MachineOperand::MO_ConstantPoolIndex:
1690     case MachineOperand::MO_JumpTableIndex:
1691       Key |= MO.getIndex();
1692       break;
1693     case MachineOperand::MO_MachineBasicBlock:
1694       Key |= DenseMapInfo<void*>::getHashValue(MO.getMBB());
1695       break;
1696     case MachineOperand::MO_GlobalAddress:
1697       Key |= DenseMapInfo<void*>::getHashValue(MO.getGlobal());
1698       break;
1699     case MachineOperand::MO_BlockAddress:
1700       Key |= DenseMapInfo<void*>::getHashValue(MO.getBlockAddress());
1701       break;
1702     case MachineOperand::MO_MCSymbol:
1703       Key |= DenseMapInfo<void*>::getHashValue(MO.getMCSymbol());
1704       break;
1705     }
1706     Key += ~(Key << 32);
1707     Key ^= (Key >> 22);
1708     Key += ~(Key << 13);
1709     Key ^= (Key >> 8);
1710     Key += (Key << 3);
1711     Key ^= (Key >> 15);
1712     Key += ~(Key << 27);
1713     Key ^= (Key >> 31);
1714     Hash = (unsigned)Key + Hash * 37;
1715   }
1716   return Hash;
1717 }
1718
1719 void MachineInstr::emitError(StringRef Msg) const {
1720   // Find the source location cookie.
1721   unsigned LocCookie = 0;
1722   const MDNode *LocMD = 0;
1723   for (unsigned i = getNumOperands(); i != 0; --i) {
1724     if (getOperand(i-1).isMetadata() &&
1725         (LocMD = getOperand(i-1).getMetadata()) &&
1726         LocMD->getNumOperands() != 0) {
1727       if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
1728         LocCookie = CI->getZExtValue();
1729         break;
1730       }
1731     }
1732   }
1733
1734   if (const MachineBasicBlock *MBB = getParent())
1735     if (const MachineFunction *MF = MBB->getParent())
1736       return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
1737   report_fatal_error(Msg);
1738 }