f0c1b3714ab8d79bc942e99d61e9be909c24d260
[oota-llvm.git] / lib / Target / X86 / X86InstrInfo.cpp
1 //===- X86InstrInfo.cpp - X86 Instruction Information -----------*- 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 // This file contains the X86 implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "X86InstrInfo.h"
15 #include "X86.h"
16 #include "X86GenInstrInfo.inc"
17 #include "X86InstrBuilder.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86Subtarget.h"
20 #include "X86TargetMachine.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/LiveVariables.h"
26 #include "llvm/Target/TargetOptions.h"
27 using namespace llvm;
28
29 X86InstrInfo::X86InstrInfo(X86TargetMachine &tm)
30   : TargetInstrInfoImpl(X86Insts, array_lengthof(X86Insts)),
31     TM(tm), RI(tm, *this) {
32 }
33
34 bool X86InstrInfo::isMoveInstr(const MachineInstr& MI,
35                                unsigned& sourceReg,
36                                unsigned& destReg) const {
37   MachineOpCode oc = MI.getOpcode();
38   if (oc == X86::MOV8rr || oc == X86::MOV16rr ||
39       oc == X86::MOV32rr || oc == X86::MOV64rr ||
40       oc == X86::MOV16to16_ || oc == X86::MOV32to32_ ||
41       oc == X86::MOV_Fp3232  || oc == X86::MOVSSrr || oc == X86::MOVSDrr ||
42       oc == X86::MOV_Fp3264 || oc == X86::MOV_Fp6432 || oc == X86::MOV_Fp6464 ||
43       oc == X86::FsMOVAPSrr || oc == X86::FsMOVAPDrr ||
44       oc == X86::MOVAPSrr || oc == X86::MOVAPDrr ||
45       oc == X86::MOVSS2PSrr || oc == X86::MOVSD2PDrr ||
46       oc == X86::MOVPS2SSrr || oc == X86::MOVPD2SDrr ||
47       oc == X86::MMX_MOVD64rr || oc == X86::MMX_MOVQ64rr) {
48       assert(MI.getNumOperands() >= 2 &&
49              MI.getOperand(0).isRegister() &&
50              MI.getOperand(1).isRegister() &&
51              "invalid register-register move instruction");
52       sourceReg = MI.getOperand(1).getReg();
53       destReg = MI.getOperand(0).getReg();
54       return true;
55   }
56   return false;
57 }
58
59 unsigned X86InstrInfo::isLoadFromStackSlot(MachineInstr *MI, 
60                                            int &FrameIndex) const {
61   switch (MI->getOpcode()) {
62   default: break;
63   case X86::MOV8rm:
64   case X86::MOV16rm:
65   case X86::MOV16_rm:
66   case X86::MOV32rm:
67   case X86::MOV32_rm:
68   case X86::MOV64rm:
69   case X86::LD_Fp64m:
70   case X86::MOVSSrm:
71   case X86::MOVSDrm:
72   case X86::MOVAPSrm:
73   case X86::MOVAPDrm:
74   case X86::MMX_MOVD64rm:
75   case X86::MMX_MOVQ64rm:
76     if (MI->getOperand(1).isFI() && MI->getOperand(2).isImm() &&
77         MI->getOperand(3).isReg() && MI->getOperand(4).isImm() &&
78         MI->getOperand(2).getImm() == 1 &&
79         MI->getOperand(3).getReg() == 0 &&
80         MI->getOperand(4).getImm() == 0) {
81       FrameIndex = MI->getOperand(1).getIndex();
82       return MI->getOperand(0).getReg();
83     }
84     break;
85   }
86   return 0;
87 }
88
89 unsigned X86InstrInfo::isStoreToStackSlot(MachineInstr *MI,
90                                           int &FrameIndex) const {
91   switch (MI->getOpcode()) {
92   default: break;
93   case X86::MOV8mr:
94   case X86::MOV16mr:
95   case X86::MOV16_mr:
96   case X86::MOV32mr:
97   case X86::MOV32_mr:
98   case X86::MOV64mr:
99   case X86::ST_FpP64m:
100   case X86::MOVSSmr:
101   case X86::MOVSDmr:
102   case X86::MOVAPSmr:
103   case X86::MOVAPDmr:
104   case X86::MMX_MOVD64mr:
105   case X86::MMX_MOVQ64mr:
106   case X86::MMX_MOVNTQmr:
107     if (MI->getOperand(0).isFI() && MI->getOperand(1).isImm() &&
108         MI->getOperand(2).isReg() && MI->getOperand(3).isImm() &&
109         MI->getOperand(1).getImm() == 1 &&
110         MI->getOperand(2).getReg() == 0 &&
111         MI->getOperand(3).getImm() == 0) {
112       FrameIndex = MI->getOperand(0).getIndex();
113       return MI->getOperand(4).getReg();
114     }
115     break;
116   }
117   return 0;
118 }
119
120
121 bool X86InstrInfo::isReallyTriviallyReMaterializable(MachineInstr *MI) const {
122   switch (MI->getOpcode()) {
123   default: break;
124   case X86::MOV8rm:
125   case X86::MOV16rm:
126   case X86::MOV16_rm:
127   case X86::MOV32rm:
128   case X86::MOV32_rm:
129   case X86::MOV64rm:
130   case X86::LD_Fp64m:
131   case X86::MOVSSrm:
132   case X86::MOVSDrm:
133   case X86::MOVAPSrm:
134   case X86::MOVAPDrm:
135   case X86::MMX_MOVD64rm:
136   case X86::MMX_MOVQ64rm:
137     // Loads from constant pools are trivially rematerializable.
138     if (MI->getOperand(1).isReg() && MI->getOperand(2).isImm() &&
139         MI->getOperand(3).isReg() && MI->getOperand(4).isCPI() &&
140         MI->getOperand(1).getReg() == 0 &&
141         MI->getOperand(2).getImm() == 1 &&
142         MI->getOperand(3).getReg() == 0)
143       return true;
144     return false;
145   }
146   // All other instructions marked M_REMATERIALIZABLE are always trivially
147   // rematerializable.
148   return true;
149 }
150
151 /// isReallySideEffectFree - If the M_MAY_HAVE_SIDE_EFFECTS flag is set, this
152 /// method is called to determine if the specific instance of this instruction
153 /// has side effects. This is useful in cases of instructions, like loads, which
154 /// generally always have side effects. A load from a constant pool doesn't have
155 /// side effects, though. So we need to differentiate it from the general case.
156 bool X86InstrInfo::isReallySideEffectFree(MachineInstr *MI) const {
157   switch (MI->getOpcode()) {
158   default: break;
159   case X86::MOV32rm:
160     if (MI->getOperand(1).isRegister()) {
161       unsigned Reg = MI->getOperand(1).getReg();
162
163       // Loads from global addresses which aren't redefined in the function are
164       // side effect free.
165       if (Reg != 0 && MRegisterInfo::isVirtualRegister(Reg) &&
166           MI->getOperand(2).isImmediate() &&
167           MI->getOperand(3).isRegister() &&
168           MI->getOperand(4).isGlobalAddress() &&
169           MI->getOperand(2).getImm() == 1 &&
170           MI->getOperand(3).getReg() == 0)
171         return true;
172     }
173     break;
174   }
175
176   // Anything that is rematerializable obviously has no side effects.
177   return isReallyTriviallyReMaterializable(MI);
178 }
179
180 /// hasLiveCondCodeDef - True if MI has a condition code def, e.g. EFLAGS, that
181 /// is not marked dead.
182 static bool hasLiveCondCodeDef(MachineInstr *MI) {
183   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
184     MachineOperand &MO = MI->getOperand(i);
185     if (MO.isRegister() && MO.isDef() &&
186         MO.getReg() == X86::EFLAGS && !MO.isDead()) {
187       return true;
188     }
189   }
190   return false;
191 }
192
193 /// convertToThreeAddress - This method must be implemented by targets that
194 /// set the M_CONVERTIBLE_TO_3_ADDR flag.  When this flag is set, the target
195 /// may be able to convert a two-address instruction into a true
196 /// three-address instruction on demand.  This allows the X86 target (for
197 /// example) to convert ADD and SHL instructions into LEA instructions if they
198 /// would require register copies due to two-addressness.
199 ///
200 /// This method returns a null pointer if the transformation cannot be
201 /// performed, otherwise it returns the new instruction.
202 ///
203 MachineInstr *
204 X86InstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
205                                     MachineBasicBlock::iterator &MBBI,
206                                     LiveVariables &LV) const {
207   MachineInstr *MI = MBBI;
208   // All instructions input are two-addr instructions.  Get the known operands.
209   unsigned Dest = MI->getOperand(0).getReg();
210   unsigned Src = MI->getOperand(1).getReg();
211
212   MachineInstr *NewMI = NULL;
213   // FIXME: 16-bit LEA's are really slow on Athlons, but not bad on P4's.  When
214   // we have better subtarget support, enable the 16-bit LEA generation here.
215   bool DisableLEA16 = true;
216
217   unsigned MIOpc = MI->getOpcode();
218   switch (MIOpc) {
219   case X86::SHUFPSrri: {
220     assert(MI->getNumOperands() == 4 && "Unknown shufps instruction!");
221     if (!TM.getSubtarget<X86Subtarget>().hasSSE2()) return 0;
222     
223     unsigned A = MI->getOperand(0).getReg();
224     unsigned B = MI->getOperand(1).getReg();
225     unsigned C = MI->getOperand(2).getReg();
226     unsigned M = MI->getOperand(3).getImm();
227     if (B != C) return 0;
228     NewMI = BuildMI(get(X86::PSHUFDri), A).addReg(B).addImm(M);
229     break;
230   }
231   case X86::SHL64ri: {
232     assert(MI->getNumOperands() >= 3 && "Unknown shift instruction!");
233     // NOTE: LEA doesn't produce flags like shift does, but LLVM never uses
234     // the flags produced by a shift yet, so this is safe.
235     unsigned Dest = MI->getOperand(0).getReg();
236     unsigned Src = MI->getOperand(1).getReg();
237     unsigned ShAmt = MI->getOperand(2).getImm();
238     if (ShAmt == 0 || ShAmt >= 4) return 0;
239     
240     NewMI = BuildMI(get(X86::LEA64r), Dest)
241       .addReg(0).addImm(1 << ShAmt).addReg(Src).addImm(0);
242     break;
243   }
244   case X86::SHL32ri: {
245     assert(MI->getNumOperands() >= 3 && "Unknown shift instruction!");
246     // NOTE: LEA doesn't produce flags like shift does, but LLVM never uses
247     // the flags produced by a shift yet, so this is safe.
248     unsigned Dest = MI->getOperand(0).getReg();
249     unsigned Src = MI->getOperand(1).getReg();
250     unsigned ShAmt = MI->getOperand(2).getImm();
251     if (ShAmt == 0 || ShAmt >= 4) return 0;
252     
253     unsigned Opc = TM.getSubtarget<X86Subtarget>().is64Bit() ?
254       X86::LEA64_32r : X86::LEA32r;
255     NewMI = BuildMI(get(Opc), Dest)
256       .addReg(0).addImm(1 << ShAmt).addReg(Src).addImm(0);
257     break;
258   }
259   case X86::SHL16ri: {
260     assert(MI->getNumOperands() >= 3 && "Unknown shift instruction!");
261     // NOTE: LEA doesn't produce flags like shift does, but LLVM never uses
262     // the flags produced by a shift yet, so this is safe.
263     unsigned Dest = MI->getOperand(0).getReg();
264     unsigned Src = MI->getOperand(1).getReg();
265     unsigned ShAmt = MI->getOperand(2).getImm();
266     if (ShAmt == 0 || ShAmt >= 4) return 0;
267     
268     if (DisableLEA16) {
269       // If 16-bit LEA is disabled, use 32-bit LEA via subregisters.
270       MachineRegisterInfo &RegInfo = MFI->getParent()->getRegInfo();
271       unsigned Opc = TM.getSubtarget<X86Subtarget>().is64Bit()
272         ? X86::LEA64_32r : X86::LEA32r;
273       unsigned leaInReg = RegInfo.createVirtualRegister(&X86::GR32RegClass);
274       unsigned leaOutReg = RegInfo.createVirtualRegister(&X86::GR32RegClass);
275             
276       MachineInstr *Ins =
277         BuildMI(get(X86::INSERT_SUBREG), leaInReg).addReg(Src).addImm(2);
278       Ins->copyKillDeadInfo(MI);
279       
280       NewMI = BuildMI(get(Opc), leaOutReg)
281         .addReg(0).addImm(1 << ShAmt).addReg(leaInReg).addImm(0);
282       
283       MachineInstr *Ext =
284         BuildMI(get(X86::EXTRACT_SUBREG), Dest).addReg(leaOutReg).addImm(2);
285       Ext->copyKillDeadInfo(MI);
286       
287       MFI->insert(MBBI, Ins);            // Insert the insert_subreg
288       LV.instructionChanged(MI, NewMI);  // Update live variables
289       LV.addVirtualRegisterKilled(leaInReg, NewMI);
290       MFI->insert(MBBI, NewMI);          // Insert the new inst
291       LV.addVirtualRegisterKilled(leaOutReg, Ext);
292       MFI->insert(MBBI, Ext);            // Insert the extract_subreg      
293       return Ext;
294     } else {
295       NewMI = BuildMI(get(X86::LEA16r), Dest)
296         .addReg(0).addImm(1 << ShAmt).addReg(Src).addImm(0);
297     }
298     break;
299   }
300   default: {
301     // The following opcodes also sets the condition code register(s). Only
302     // convert them to equivalent lea if the condition code register def's
303     // are dead!
304     if (hasLiveCondCodeDef(MI))
305       return 0;
306
307     bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
308     switch (MIOpc) {
309     default: return 0;
310     case X86::INC64r:
311     case X86::INC32r: {
312       assert(MI->getNumOperands() >= 2 && "Unknown inc instruction!");
313       unsigned Opc = MIOpc == X86::INC64r ? X86::LEA64r
314         : (is64Bit ? X86::LEA64_32r : X86::LEA32r);
315       NewMI = addRegOffset(BuildMI(get(Opc), Dest), Src, 1);
316       break;
317     }
318     case X86::INC16r:
319     case X86::INC64_16r:
320       if (DisableLEA16) return 0;
321       assert(MI->getNumOperands() >= 2 && "Unknown inc instruction!");
322       NewMI = addRegOffset(BuildMI(get(X86::LEA16r), Dest), Src, 1);
323       break;
324     case X86::DEC64r:
325     case X86::DEC32r: {
326       assert(MI->getNumOperands() >= 2 && "Unknown dec instruction!");
327       unsigned Opc = MIOpc == X86::DEC64r ? X86::LEA64r
328         : (is64Bit ? X86::LEA64_32r : X86::LEA32r);
329       NewMI = addRegOffset(BuildMI(get(Opc), Dest), Src, -1);
330       break;
331     }
332     case X86::DEC16r:
333     case X86::DEC64_16r:
334       if (DisableLEA16) return 0;
335       assert(MI->getNumOperands() >= 2 && "Unknown dec instruction!");
336       NewMI = addRegOffset(BuildMI(get(X86::LEA16r), Dest), Src, -1);
337       break;
338     case X86::ADD64rr:
339     case X86::ADD32rr: {
340       assert(MI->getNumOperands() >= 3 && "Unknown add instruction!");
341       unsigned Opc = MIOpc == X86::ADD64rr ? X86::LEA64r
342         : (is64Bit ? X86::LEA64_32r : X86::LEA32r);
343       NewMI = addRegReg(BuildMI(get(Opc), Dest), Src,
344                         MI->getOperand(2).getReg());
345       break;
346     }
347     case X86::ADD16rr:
348       if (DisableLEA16) return 0;
349       assert(MI->getNumOperands() >= 3 && "Unknown add instruction!");
350       NewMI = addRegReg(BuildMI(get(X86::LEA16r), Dest), Src,
351                         MI->getOperand(2).getReg());
352       break;
353     case X86::ADD64ri32:
354     case X86::ADD64ri8:
355       assert(MI->getNumOperands() >= 3 && "Unknown add instruction!");
356       if (MI->getOperand(2).isImmediate())
357         NewMI = addRegOffset(BuildMI(get(X86::LEA64r), Dest), Src,
358                              MI->getOperand(2).getImm());
359       break;
360     case X86::ADD32ri:
361     case X86::ADD32ri8:
362       assert(MI->getNumOperands() >= 3 && "Unknown add instruction!");
363       if (MI->getOperand(2).isImmediate()) {
364         unsigned Opc = is64Bit ? X86::LEA64_32r : X86::LEA32r;
365         NewMI = addRegOffset(BuildMI(get(Opc), Dest), Src,
366                              MI->getOperand(2).getImm());
367       }
368       break;
369     case X86::ADD16ri:
370     case X86::ADD16ri8:
371       if (DisableLEA16) return 0;
372       assert(MI->getNumOperands() >= 3 && "Unknown add instruction!");
373       if (MI->getOperand(2).isImmediate())
374         NewMI = addRegOffset(BuildMI(get(X86::LEA16r), Dest), Src,
375                              MI->getOperand(2).getImm());
376       break;
377     case X86::SHL16ri:
378       if (DisableLEA16) return 0;
379     case X86::SHL32ri:
380     case X86::SHL64ri: {
381       assert(MI->getNumOperands() >= 3 && MI->getOperand(2).isImmediate() &&
382              "Unknown shl instruction!");
383       unsigned ShAmt = MI->getOperand(2).getImm();
384       if (ShAmt == 1 || ShAmt == 2 || ShAmt == 3) {
385         X86AddressMode AM;
386         AM.Scale = 1 << ShAmt;
387         AM.IndexReg = Src;
388         unsigned Opc = MIOpc == X86::SHL64ri ? X86::LEA64r
389           : (MIOpc == X86::SHL32ri
390              ? (is64Bit ? X86::LEA64_32r : X86::LEA32r) : X86::LEA16r);
391         NewMI = addFullAddress(BuildMI(get(Opc), Dest), AM);
392       }
393       break;
394     }
395     }
396   }
397   }
398
399   NewMI->copyKillDeadInfo(MI);
400   LV.instructionChanged(MI, NewMI);  // Update live variables
401   MFI->insert(MBBI, NewMI);          // Insert the new inst    
402   return NewMI;
403 }
404
405 /// commuteInstruction - We have a few instructions that must be hacked on to
406 /// commute them.
407 ///
408 MachineInstr *X86InstrInfo::commuteInstruction(MachineInstr *MI) const {
409   switch (MI->getOpcode()) {
410   case X86::SHRD16rri8: // A = SHRD16rri8 B, C, I -> A = SHLD16rri8 C, B, (16-I)
411   case X86::SHLD16rri8: // A = SHLD16rri8 B, C, I -> A = SHRD16rri8 C, B, (16-I)
412   case X86::SHRD32rri8: // A = SHRD32rri8 B, C, I -> A = SHLD32rri8 C, B, (32-I)
413   case X86::SHLD32rri8: // A = SHLD32rri8 B, C, I -> A = SHRD32rri8 C, B, (32-I)
414   case X86::SHRD64rri8: // A = SHRD64rri8 B, C, I -> A = SHLD64rri8 C, B, (64-I)
415   case X86::SHLD64rri8:{// A = SHLD64rri8 B, C, I -> A = SHRD64rri8 C, B, (64-I)
416     unsigned Opc;
417     unsigned Size;
418     switch (MI->getOpcode()) {
419     default: assert(0 && "Unreachable!");
420     case X86::SHRD16rri8: Size = 16; Opc = X86::SHLD16rri8; break;
421     case X86::SHLD16rri8: Size = 16; Opc = X86::SHRD16rri8; break;
422     case X86::SHRD32rri8: Size = 32; Opc = X86::SHLD32rri8; break;
423     case X86::SHLD32rri8: Size = 32; Opc = X86::SHRD32rri8; break;
424     case X86::SHRD64rri8: Size = 64; Opc = X86::SHLD64rri8; break;
425     case X86::SHLD64rri8: Size = 64; Opc = X86::SHRD64rri8; break;
426     }
427     unsigned Amt = MI->getOperand(3).getImm();
428     unsigned A = MI->getOperand(0).getReg();
429     unsigned B = MI->getOperand(1).getReg();
430     unsigned C = MI->getOperand(2).getReg();
431     bool BisKill = MI->getOperand(1).isKill();
432     bool CisKill = MI->getOperand(2).isKill();
433     return BuildMI(get(Opc), A).addReg(C, false, false, CisKill)
434       .addReg(B, false, false, BisKill).addImm(Size-Amt);
435   }
436   case X86::CMOVB16rr:
437   case X86::CMOVB32rr:
438   case X86::CMOVB64rr:
439   case X86::CMOVAE16rr:
440   case X86::CMOVAE32rr:
441   case X86::CMOVAE64rr:
442   case X86::CMOVE16rr:
443   case X86::CMOVE32rr:
444   case X86::CMOVE64rr:
445   case X86::CMOVNE16rr:
446   case X86::CMOVNE32rr:
447   case X86::CMOVNE64rr:
448   case X86::CMOVBE16rr:
449   case X86::CMOVBE32rr:
450   case X86::CMOVBE64rr:
451   case X86::CMOVA16rr:
452   case X86::CMOVA32rr:
453   case X86::CMOVA64rr:
454   case X86::CMOVL16rr:
455   case X86::CMOVL32rr:
456   case X86::CMOVL64rr:
457   case X86::CMOVGE16rr:
458   case X86::CMOVGE32rr:
459   case X86::CMOVGE64rr:
460   case X86::CMOVLE16rr:
461   case X86::CMOVLE32rr:
462   case X86::CMOVLE64rr:
463   case X86::CMOVG16rr:
464   case X86::CMOVG32rr:
465   case X86::CMOVG64rr:
466   case X86::CMOVS16rr:
467   case X86::CMOVS32rr:
468   case X86::CMOVS64rr:
469   case X86::CMOVNS16rr:
470   case X86::CMOVNS32rr:
471   case X86::CMOVNS64rr:
472   case X86::CMOVP16rr:
473   case X86::CMOVP32rr:
474   case X86::CMOVP64rr:
475   case X86::CMOVNP16rr:
476   case X86::CMOVNP32rr:
477   case X86::CMOVNP64rr: {
478     unsigned Opc = 0;
479     switch (MI->getOpcode()) {
480     default: break;
481     case X86::CMOVB16rr:  Opc = X86::CMOVAE16rr; break;
482     case X86::CMOVB32rr:  Opc = X86::CMOVAE32rr; break;
483     case X86::CMOVB64rr:  Opc = X86::CMOVAE64rr; break;
484     case X86::CMOVAE16rr: Opc = X86::CMOVB16rr; break;
485     case X86::CMOVAE32rr: Opc = X86::CMOVB32rr; break;
486     case X86::CMOVAE64rr: Opc = X86::CMOVB64rr; break;
487     case X86::CMOVE16rr:  Opc = X86::CMOVNE16rr; break;
488     case X86::CMOVE32rr:  Opc = X86::CMOVNE32rr; break;
489     case X86::CMOVE64rr:  Opc = X86::CMOVNE64rr; break;
490     case X86::CMOVNE16rr: Opc = X86::CMOVE16rr; break;
491     case X86::CMOVNE32rr: Opc = X86::CMOVE32rr; break;
492     case X86::CMOVNE64rr: Opc = X86::CMOVE64rr; break;
493     case X86::CMOVBE16rr: Opc = X86::CMOVA16rr; break;
494     case X86::CMOVBE32rr: Opc = X86::CMOVA32rr; break;
495     case X86::CMOVBE64rr: Opc = X86::CMOVA64rr; break;
496     case X86::CMOVA16rr:  Opc = X86::CMOVBE16rr; break;
497     case X86::CMOVA32rr:  Opc = X86::CMOVBE32rr; break;
498     case X86::CMOVA64rr:  Opc = X86::CMOVBE64rr; break;
499     case X86::CMOVL16rr:  Opc = X86::CMOVGE16rr; break;
500     case X86::CMOVL32rr:  Opc = X86::CMOVGE32rr; break;
501     case X86::CMOVL64rr:  Opc = X86::CMOVGE64rr; break;
502     case X86::CMOVGE16rr: Opc = X86::CMOVL16rr; break;
503     case X86::CMOVGE32rr: Opc = X86::CMOVL32rr; break;
504     case X86::CMOVGE64rr: Opc = X86::CMOVL64rr; break;
505     case X86::CMOVLE16rr: Opc = X86::CMOVG16rr; break;
506     case X86::CMOVLE32rr: Opc = X86::CMOVG32rr; break;
507     case X86::CMOVLE64rr: Opc = X86::CMOVG64rr; break;
508     case X86::CMOVG16rr:  Opc = X86::CMOVLE16rr; break;
509     case X86::CMOVG32rr:  Opc = X86::CMOVLE32rr; break;
510     case X86::CMOVG64rr:  Opc = X86::CMOVLE64rr; break;
511     case X86::CMOVS16rr:  Opc = X86::CMOVNS16rr; break;
512     case X86::CMOVS32rr:  Opc = X86::CMOVNS32rr; break;
513     case X86::CMOVS64rr:  Opc = X86::CMOVNS32rr; break;
514     case X86::CMOVNS16rr: Opc = X86::CMOVS16rr; break;
515     case X86::CMOVNS32rr: Opc = X86::CMOVS32rr; break;
516     case X86::CMOVNS64rr: Opc = X86::CMOVS64rr; break;
517     case X86::CMOVP16rr:  Opc = X86::CMOVNP16rr; break;
518     case X86::CMOVP32rr:  Opc = X86::CMOVNP32rr; break;
519     case X86::CMOVP64rr:  Opc = X86::CMOVNP32rr; break;
520     case X86::CMOVNP16rr: Opc = X86::CMOVP16rr; break;
521     case X86::CMOVNP32rr: Opc = X86::CMOVP32rr; break;
522     case X86::CMOVNP64rr: Opc = X86::CMOVP64rr; break;
523     }
524
525     MI->setInstrDescriptor(get(Opc));
526     // Fallthrough intended.
527   }
528   default:
529     return TargetInstrInfoImpl::commuteInstruction(MI);
530   }
531 }
532
533 static X86::CondCode GetCondFromBranchOpc(unsigned BrOpc) {
534   switch (BrOpc) {
535   default: return X86::COND_INVALID;
536   case X86::JE:  return X86::COND_E;
537   case X86::JNE: return X86::COND_NE;
538   case X86::JL:  return X86::COND_L;
539   case X86::JLE: return X86::COND_LE;
540   case X86::JG:  return X86::COND_G;
541   case X86::JGE: return X86::COND_GE;
542   case X86::JB:  return X86::COND_B;
543   case X86::JBE: return X86::COND_BE;
544   case X86::JA:  return X86::COND_A;
545   case X86::JAE: return X86::COND_AE;
546   case X86::JS:  return X86::COND_S;
547   case X86::JNS: return X86::COND_NS;
548   case X86::JP:  return X86::COND_P;
549   case X86::JNP: return X86::COND_NP;
550   case X86::JO:  return X86::COND_O;
551   case X86::JNO: return X86::COND_NO;
552   }
553 }
554
555 unsigned X86::GetCondBranchFromCond(X86::CondCode CC) {
556   switch (CC) {
557   default: assert(0 && "Illegal condition code!");
558   case X86::COND_E:  return X86::JE;
559   case X86::COND_NE: return X86::JNE;
560   case X86::COND_L:  return X86::JL;
561   case X86::COND_LE: return X86::JLE;
562   case X86::COND_G:  return X86::JG;
563   case X86::COND_GE: return X86::JGE;
564   case X86::COND_B:  return X86::JB;
565   case X86::COND_BE: return X86::JBE;
566   case X86::COND_A:  return X86::JA;
567   case X86::COND_AE: return X86::JAE;
568   case X86::COND_S:  return X86::JS;
569   case X86::COND_NS: return X86::JNS;
570   case X86::COND_P:  return X86::JP;
571   case X86::COND_NP: return X86::JNP;
572   case X86::COND_O:  return X86::JO;
573   case X86::COND_NO: return X86::JNO;
574   }
575 }
576
577 /// GetOppositeBranchCondition - Return the inverse of the specified condition,
578 /// e.g. turning COND_E to COND_NE.
579 X86::CondCode X86::GetOppositeBranchCondition(X86::CondCode CC) {
580   switch (CC) {
581   default: assert(0 && "Illegal condition code!");
582   case X86::COND_E:  return X86::COND_NE;
583   case X86::COND_NE: return X86::COND_E;
584   case X86::COND_L:  return X86::COND_GE;
585   case X86::COND_LE: return X86::COND_G;
586   case X86::COND_G:  return X86::COND_LE;
587   case X86::COND_GE: return X86::COND_L;
588   case X86::COND_B:  return X86::COND_AE;
589   case X86::COND_BE: return X86::COND_A;
590   case X86::COND_A:  return X86::COND_BE;
591   case X86::COND_AE: return X86::COND_B;
592   case X86::COND_S:  return X86::COND_NS;
593   case X86::COND_NS: return X86::COND_S;
594   case X86::COND_P:  return X86::COND_NP;
595   case X86::COND_NP: return X86::COND_P;
596   case X86::COND_O:  return X86::COND_NO;
597   case X86::COND_NO: return X86::COND_O;
598   }
599 }
600
601 bool X86InstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
602   const TargetInstrDescriptor *TID = MI->getInstrDescriptor();
603   if (TID->Flags & M_TERMINATOR_FLAG) {
604     // Conditional branch is a special case.
605     if ((TID->Flags & M_BRANCH_FLAG) != 0 && (TID->Flags & M_BARRIER_FLAG) == 0)
606       return true;
607     if ((TID->Flags & M_PREDICABLE) == 0)
608       return true;
609     return !isPredicated(MI);
610   }
611   return false;
612 }
613
614 // For purposes of branch analysis do not count FP_REG_KILL as a terminator.
615 static bool isBrAnalysisUnpredicatedTerminator(const MachineInstr *MI,
616                                                const X86InstrInfo &TII) {
617   if (MI->getOpcode() == X86::FP_REG_KILL)
618     return false;
619   return TII.isUnpredicatedTerminator(MI);
620 }
621
622 bool X86InstrInfo::AnalyzeBranch(MachineBasicBlock &MBB, 
623                                  MachineBasicBlock *&TBB,
624                                  MachineBasicBlock *&FBB,
625                                  std::vector<MachineOperand> &Cond) const {
626   // If the block has no terminators, it just falls into the block after it.
627   MachineBasicBlock::iterator I = MBB.end();
628   if (I == MBB.begin() || !isBrAnalysisUnpredicatedTerminator(--I, *this))
629     return false;
630
631   // Get the last instruction in the block.
632   MachineInstr *LastInst = I;
633   
634   // If there is only one terminator instruction, process it.
635   if (I == MBB.begin() || !isBrAnalysisUnpredicatedTerminator(--I, *this)) {
636     if (!isBranch(LastInst->getOpcode()))
637       return true;
638     
639     // If the block ends with a branch there are 3 possibilities:
640     // it's an unconditional, conditional, or indirect branch.
641     
642     if (LastInst->getOpcode() == X86::JMP) {
643       TBB = LastInst->getOperand(0).getMBB();
644       return false;
645     }
646     X86::CondCode BranchCode = GetCondFromBranchOpc(LastInst->getOpcode());
647     if (BranchCode == X86::COND_INVALID)
648       return true;  // Can't handle indirect branch.
649
650     // Otherwise, block ends with fall-through condbranch.
651     TBB = LastInst->getOperand(0).getMBB();
652     Cond.push_back(MachineOperand::CreateImm(BranchCode));
653     return false;
654   }
655   
656   // Get the instruction before it if it's a terminator.
657   MachineInstr *SecondLastInst = I;
658   
659   // If there are three terminators, we don't know what sort of block this is.
660   if (SecondLastInst && I != MBB.begin() &&
661       isBrAnalysisUnpredicatedTerminator(--I, *this))
662     return true;
663
664   // If the block ends with X86::JMP and a conditional branch, handle it.
665   X86::CondCode BranchCode = GetCondFromBranchOpc(SecondLastInst->getOpcode());
666   if (BranchCode != X86::COND_INVALID && LastInst->getOpcode() == X86::JMP) {
667     TBB = SecondLastInst->getOperand(0).getMBB();
668     Cond.push_back(MachineOperand::CreateImm(BranchCode));
669     FBB = LastInst->getOperand(0).getMBB();
670     return false;
671   }
672
673   // If the block ends with two X86::JMPs, handle it.  The second one is not
674   // executed, so remove it.
675   if (SecondLastInst->getOpcode() == X86::JMP && 
676       LastInst->getOpcode() == X86::JMP) {
677     TBB = SecondLastInst->getOperand(0).getMBB();
678     I = LastInst;
679     I->eraseFromParent();
680     return false;
681   }
682
683   // Otherwise, can't handle this.
684   return true;
685 }
686
687 unsigned X86InstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
688   MachineBasicBlock::iterator I = MBB.end();
689   if (I == MBB.begin()) return 0;
690   --I;
691   if (I->getOpcode() != X86::JMP && 
692       GetCondFromBranchOpc(I->getOpcode()) == X86::COND_INVALID)
693     return 0;
694   
695   // Remove the branch.
696   I->eraseFromParent();
697   
698   I = MBB.end();
699   
700   if (I == MBB.begin()) return 1;
701   --I;
702   if (GetCondFromBranchOpc(I->getOpcode()) == X86::COND_INVALID)
703     return 1;
704   
705   // Remove the branch.
706   I->eraseFromParent();
707   return 2;
708 }
709
710 static const MachineInstrBuilder &X86InstrAddOperand(MachineInstrBuilder &MIB,
711                                                      MachineOperand &MO) {
712   if (MO.isRegister())
713     MIB = MIB.addReg(MO.getReg(), MO.isDef(), MO.isImplicit(),
714                      false, false, MO.getSubReg());
715   else if (MO.isImmediate())
716     MIB = MIB.addImm(MO.getImm());
717   else if (MO.isFrameIndex())
718     MIB = MIB.addFrameIndex(MO.getIndex());
719   else if (MO.isGlobalAddress())
720     MIB = MIB.addGlobalAddress(MO.getGlobal(), MO.getOffset());
721   else if (MO.isConstantPoolIndex())
722     MIB = MIB.addConstantPoolIndex(MO.getIndex(), MO.getOffset());
723   else if (MO.isJumpTableIndex())
724     MIB = MIB.addJumpTableIndex(MO.getIndex());
725   else if (MO.isExternalSymbol())
726     MIB = MIB.addExternalSymbol(MO.getSymbolName());
727   else
728     assert(0 && "Unknown operand for X86InstrAddOperand!");
729
730   return MIB;
731 }
732
733 unsigned
734 X86InstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
735                            MachineBasicBlock *FBB,
736                            const std::vector<MachineOperand> &Cond) const {
737   // Shouldn't be a fall through.
738   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
739   assert((Cond.size() == 1 || Cond.size() == 0) &&
740          "X86 branch conditions have one component!");
741
742   if (FBB == 0) { // One way branch.
743     if (Cond.empty()) {
744       // Unconditional branch?
745       BuildMI(&MBB, get(X86::JMP)).addMBB(TBB);
746     } else {
747       // Conditional branch.
748       unsigned Opc = GetCondBranchFromCond((X86::CondCode)Cond[0].getImm());
749       BuildMI(&MBB, get(Opc)).addMBB(TBB);
750     }
751     return 1;
752   }
753   
754   // Two-way Conditional branch.
755   unsigned Opc = GetCondBranchFromCond((X86::CondCode)Cond[0].getImm());
756   BuildMI(&MBB, get(Opc)).addMBB(TBB);
757   BuildMI(&MBB, get(X86::JMP)).addMBB(FBB);
758   return 2;
759 }
760
761 void X86InstrInfo::copyRegToReg(MachineBasicBlock &MBB,
762                                    MachineBasicBlock::iterator MI,
763                                    unsigned DestReg, unsigned SrcReg,
764                                    const TargetRegisterClass *DestRC,
765                                    const TargetRegisterClass *SrcRC) const {
766   if (DestRC != SrcRC) {
767     // Moving EFLAGS to / from another register requires a push and a pop.
768     if (SrcRC == &X86::CCRRegClass) {
769       assert(SrcReg == X86::EFLAGS);
770       if (DestRC == &X86::GR64RegClass) {
771         BuildMI(MBB, MI, get(X86::PUSHFQ));
772         BuildMI(MBB, MI, get(X86::POP64r), DestReg);
773         return;
774       } else if (DestRC == &X86::GR32RegClass) {
775         BuildMI(MBB, MI, get(X86::PUSHFD));
776         BuildMI(MBB, MI, get(X86::POP32r), DestReg);
777         return;
778       }
779     } else if (DestRC == &X86::CCRRegClass) {
780       assert(DestReg == X86::EFLAGS);
781       if (SrcRC == &X86::GR64RegClass) {
782         BuildMI(MBB, MI, get(X86::PUSH64r)).addReg(SrcReg);
783         BuildMI(MBB, MI, get(X86::POPFQ));
784         return;
785       } else if (SrcRC == &X86::GR32RegClass) {
786         BuildMI(MBB, MI, get(X86::PUSH32r)).addReg(SrcReg);
787         BuildMI(MBB, MI, get(X86::POPFD));
788         return;
789       }
790     }
791     cerr << "Not yet supported!";
792     abort();
793   }
794
795   unsigned Opc;
796   if (DestRC == &X86::GR64RegClass) {
797     Opc = X86::MOV64rr;
798   } else if (DestRC == &X86::GR32RegClass) {
799     Opc = X86::MOV32rr;
800   } else if (DestRC == &X86::GR16RegClass) {
801     Opc = X86::MOV16rr;
802   } else if (DestRC == &X86::GR8RegClass) {
803     Opc = X86::MOV8rr;
804   } else if (DestRC == &X86::GR32_RegClass) {
805     Opc = X86::MOV32_rr;
806   } else if (DestRC == &X86::GR16_RegClass) {
807     Opc = X86::MOV16_rr;
808   } else if (DestRC == &X86::RFP32RegClass) {
809     Opc = X86::MOV_Fp3232;
810   } else if (DestRC == &X86::RFP64RegClass || DestRC == &X86::RSTRegClass) {
811     Opc = X86::MOV_Fp6464;
812   } else if (DestRC == &X86::RFP80RegClass) {
813     Opc = X86::MOV_Fp8080;
814   } else if (DestRC == &X86::FR32RegClass) {
815     Opc = X86::FsMOVAPSrr;
816   } else if (DestRC == &X86::FR64RegClass) {
817     Opc = X86::FsMOVAPDrr;
818   } else if (DestRC == &X86::VR128RegClass) {
819     Opc = X86::MOVAPSrr;
820   } else if (DestRC == &X86::VR64RegClass) {
821     Opc = X86::MMX_MOVQ64rr;
822   } else {
823     assert(0 && "Unknown regclass");
824     abort();
825   }
826   BuildMI(MBB, MI, get(Opc), DestReg).addReg(SrcReg);
827 }
828
829 static unsigned getStoreRegOpcode(const TargetRegisterClass *RC,
830                                   unsigned StackAlign) {
831   unsigned Opc = 0;
832   if (RC == &X86::GR64RegClass) {
833     Opc = X86::MOV64mr;
834   } else if (RC == &X86::GR32RegClass) {
835     Opc = X86::MOV32mr;
836   } else if (RC == &X86::GR16RegClass) {
837     Opc = X86::MOV16mr;
838   } else if (RC == &X86::GR8RegClass) {
839     Opc = X86::MOV8mr;
840   } else if (RC == &X86::GR32_RegClass) {
841     Opc = X86::MOV32_mr;
842   } else if (RC == &X86::GR16_RegClass) {
843     Opc = X86::MOV16_mr;
844   } else if (RC == &X86::RFP80RegClass) {
845     Opc = X86::ST_FpP80m;   // pops
846   } else if (RC == &X86::RFP64RegClass) {
847     Opc = X86::ST_Fp64m;
848   } else if (RC == &X86::RFP32RegClass) {
849     Opc = X86::ST_Fp32m;
850   } else if (RC == &X86::FR32RegClass) {
851     Opc = X86::MOVSSmr;
852   } else if (RC == &X86::FR64RegClass) {
853     Opc = X86::MOVSDmr;
854   } else if (RC == &X86::VR128RegClass) {
855     // FIXME: Use movaps once we are capable of selectively
856     // aligning functions that spill SSE registers on 16-byte boundaries.
857     Opc = StackAlign >= 16 ? X86::MOVAPSmr : X86::MOVUPSmr;
858   } else if (RC == &X86::VR64RegClass) {
859     Opc = X86::MMX_MOVQ64mr;
860   } else {
861     assert(0 && "Unknown regclass");
862     abort();
863   }
864
865   return Opc;
866 }
867
868 void X86InstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
869                                        MachineBasicBlock::iterator MI,
870                                        unsigned SrcReg, bool isKill, int FrameIdx,
871                                        const TargetRegisterClass *RC) const {
872   unsigned Opc = getStoreRegOpcode(RC, RI.getStackAlignment());
873   addFrameReference(BuildMI(MBB, MI, get(Opc)), FrameIdx)
874     .addReg(SrcReg, false, false, isKill);
875 }
876
877 void X86InstrInfo::storeRegToAddr(MachineFunction &MF, unsigned SrcReg,
878                                   bool isKill,
879                                   SmallVectorImpl<MachineOperand> &Addr,
880                                   const TargetRegisterClass *RC,
881                                   SmallVectorImpl<MachineInstr*> &NewMIs) const {
882   unsigned Opc = getStoreRegOpcode(RC, RI.getStackAlignment());
883   MachineInstrBuilder MIB = BuildMI(get(Opc));
884   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
885     MIB = X86InstrAddOperand(MIB, Addr[i]);
886   MIB.addReg(SrcReg, false, false, isKill);
887   NewMIs.push_back(MIB);
888 }
889
890 static unsigned getLoadRegOpcode(const TargetRegisterClass *RC,
891                                  unsigned StackAlign) {
892   unsigned Opc = 0;
893   if (RC == &X86::GR64RegClass) {
894     Opc = X86::MOV64rm;
895   } else if (RC == &X86::GR32RegClass) {
896     Opc = X86::MOV32rm;
897   } else if (RC == &X86::GR16RegClass) {
898     Opc = X86::MOV16rm;
899   } else if (RC == &X86::GR8RegClass) {
900     Opc = X86::MOV8rm;
901   } else if (RC == &X86::GR32_RegClass) {
902     Opc = X86::MOV32_rm;
903   } else if (RC == &X86::GR16_RegClass) {
904     Opc = X86::MOV16_rm;
905   } else if (RC == &X86::RFP80RegClass) {
906     Opc = X86::LD_Fp80m;
907   } else if (RC == &X86::RFP64RegClass) {
908     Opc = X86::LD_Fp64m;
909   } else if (RC == &X86::RFP32RegClass) {
910     Opc = X86::LD_Fp32m;
911   } else if (RC == &X86::FR32RegClass) {
912     Opc = X86::MOVSSrm;
913   } else if (RC == &X86::FR64RegClass) {
914     Opc = X86::MOVSDrm;
915   } else if (RC == &X86::VR128RegClass) {
916     // FIXME: Use movaps once we are capable of selectively
917     // aligning functions that spill SSE registers on 16-byte boundaries.
918     Opc = StackAlign >= 16 ? X86::MOVAPSrm : X86::MOVUPSrm;
919   } else if (RC == &X86::VR64RegClass) {
920     Opc = X86::MMX_MOVQ64rm;
921   } else {
922     assert(0 && "Unknown regclass");
923     abort();
924   }
925
926   return Opc;
927 }
928
929 void X86InstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
930                                            MachineBasicBlock::iterator MI,
931                                            unsigned DestReg, int FrameIdx,
932                                            const TargetRegisterClass *RC) const{
933   unsigned Opc = getLoadRegOpcode(RC, RI.getStackAlignment());
934   addFrameReference(BuildMI(MBB, MI, get(Opc), DestReg), FrameIdx);
935 }
936
937 void X86InstrInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
938                                       SmallVectorImpl<MachineOperand> &Addr,
939                                       const TargetRegisterClass *RC,
940                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
941   unsigned Opc = getLoadRegOpcode(RC, RI.getStackAlignment());
942   MachineInstrBuilder MIB = BuildMI(get(Opc), DestReg);
943   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
944     MIB = X86InstrAddOperand(MIB, Addr[i]);
945   NewMIs.push_back(MIB);
946 }
947
948 bool X86InstrInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
949                                                 MachineBasicBlock::iterator MI,
950                                 const std::vector<CalleeSavedInfo> &CSI) const {
951   if (CSI.empty())
952     return false;
953
954   bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
955   unsigned SlotSize = is64Bit ? 8 : 4;
956
957   MachineFunction &MF = *MBB.getParent();
958   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
959   X86FI->setCalleeSavedFrameSize(CSI.size() * SlotSize);
960   
961   unsigned Opc = is64Bit ? X86::PUSH64r : X86::PUSH32r;
962   for (unsigned i = CSI.size(); i != 0; --i) {
963     unsigned Reg = CSI[i-1].getReg();
964     // Add the callee-saved register as live-in. It's killed at the spill.
965     MBB.addLiveIn(Reg);
966     BuildMI(MBB, MI, get(Opc)).addReg(Reg);
967   }
968   return true;
969 }
970
971 bool X86InstrInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
972                                                  MachineBasicBlock::iterator MI,
973                                 const std::vector<CalleeSavedInfo> &CSI) const {
974   if (CSI.empty())
975     return false;
976     
977   bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
978
979   unsigned Opc = is64Bit ? X86::POP64r : X86::POP32r;
980   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
981     unsigned Reg = CSI[i].getReg();
982     BuildMI(MBB, MI, get(Opc), Reg);
983   }
984   return true;
985 }
986
987 bool X86InstrInfo::BlockHasNoFallThrough(MachineBasicBlock &MBB) const {
988   if (MBB.empty()) return false;
989   
990   switch (MBB.back().getOpcode()) {
991   case X86::TCRETURNri:
992   case X86::TCRETURNdi:
993   case X86::RET:     // Return.
994   case X86::RETI:
995   case X86::TAILJMPd:
996   case X86::TAILJMPr:
997   case X86::TAILJMPm:
998   case X86::JMP:     // Uncond branch.
999   case X86::JMP32r:  // Indirect branch.
1000   case X86::JMP64r:  // Indirect branch (64-bit).
1001   case X86::JMP32m:  // Indirect branch through mem.
1002   case X86::JMP64m:  // Indirect branch through mem (64-bit).
1003     return true;
1004   default: return false;
1005   }
1006 }
1007
1008 bool X86InstrInfo::
1009 ReverseBranchCondition(std::vector<MachineOperand> &Cond) const {
1010   assert(Cond.size() == 1 && "Invalid X86 branch condition!");
1011   Cond[0].setImm(GetOppositeBranchCondition((X86::CondCode)Cond[0].getImm()));
1012   return false;
1013 }
1014
1015 const TargetRegisterClass *X86InstrInfo::getPointerRegClass() const {
1016   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
1017   if (Subtarget->is64Bit())
1018     return &X86::GR64RegClass;
1019   else
1020     return &X86::GR32RegClass;
1021 }