992fba72ca6893083b1887a19f2a844901ecf828
[oota-llvm.git] / lib / Target / X86 / InstSelectSimple.cpp
1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
2 //
3 // This file defines a simple peephole instruction selector for the x86 platform
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "X86.h"
8 #include "X86InstrInfo.h"
9 #include "X86InstrBuilder.h"
10 #include "llvm/Function.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iOperators.h"
13 #include "llvm/iOther.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/iMemory.h"
16 #include "llvm/Type.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Pass.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Support/InstVisitor.h"
23 #include "llvm/Target/MRegisterInfo.h"
24 #include <map>
25
26 using namespace MOTy;  // Get Use, Def, UseAndDef
27
28 namespace {
29   struct ISel : public FunctionPass, InstVisitor<ISel> {
30     TargetMachine &TM;
31     MachineFunction *F;                    // The function we are compiling into
32     MachineBasicBlock *BB;                 // The current MBB we are compiling
33
34     unsigned CurReg;
35     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
36
37     ISel(TargetMachine &tm)
38       : TM(tm), F(0), BB(0), CurReg(MRegisterInfo::FirstVirtualRegister) {}
39
40     /// runOnFunction - Top level implementation of instruction selection for
41     /// the entire function.
42     ///
43     bool runOnFunction(Function &Fn) {
44       F = &MachineFunction::construct(&Fn, TM);
45       visit(Fn);
46       RegMap.clear();
47       CurReg = MRegisterInfo::FirstVirtualRegister;
48       F = 0;
49       return false;  // We never modify the LLVM itself.
50     }
51
52     /// visitBasicBlock - This method is called when we are visiting a new basic
53     /// block.  This simply creates a new MachineBasicBlock to emit code into
54     /// and adds it to the current MachineFunction.  Subsequent visit* for
55     /// instructions will be invoked for all instructions in the basic block.
56     ///
57     void visitBasicBlock(BasicBlock &LLVM_BB) {
58       BB = new MachineBasicBlock(&LLVM_BB);
59       // FIXME: Use the auto-insert form when it's available
60       F->getBasicBlockList().push_back(BB);
61     }
62
63     // Visitation methods for various instructions.  These methods simply emit
64     // fixed X86 code for each instruction.
65     //
66
67     // Control flow operators
68     void visitReturnInst(ReturnInst &RI);
69     void visitBranchInst(BranchInst &BI);
70     void visitCallInst(CallInst &I);
71
72     // Arithmetic operators
73     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
74     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
75     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
76     void visitMul(BinaryOperator &B);
77
78     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
79     void visitRem(BinaryOperator &B) { visitDivRem(B); }
80     void visitDivRem(BinaryOperator &B);
81
82     // Bitwise operators
83     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
84     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
85     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
86
87     // Binary comparison operators
88     void visitSetCCInst(SetCondInst &I, unsigned OpNum);
89     void visitSetEQ(SetCondInst &I) { visitSetCCInst(I, 0); }
90     void visitSetNE(SetCondInst &I) { visitSetCCInst(I, 1); }
91     void visitSetLT(SetCondInst &I) { visitSetCCInst(I, 2); }
92     void visitSetGT(SetCondInst &I) { visitSetCCInst(I, 3); }
93     void visitSetLE(SetCondInst &I) { visitSetCCInst(I, 4); }
94     void visitSetGE(SetCondInst &I) { visitSetCCInst(I, 5); }
95
96     // Memory Instructions
97     void visitLoadInst(LoadInst &I);
98     void visitStoreInst(StoreInst &I);
99
100     // Other operators
101     void visitShiftInst(ShiftInst &I);
102     void visitPHINode(PHINode &I);
103     void visitCastInst(CastInst &I);
104
105     void visitInstruction(Instruction &I) {
106       std::cerr << "Cannot instruction select: " << I;
107       abort();
108     }
109
110     void promote32 (const unsigned targetReg, Value *v);
111     
112     /// copyConstantToRegister - Output the instructions required to put the
113     /// specified constant into the specified register.
114     ///
115     void copyConstantToRegister(Constant *C, unsigned Reg);
116
117     /// getReg - This method turns an LLVM value into a register number.  This
118     /// is guaranteed to produce the same register number for a particular value
119     /// every time it is queried.
120     ///
121     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
122     unsigned getReg(Value *V) {
123       unsigned &Reg = RegMap[V];
124       if (Reg == 0) {
125         Reg = CurReg++;
126         RegMap[V] = Reg;
127
128         // Add the mapping of regnumber => reg class to MachineFunction
129         F->addRegMap(Reg,
130                      TM.getRegisterInfo()->getRegClassForType(V->getType()));
131       }
132
133       // If this operand is a constant, emit the code to copy the constant into
134       // the register here...
135       //
136       if (Constant *C = dyn_cast<Constant>(V))
137         copyConstantToRegister(C, Reg);
138
139       return Reg;
140     }
141   };
142 }
143
144 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
145 /// Representation.
146 ///
147 enum TypeClass {
148   cByte, cShort, cInt, cLong, cFloat, cDouble
149 };
150
151 /// getClass - Turn a primitive type into a "class" number which is based on the
152 /// size of the type, and whether or not it is floating point.
153 ///
154 static inline TypeClass getClass(const Type *Ty) {
155   switch (Ty->getPrimitiveID()) {
156   case Type::SByteTyID:
157   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
158   case Type::ShortTyID:
159   case Type::UShortTyID:  return cShort;     // Short operands are class #1
160   case Type::IntTyID:
161   case Type::UIntTyID:
162   case Type::PointerTyID: return cInt;       // Int's and pointers are class #2
163
164   case Type::LongTyID:
165   case Type::ULongTyID:   return cLong;      // Longs are class #3
166   case Type::FloatTyID:   return cFloat;     // Float is class #4
167   case Type::DoubleTyID:  return cDouble;    // Doubles are class #5
168   default:
169     assert(0 && "Invalid type to getClass!");
170     return cByte;  // not reached
171   }
172 }
173
174
175 /// copyConstantToRegister - Output the instructions required to put the
176 /// specified constant into the specified register.
177 ///
178 void ISel::copyConstantToRegister(Constant *C, unsigned R) {
179   assert (!isa<ConstantExpr>(C) && "Constant expressions not yet handled!\n");
180
181   if (C->getType()->isIntegral()) {
182     unsigned Class = getClass(C->getType());
183     assert(Class != 3 && "Type not handled yet!");
184
185     static const unsigned IntegralOpcodeTab[] = {
186       X86::MOVir8, X86::MOVir16, X86::MOVir32
187     };
188
189     if (C->getType()->isSigned()) {
190       ConstantSInt *CSI = cast<ConstantSInt>(C);
191       BuildMI(BB, IntegralOpcodeTab[Class], 1, R).addSImm(CSI->getValue());
192     } else {
193       ConstantUInt *CUI = cast<ConstantUInt>(C);
194       BuildMI(BB, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
195     }
196   } else {
197     assert(0 && "Type not handled yet!");
198   }
199 }
200
201
202 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
203 /// register, then move it to wherever the result should be. 
204 /// We handle FP setcc instructions by pushing them, doing a
205 /// compare-and-pop-twice, and then copying the concodes to the main
206 /// processor's concodes (I didn't make this up, it's in the Intel manual)
207 ///
208 void ISel::visitSetCCInst(SetCondInst &I, unsigned OpNum) {
209   // The arguments are already supposed to be of the same type.
210   const Type *CompTy = I.getOperand(0)->getType();
211   unsigned reg1 = getReg(I.getOperand(0));
212   unsigned reg2 = getReg(I.getOperand(1));
213
214   unsigned Class = getClass(CompTy);
215   switch (Class) {
216     // Emit: cmp <var1>, <var2> (do the comparison).  We can
217     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
218     // 32-bit.
219   case cByte:
220     BuildMI (BB, X86::CMPrr8, 2).addReg (reg1).addReg (reg2);
221     break;
222   case cShort:
223     BuildMI (BB, X86::CMPrr16, 2).addReg (reg1).addReg (reg2);
224     break;
225   case cInt:
226     BuildMI (BB, X86::CMPrr32, 2).addReg (reg1).addReg (reg2);
227     break;
228
229     // Push the variables on the stack with fldl opcodes.
230     // FIXME: assuming var1, var2 are in memory, if not, spill to
231     // stack first
232   case cFloat:  // Floats
233     BuildMI (BB, X86::FLDr4, 1).addReg (reg1);
234     BuildMI (BB, X86::FLDr4, 1).addReg (reg2);
235     break;
236   case cDouble:  // Doubles
237     BuildMI (BB, X86::FLDr8, 1).addReg (reg1);
238     BuildMI (BB, X86::FLDr8, 1).addReg (reg2);
239     break;
240   case cLong:
241   default:
242     visitInstruction(I);
243   }
244
245   if (CompTy->isFloatingPoint()) {
246     // (Non-trapping) compare and pop twice.
247     BuildMI (BB, X86::FUCOMPP, 0);
248     // Move fp status word (concodes) to ax.
249     BuildMI (BB, X86::FNSTSWr8, 1, X86::AX);
250     // Load real concodes from ax.
251     BuildMI (BB, X86::SAHF, 1).addReg(X86::AH);
252   }
253
254   // Emit setOp instruction (extract concode; clobbers ax),
255   // using the following mapping:
256   // LLVM  -> X86 signed  X86 unsigned
257   // -----    -----       -----
258   // seteq -> sete        sete
259   // setne -> setne       setne
260   // setlt -> setl        setb
261   // setgt -> setg        seta
262   // setle -> setle       setbe
263   // setge -> setge       setae
264
265   static const unsigned OpcodeTab[2][6] = {
266     {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAr, X86::SETBEr, X86::SETAEr},
267     {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGr, X86::SETLEr, X86::SETGEr},
268   };
269
270   BuildMI(BB, OpcodeTab[CompTy->isSigned()][OpNum], 0, X86::AL);
271   
272   // Put it in the result using a move.
273   BuildMI (BB, X86::MOVrr8, 1, getReg(I)).addReg(X86::AL);
274 }
275
276 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
277 /// operand, in the specified target register.
278 void
279 ISel::promote32 (const unsigned targetReg, Value *v)
280 {
281   unsigned vReg = getReg (v);
282   unsigned Class = getClass (v->getType ());
283   bool isUnsigned = v->getType ()->isUnsigned ();
284   assert (((Class == cByte) || (Class == cShort) || (Class == cInt))
285           && "Unpromotable operand class in promote32");
286   switch (Class)
287     {
288     case cByte:
289       // Extend value into target register (8->32)
290       if (isUnsigned)
291         BuildMI (BB, X86::MOVZXr32r8, 1, targetReg).addReg (vReg);
292       else
293         BuildMI (BB, X86::MOVSXr32r8, 1, targetReg).addReg (vReg);
294       break;
295     case cShort:
296       // Extend value into target register (16->32)
297       if (isUnsigned)
298         BuildMI (BB, X86::MOVZXr32r16, 1, targetReg).addReg (vReg);
299       else
300         BuildMI (BB, X86::MOVSXr32r16, 1, targetReg).addReg (vReg);
301       break;
302     case cInt:
303       // Move value into target register (32->32)
304       BuildMI (BB, X86::MOVrr32, 1, targetReg).addReg (vReg);
305       break;
306     }
307 }
308
309 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
310 /// we have the following possibilities:
311 ///
312 ///   ret void: No return value, simply emit a 'ret' instruction
313 ///   ret sbyte, ubyte : Extend value into EAX and return
314 ///   ret short, ushort: Extend value into EAX and return
315 ///   ret int, uint    : Move value into EAX and return
316 ///   ret pointer      : Move value into EAX and return
317 ///   ret long, ulong  : Move value into EAX/EDX and return
318 ///   ret float/double : Top of FP stack
319 ///
320 void
321 ISel::visitReturnInst (ReturnInst &I)
322 {
323   if (I.getNumOperands () == 0)
324     {
325       // Emit a 'ret' instruction
326       BuildMI (BB, X86::RET, 0);
327       return;
328     }
329   Value *rv = I.getOperand (0);
330   unsigned Class = getClass (rv->getType ());
331   switch (Class)
332     {
333       // integral return values: extend or move into EAX and return. 
334     case cByte:
335     case cShort:
336     case cInt:
337       promote32 (X86::EAX, rv);
338       break;
339       // ret float/double: top of FP stack
340       // FLD <val>
341     case cFloat:                // Floats
342       BuildMI (BB, X86::FLDr4, 1).addReg (getReg (rv));
343       break;
344     case cDouble:               // Doubles
345       BuildMI (BB, X86::FLDr8, 1).addReg (getReg (rv));
346       break;
347     case cLong:
348       // ret long: use EAX(least significant 32 bits)/EDX (most
349       // significant 32)...uh, I think so Brain, but how do i call
350       // up the two parts of the value from inside this mouse
351       // cage? *zort*
352     default:
353       visitInstruction (I);
354     }
355   // Emit a 'ret' instruction
356   BuildMI (BB, X86::RET, 0);
357 }
358
359 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
360 /// that since code layout is frozen at this point, that if we are trying to
361 /// jump to a block that is the immediate successor of the current block, we can
362 /// just make a fall-through. (but we don't currently).
363 ///
364 void
365 ISel::visitBranchInst (BranchInst & BI)
366 {
367   if (BI.isConditional ())
368     {
369       BasicBlock *ifTrue = BI.getSuccessor (0);
370       BasicBlock *ifFalse = BI.getSuccessor (1); // this is really unobvious 
371
372       // simplest thing I can think of: compare condition with zero,
373       // followed by jump-if-equal to ifFalse, and jump-if-nonequal to
374       // ifTrue
375       unsigned int condReg = getReg (BI.getCondition ());
376       BuildMI (BB, X86::CMPri8, 2).addReg (condReg).addZImm (0);
377       BuildMI (BB, X86::JNE, 1).addPCDisp (BI.getSuccessor (0));
378       BuildMI (BB, X86::JE, 1).addPCDisp (BI.getSuccessor (1));
379     }
380   else // unconditional branch
381     {
382       BuildMI (BB, X86::JMP, 1).addPCDisp (BI.getSuccessor (0));
383     }
384 }
385
386 /// visitCallInst - Push args on stack and do a procedure call instruction.
387 void
388 ISel::visitCallInst (CallInst & CI)
389 {
390   // Push the arguments on the stack in reverse order, as specified by
391   // the ABI.
392   for (unsigned i = CI.getNumOperands (); i >= 1; --i)
393     {
394       Value *v = CI.getOperand (i);
395       unsigned argReg = getReg (v);
396       switch (getClass (v->getType ()))
397         {
398         case cByte:
399         case cShort:
400           promote32 (X86::EAX, v);
401           BuildMI (BB, X86::PUSHr32, 1).addReg (X86::EAX);
402           break;
403         case cInt:
404         case cFloat:
405           BuildMI (BB, X86::PUSHr32, 1).addReg (argReg);
406           break;
407         default:
408           // FIXME
409           visitInstruction (CI);
410           break;
411         }
412     }
413   // Emit a CALL instruction with PC-relative displacement.
414   BuildMI (BB, X86::CALLpcrel32, 1).addPCDisp (CI.getCalledValue ());
415 }
416
417 /// visitSimpleBinary - Implement simple binary operators for integral types...
418 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
419 /// 4 for Xor.
420 ///
421 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
422   if (B.getType() == Type::BoolTy)  // FIXME: Handle bools for logicals
423     visitInstruction(B);
424
425   unsigned Class = getClass(B.getType());
426   if (Class > 2)  // FIXME: Handle longs
427     visitInstruction(B);
428
429   static const unsigned OpcodeTab[][4] = {
430     // Arithmetic operators
431     { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, 0 },  // ADD
432     { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, 0 },  // SUB
433
434     // Bitwise operators
435     { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 },  // AND
436     { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 },  // OR
437     { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 },  // XOR
438   };
439   
440   unsigned Opcode = OpcodeTab[OperatorClass][Class];
441   unsigned Op0r = getReg(B.getOperand(0));
442   unsigned Op1r = getReg(B.getOperand(1));
443   BuildMI(BB, Opcode, 2, getReg(B)).addReg(Op0r).addReg(Op1r);
444 }
445
446 /// visitMul - Multiplies are not simple binary operators because they must deal
447 /// with the EAX register explicitly.
448 ///
449 void ISel::visitMul(BinaryOperator &I) {
450   unsigned Class = getClass(I.getType());
451   if (Class > 2)  // FIXME: Handle longs
452     visitInstruction(I);
453
454   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
455   static const unsigned MulOpcode[]={ X86::MULrr8, X86::MULrr16, X86::MULrr32 };
456   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
457
458   unsigned Reg     = Regs[Class];
459   unsigned Op0Reg  = getReg(I.getOperand(0));
460   unsigned Op1Reg  = getReg(I.getOperand(1));
461
462   // Put the first operand into one of the A registers...
463   BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
464   
465   // Emit the appropriate multiply instruction...
466   BuildMI(BB, MulOpcode[Class], 1).addReg(Op1Reg);
467
468   // Put the result into the destination register...
469   BuildMI(BB, MovOpcode[Class], 1, getReg(I)).addReg(Reg);
470 }
471
472
473 /// visitDivRem - Handle division and remainder instructions... these
474 /// instruction both require the same instructions to be generated, they just
475 /// select the result from a different register.  Note that both of these
476 /// instructions work differently for signed and unsigned operands.
477 ///
478 void ISel::visitDivRem(BinaryOperator &I) {
479   unsigned Class = getClass(I.getType());
480   if (Class > 2)  // FIXME: Handle longs
481     visitInstruction(I);
482
483   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
484   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
485   static const unsigned ExtOpcode[]={ X86::CBW   , X86::CWD    , X86::CDQ     };
486   static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
487   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
488
489   static const unsigned DivOpcode[][4] = {
490     { X86::DIVrr8 , X86::DIVrr16 , X86::DIVrr32 , 0 },  // Unsigned division
491     { X86::IDIVrr8, X86::IDIVrr16, X86::IDIVrr32, 0 },  // Signed division
492   };
493
494   bool isSigned   = I.getType()->isSigned();
495   unsigned Reg    = Regs[Class];
496   unsigned ExtReg = ExtRegs[Class];
497   unsigned Op0Reg = getReg(I.getOperand(0));
498   unsigned Op1Reg = getReg(I.getOperand(1));
499
500   // Put the first operand into one of the A registers...
501   BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
502
503   if (isSigned) {
504     // Emit a sign extension instruction...
505     BuildMI(BB, ExtOpcode[Class], 1, ExtReg).addReg(Reg);
506   } else {
507     // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
508     BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
509   }
510
511   // Emit the appropriate divide or remainder instruction...
512   BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
513
514   // Figure out which register we want to pick the result out of...
515   unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
516   
517   // Put the result into the destination register...
518   BuildMI(BB, MovOpcode[Class], 1, getReg(I)).addReg(DestReg);
519 }
520
521
522 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
523 /// for constant immediate shift values, and for constant immediate
524 /// shift values equal to 1. Even the general case is sort of special,
525 /// because the shift amount has to be in CL, not just any old register.
526 ///
527 void ISel::visitShiftInst (ShiftInst &I) {
528   unsigned Op0r = getReg (I.getOperand(0));
529   unsigned DestReg = getReg(I);
530   bool isLeftShift = I.getOpcode() == Instruction::Shl;
531   bool isOperandSigned = I.getType()->isUnsigned();
532   unsigned OperandClass = getClass(I.getType());
533
534   if (OperandClass > 2)
535     visitInstruction(I); // Can't handle longs yet!
536
537   if (ConstantUInt *CUI = dyn_cast <ConstantUInt> (I.getOperand (1)))
538     {
539       // The shift amount is constant, guaranteed to be a ubyte. Get its value.
540       assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
541       unsigned char shAmt = CUI->getValue();
542
543       static const unsigned ConstantOperand[][4] = {
544         { X86::SHRir8, X86::SHRir16, X86::SHRir32, 0 },  // SHR
545         { X86::SARir8, X86::SARir16, X86::SARir32, 0 },  // SAR
546         { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 },  // SHL
547         { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 },  // SAL = SHL
548       };
549
550       const unsigned *OpTab = // Figure out the operand table to use
551         ConstantOperand[isLeftShift*2+isOperandSigned];
552
553       // Emit: <insn> reg, shamt  (shift-by-immediate opcode "ir" form.)
554       BuildMI(BB, OpTab[OperandClass], 2, DestReg).addReg(Op0r).addZImm(shAmt);
555     }
556   else
557     {
558       // The shift amount is non-constant.
559       //
560       // In fact, you can only shift with a variable shift amount if
561       // that amount is already in the CL register, so we have to put it
562       // there first.
563       //
564
565       // Emit: move cl, shiftAmount (put the shift amount in CL.)
566       BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
567
568       // This is a shift right (SHR).
569       static const unsigned NonConstantOperand[][4] = {
570         { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32, 0 },  // SHR
571         { X86::SARrr8, X86::SARrr16, X86::SARrr32, 0 },  // SAR
572         { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 },  // SHL
573         { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 },  // SAL = SHL
574       };
575
576       const unsigned *OpTab = // Figure out the operand table to use
577         NonConstantOperand[isLeftShift*2+isOperandSigned];
578
579       BuildMI(BB, OpTab[OperandClass], 1, DestReg).addReg(Op0r);
580     }
581 }
582
583
584 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
585 /// instruction.
586 ///
587 void ISel::visitLoadInst(LoadInst &I) {
588   unsigned Class = getClass(I.getType());
589   if (Class > 2)  // FIXME: Handle longs and others...
590     visitInstruction(I);
591
592   static const unsigned Opcode[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
593
594   unsigned AddressReg = getReg(I.getOperand(0));
595   addDirectMem(BuildMI(BB, Opcode[Class], 4, getReg(I)), AddressReg);
596 }
597
598
599 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
600 /// instruction.
601 ///
602 void ISel::visitStoreInst(StoreInst &I) {
603   unsigned Class = getClass(I.getOperand(0)->getType());
604   if (Class > 2)  // FIXME: Handle longs and others...
605     visitInstruction(I);
606
607   static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
608
609   unsigned ValReg = getReg(I.getOperand(0));
610   unsigned AddressReg = getReg(I.getOperand(1));
611   addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
612 }
613
614
615 /// visitPHINode - Turn an LLVM PHI node into an X86 PHI node...
616 ///
617 void ISel::visitPHINode(PHINode &PN) {
618   MachineInstr *MI = BuildMI(BB, X86::PHI, PN.getNumOperands(), getReg(PN));
619
620   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
621     // FIXME: This will put constants after the PHI nodes in the block, which
622     // is invalid.  They should be put inline into the PHI node eventually.
623     //
624     MI->addRegOperand(getReg(PN.getIncomingValue(i)));
625     MI->addPCDispOperand(PN.getIncomingBlock(i));
626   }
627 }
628
629 /// visitCastInst - Here we have various kinds of copying with or without
630 /// sign extension going on.
631 void
632 ISel::visitCastInst (CastInst &CI)
633 {
634 //> cast larger int to smaller int -->  copy least significant byte/word w/ mov?
635 //
636 //I'm not really sure what to do with this.  We could insert a pseudo-op
637 //that says take the low X bits of a Y bit register, but for now we can just
638 //force the value into, say, EAX, then rip out AL or AX.  The advantage of  
639 //the former is that the register allocator could use any register it wants,
640 //but for now this obviously doesn't matter.  :)
641
642 // if target type is bool
643 // Emit Compare
644 // Emit Set-if-not-zero
645
646 // if size of target type == size of source type
647 // Emit Mov reg(target) <- reg(source)
648
649 // if size of target type > size of source type
650 //      if both types are integer types
651 //              if source type is signed
652 //                 sbyte to short, ushort: Emit movsx 8->16
653 //                 sbyte to int, uint:     Emit movsx 8->32
654 //                 short to int, uint:     Emit movsx 16->32
655 //              else if source type is unsigned
656 //                 ubyte to short, ushort: Emit movzx 8->16
657 //                 ubyte to int, uint:     Emit movzx 8->32
658 //                 ushort to int, uint:    Emit movzx 16->32
659 //      if both types are fp types
660 //              float to double: Emit fstp, fld (???)
661
662   visitInstruction (CI);
663 }
664
665 /// createSimpleX86InstructionSelector - This pass converts an LLVM function
666 /// into a machine code representation is a very simple peep-hole fashion.  The
667 /// generated code sucks but the implementation is nice and simple.
668 ///
669 Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
670   return new ISel(TM);
671 }