brg
[oota-llvm.git] / lib / Target / X86 / X86ISelSimple.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/DerivedTypes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Pass.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Support/InstVisitor.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include <map>
26
27 using namespace MOTy;  // Get Use, Def, UseAndDef
28
29 namespace {
30   struct ISel : public FunctionPass, InstVisitor<ISel> {
31     TargetMachine &TM;
32     MachineFunction *F;                    // The function we are compiling into
33     MachineBasicBlock *BB;                 // The current MBB we are compiling
34
35     unsigned CurReg;
36     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
37
38     ISel(TargetMachine &tm)
39       : TM(tm), F(0), BB(0), CurReg(MRegisterInfo::FirstVirtualRegister) {}
40
41     /// runOnFunction - Top level implementation of instruction selection for
42     /// the entire function.
43     ///
44     bool runOnFunction(Function &Fn) {
45       F = &MachineFunction::construct(&Fn, TM);
46       visit(Fn);
47       RegMap.clear();
48       CurReg = MRegisterInfo::FirstVirtualRegister;
49       F = 0;
50       return false;  // We never modify the LLVM itself.
51     }
52
53     /// visitBasicBlock - This method is called when we are visiting a new basic
54     /// block.  This simply creates a new MachineBasicBlock to emit code into
55     /// and adds it to the current MachineFunction.  Subsequent visit* for
56     /// instructions will be invoked for all instructions in the basic block.
57     ///
58     void visitBasicBlock(BasicBlock &LLVM_BB) {
59       BB = new MachineBasicBlock(&LLVM_BB);
60       // FIXME: Use the auto-insert form when it's available
61       F->getBasicBlockList().push_back(BB);
62     }
63
64     // Visitation methods for various instructions.  These methods simply emit
65     // fixed X86 code for each instruction.
66     //
67
68     // Control flow operators
69     void visitReturnInst(ReturnInst &RI);
70     void visitBranchInst(BranchInst &BI);
71     void visitCallInst(CallInst &I);
72
73     // Arithmetic operators
74     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
75     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
76     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
77     void doMultiply(unsigned destReg, const Type *resultType,
78                     unsigned op0Reg, unsigned op1Reg);
79     void visitMul(BinaryOperator &B);
80
81     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
82     void visitRem(BinaryOperator &B) { visitDivRem(B); }
83     void visitDivRem(BinaryOperator &B);
84
85     // Bitwise operators
86     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
87     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
88     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
89
90     // Binary comparison operators
91     void visitSetCCInst(SetCondInst &I, unsigned OpNum);
92     void visitSetEQ(SetCondInst &I) { visitSetCCInst(I, 0); }
93     void visitSetNE(SetCondInst &I) { visitSetCCInst(I, 1); }
94     void visitSetLT(SetCondInst &I) { visitSetCCInst(I, 2); }
95     void visitSetGT(SetCondInst &I) { visitSetCCInst(I, 3); }
96     void visitSetLE(SetCondInst &I) { visitSetCCInst(I, 4); }
97     void visitSetGE(SetCondInst &I) { visitSetCCInst(I, 5); }
98
99     // Memory Instructions
100     void visitLoadInst(LoadInst &I);
101     void visitStoreInst(StoreInst &I);
102     void visitGetElementPtrInst(GetElementPtrInst &I);
103     void visitMallocInst(MallocInst &I);
104     void visitFreeInst(FreeInst &I);
105     void visitAllocaInst(AllocaInst &I);
106     
107     // Other operators
108     void visitShiftInst(ShiftInst &I);
109     void visitPHINode(PHINode &I);
110     void visitCastInst(CastInst &I);
111
112     void visitInstruction(Instruction &I) {
113       std::cerr << "Cannot instruction select: " << I;
114       abort();
115     }
116
117     void promote32 (const unsigned targetReg, Value *v);
118     
119     /// copyConstantToRegister - Output the instructions required to put the
120     /// specified constant into the specified register.
121     ///
122     void copyConstantToRegister(Constant *C, unsigned Reg);
123
124     /// makeAnotherReg - This method returns the next register number
125     /// we haven't yet used.
126     unsigned makeAnotherReg (void) {
127       unsigned Reg = CurReg++;
128       return Reg;
129     }
130
131     /// getReg - This method turns an LLVM value into a register number.  This
132     /// is guaranteed to produce the same register number for a particular value
133     /// every time it is queried.
134     ///
135     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
136     unsigned getReg(Value *V) {
137       unsigned &Reg = RegMap[V];
138       if (Reg == 0) {
139         Reg = makeAnotherReg ();
140         RegMap[V] = Reg;
141
142         // Add the mapping of regnumber => reg class to MachineFunction
143         F->addRegMap(Reg,
144                      TM.getRegisterInfo()->getRegClassForType(V->getType()));
145       }
146
147       // If this operand is a constant, emit the code to copy the constant into
148       // the register here...
149       //
150       if (Constant *C = dyn_cast<Constant>(V)) {
151         copyConstantToRegister(C, Reg);
152       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
153         // Move the address of the global into the register
154         BuildMI(BB, X86::MOVir32, 1, Reg).addReg(GV);
155       } else if (Argument *A = dyn_cast<Argument>(V)) {
156         std::cerr << "ERROR: Arguments not implemented in SimpleInstSel\n";
157       }
158
159       return Reg;
160     }
161   };
162 }
163
164 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
165 /// Representation.
166 ///
167 enum TypeClass {
168   cByte, cShort, cInt, cLong, cFloat, cDouble
169 };
170
171 /// getClass - Turn a primitive type into a "class" number which is based on the
172 /// size of the type, and whether or not it is floating point.
173 ///
174 static inline TypeClass getClass(const Type *Ty) {
175   switch (Ty->getPrimitiveID()) {
176   case Type::SByteTyID:
177   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
178   case Type::ShortTyID:
179   case Type::UShortTyID:  return cShort;     // Short operands are class #1
180   case Type::IntTyID:
181   case Type::UIntTyID:
182   case Type::PointerTyID: return cInt;       // Int's and pointers are class #2
183
184   case Type::LongTyID:
185   case Type::ULongTyID:   return cLong;      // Longs are class #3
186   case Type::FloatTyID:   return cFloat;     // Float is class #4
187   case Type::DoubleTyID:  return cDouble;    // Doubles are class #5
188   default:
189     assert(0 && "Invalid type to getClass!");
190     return cByte;  // not reached
191   }
192 }
193
194
195 /// copyConstantToRegister - Output the instructions required to put the
196 /// specified constant into the specified register.
197 ///
198 void ISel::copyConstantToRegister(Constant *C, unsigned R) {
199   if (isa<ConstantExpr> (C)) {
200     // FIXME: We really need to handle getelementptr exprs, among
201     // other things.
202     std::cerr << "Offending expr: " << C << "\n";
203   }
204   assert (!isa<ConstantExpr>(C) && "Constant expressions not yet handled!\n");
205
206   if (C->getType()->isIntegral()) {
207     unsigned Class = getClass(C->getType());
208     assert(Class != 3 && "Type not handled yet!");
209
210     static const unsigned IntegralOpcodeTab[] = {
211       X86::MOVir8, X86::MOVir16, X86::MOVir32
212     };
213
214     if (C->getType()->isSigned()) {
215       ConstantSInt *CSI = cast<ConstantSInt>(C);
216       BuildMI(BB, IntegralOpcodeTab[Class], 1, R).addSImm(CSI->getValue());
217     } else {
218       ConstantUInt *CUI = cast<ConstantUInt>(C);
219       BuildMI(BB, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
220     }
221   } else if (isa <ConstantPointerNull> (C)) {
222     // Copy zero (null pointer) to the register.
223     BuildMI (BB, X86::MOVir32, 1, R).addZImm(0);
224   } else {
225     std::cerr << "Offending constant: " << C << "\n";
226     assert(0 && "Type not handled yet!");
227   }
228 }
229
230
231 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
232 /// register, then move it to wherever the result should be. 
233 /// We handle FP setcc instructions by pushing them, doing a
234 /// compare-and-pop-twice, and then copying the concodes to the main
235 /// processor's concodes (I didn't make this up, it's in the Intel manual)
236 ///
237 void ISel::visitSetCCInst(SetCondInst &I, unsigned OpNum) {
238   // The arguments are already supposed to be of the same type.
239   const Type *CompTy = I.getOperand(0)->getType();
240   unsigned reg1 = getReg(I.getOperand(0));
241   unsigned reg2 = getReg(I.getOperand(1));
242
243   unsigned Class = getClass(CompTy);
244   switch (Class) {
245     // Emit: cmp <var1>, <var2> (do the comparison).  We can
246     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
247     // 32-bit.
248   case cByte:
249     BuildMI (BB, X86::CMPrr8, 2).addReg (reg1).addReg (reg2);
250     break;
251   case cShort:
252     BuildMI (BB, X86::CMPrr16, 2).addReg (reg1).addReg (reg2);
253     break;
254   case cInt:
255     BuildMI (BB, X86::CMPrr32, 2).addReg (reg1).addReg (reg2);
256     break;
257
258     // Push the variables on the stack with fldl opcodes.
259     // FIXME: assuming var1, var2 are in memory, if not, spill to
260     // stack first
261   case cFloat:  // Floats
262     BuildMI (BB, X86::FLDr32, 1).addReg (reg1);
263     BuildMI (BB, X86::FLDr32, 1).addReg (reg2);
264     break;
265   case cDouble:  // Doubles
266     BuildMI (BB, X86::FLDr64, 1).addReg (reg1);
267     BuildMI (BB, X86::FLDr64, 1).addReg (reg2);
268     break;
269   case cLong:
270   default:
271     visitInstruction(I);
272   }
273
274   if (CompTy->isFloatingPoint()) {
275     // (Non-trapping) compare and pop twice.
276     BuildMI (BB, X86::FUCOMPP, 0);
277     // Move fp status word (concodes) to ax.
278     BuildMI (BB, X86::FNSTSWr8, 1, X86::AX);
279     // Load real concodes from ax.
280     BuildMI (BB, X86::SAHF, 1).addReg(X86::AH);
281   }
282
283   // Emit setOp instruction (extract concode; clobbers ax),
284   // using the following mapping:
285   // LLVM  -> X86 signed  X86 unsigned
286   // -----    -----       -----
287   // seteq -> sete        sete
288   // setne -> setne       setne
289   // setlt -> setl        setb
290   // setgt -> setg        seta
291   // setle -> setle       setbe
292   // setge -> setge       setae
293
294   static const unsigned OpcodeTab[2][6] = {
295     {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAr, X86::SETBEr, X86::SETAEr},
296     {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGr, X86::SETLEr, X86::SETGEr},
297   };
298
299   BuildMI(BB, OpcodeTab[CompTy->isSigned()][OpNum], 0, X86::AL);
300   
301   // Put it in the result using a move.
302   BuildMI (BB, X86::MOVrr8, 1, getReg(I)).addReg(X86::AL);
303 }
304
305 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
306 /// operand, in the specified target register.
307 void
308 ISel::promote32 (const unsigned targetReg, Value *v)
309 {
310   unsigned vReg = getReg (v);
311   unsigned Class = getClass (v->getType ());
312   bool isUnsigned = v->getType ()->isUnsigned ();
313   assert (((Class == cByte) || (Class == cShort) || (Class == cInt))
314           && "Unpromotable operand class in promote32");
315   switch (Class)
316     {
317     case cByte:
318       // Extend value into target register (8->32)
319       if (isUnsigned)
320         BuildMI (BB, X86::MOVZXr32r8, 1, targetReg).addReg (vReg);
321       else
322         BuildMI (BB, X86::MOVSXr32r8, 1, targetReg).addReg (vReg);
323       break;
324     case cShort:
325       // Extend value into target register (16->32)
326       if (isUnsigned)
327         BuildMI (BB, X86::MOVZXr32r16, 1, targetReg).addReg (vReg);
328       else
329         BuildMI (BB, X86::MOVSXr32r16, 1, targetReg).addReg (vReg);
330       break;
331     case cInt:
332       // Move value into target register (32->32)
333       BuildMI (BB, X86::MOVrr32, 1, targetReg).addReg (vReg);
334       break;
335     }
336 }
337
338 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
339 /// we have the following possibilities:
340 ///
341 ///   ret void: No return value, simply emit a 'ret' instruction
342 ///   ret sbyte, ubyte : Extend value into EAX and return
343 ///   ret short, ushort: Extend value into EAX and return
344 ///   ret int, uint    : Move value into EAX and return
345 ///   ret pointer      : Move value into EAX and return
346 ///   ret long, ulong  : Move value into EAX/EDX and return
347 ///   ret float/double : Top of FP stack
348 ///
349 void
350 ISel::visitReturnInst (ReturnInst &I)
351 {
352   if (I.getNumOperands () == 0)
353     {
354       // Emit a 'ret' instruction
355       BuildMI (BB, X86::RET, 0);
356       return;
357     }
358   Value *rv = I.getOperand (0);
359   unsigned Class = getClass (rv->getType ());
360   switch (Class)
361     {
362       // integral return values: extend or move into EAX and return. 
363     case cByte:
364     case cShort:
365     case cInt:
366       promote32 (X86::EAX, rv);
367       break;
368       // ret float/double: top of FP stack
369       // FLD <val>
370     case cFloat:                // Floats
371       BuildMI (BB, X86::FLDr32, 1).addReg (getReg (rv));
372       break;
373     case cDouble:               // Doubles
374       BuildMI (BB, X86::FLDr64, 1).addReg (getReg (rv));
375       break;
376     case cLong:
377       // ret long: use EAX(least significant 32 bits)/EDX (most
378       // significant 32)...uh, I think so Brain, but how do i call
379       // up the two parts of the value from inside this mouse
380       // cage? *zort*
381     default:
382       visitInstruction (I);
383     }
384   // Emit a 'ret' instruction
385   BuildMI (BB, X86::RET, 0);
386 }
387
388 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
389 /// that since code layout is frozen at this point, that if we are trying to
390 /// jump to a block that is the immediate successor of the current block, we can
391 /// just make a fall-through. (but we don't currently).
392 ///
393 void
394 ISel::visitBranchInst (BranchInst & BI)
395 {
396   if (BI.isConditional ())
397     {
398       BasicBlock *ifTrue = BI.getSuccessor (0);
399       BasicBlock *ifFalse = BI.getSuccessor (1); // this is really unobvious 
400
401       // simplest thing I can think of: compare condition with zero,
402       // followed by jump-if-equal to ifFalse, and jump-if-nonequal to
403       // ifTrue
404       unsigned int condReg = getReg (BI.getCondition ());
405       BuildMI (BB, X86::CMPri8, 2).addReg (condReg).addZImm (0);
406       BuildMI (BB, X86::JNE, 1).addPCDisp (BI.getSuccessor (0));
407       BuildMI (BB, X86::JE, 1).addPCDisp (BI.getSuccessor (1));
408     }
409   else // unconditional branch
410     {
411       BuildMI (BB, X86::JMP, 1).addPCDisp (BI.getSuccessor (0));
412     }
413 }
414
415 /// visitCallInst - Push args on stack and do a procedure call instruction.
416 void
417 ISel::visitCallInst (CallInst & CI)
418 {
419   // keep a counter of how many bytes we pushed on the stack
420   unsigned bytesPushed = 0;
421
422   // Push the arguments on the stack in reverse order, as specified by
423   // the ABI.
424   for (unsigned i = CI.getNumOperands()-1; i >= 1; --i)
425     {
426       Value *v = CI.getOperand (i);
427       switch (getClass (v->getType ()))
428         {
429         case cByte:
430         case cShort:
431           // Promote V to 32 bits wide, and move the result into EAX,
432           // then push EAX.
433           promote32 (X86::EAX, v);
434           BuildMI (BB, X86::PUSHr32, 1).addReg (X86::EAX);
435           bytesPushed += 4;
436           break;
437         case cInt:
438         case cFloat: {
439           unsigned Reg = getReg(v);
440           BuildMI (BB, X86::PUSHr32, 1).addReg(Reg);
441           bytesPushed += 4;
442           break;
443         }
444         default:
445           // FIXME: long/ulong/double args not handled.
446           visitInstruction (CI);
447           break;
448         }
449     }
450   // Emit a CALL instruction with PC-relative displacement.
451   BuildMI (BB, X86::CALLpcrel32, 1).addPCDisp (CI.getCalledValue ());
452
453   // Adjust the stack by `bytesPushed' amount if non-zero
454   if (bytesPushed > 0)
455     BuildMI (BB, X86::ADDri32, 2).addReg(X86::ESP).addZImm(bytesPushed);
456
457   // If there is a return value, scavenge the result from the location the call
458   // leaves it in...
459   //
460   if (CI.getType() != Type::VoidTy) {
461     unsigned resultTypeClass = getClass (CI.getType ());
462     switch (resultTypeClass) {
463     case cByte:
464     case cShort:
465     case cInt: {
466       // Integral results are in %eax, or the appropriate portion
467       // thereof.
468       static const unsigned regRegMove[] = {
469         X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
470       };
471       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
472       BuildMI (BB, regRegMove[resultTypeClass], 1,
473                getReg (CI)).addReg (AReg[resultTypeClass]);
474       break;
475     }
476     case cFloat:
477       // Floating-point return values live in %st(0) (i.e., the top of
478       // the FP stack.) The general way to approach this is to do a
479       // FSTP to save the top of the FP stack on the real stack, then
480       // do a MOV to load the top of the real stack into the target
481       // register.
482       visitInstruction (CI); // FIXME: add the right args for the calls below
483       // BuildMI (BB, X86::FSTPm32, 0);
484       // BuildMI (BB, X86::MOVmr32, 0);
485       break;
486     default:
487       std::cerr << "Cannot get return value for call of type '"
488                 << *CI.getType() << "'\n";
489       visitInstruction(CI);
490     }
491   }
492 }
493
494 /// visitSimpleBinary - Implement simple binary operators for integral types...
495 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
496 /// 4 for Xor.
497 ///
498 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
499   if (B.getType() == Type::BoolTy)  // FIXME: Handle bools for logicals
500     visitInstruction(B);
501
502   unsigned Class = getClass(B.getType());
503   if (Class > 2)  // FIXME: Handle longs
504     visitInstruction(B);
505
506   static const unsigned OpcodeTab[][4] = {
507     // Arithmetic operators
508     { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, 0 },  // ADD
509     { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, 0 },  // SUB
510
511     // Bitwise operators
512     { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 },  // AND
513     { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 },  // OR
514     { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 },  // XOR
515   };
516   
517   unsigned Opcode = OpcodeTab[OperatorClass][Class];
518   unsigned Op0r = getReg(B.getOperand(0));
519   unsigned Op1r = getReg(B.getOperand(1));
520   BuildMI(BB, Opcode, 2, getReg(B)).addReg(Op0r).addReg(Op1r);
521 }
522
523 /// doMultiply - Emit appropriate instructions to multiply together
524 /// the registers op0Reg and op1Reg, and put the result in destReg.
525 /// The type of the result should be given as resultType.
526 void
527 ISel::doMultiply(unsigned destReg, const Type *resultType,
528                  unsigned op0Reg, unsigned op1Reg)
529 {
530   unsigned Class = getClass (resultType);
531
532   // FIXME:
533   assert (Class <= 2 && "Someday, we will learn how to multiply"
534           "longs and floating-point numbers. This is not that day.");
535  
536   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
537   static const unsigned MulOpcode[]={ X86::MULrr8, X86::MULrr16, X86::MULrr32 };
538   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
539   unsigned Reg     = Regs[Class];
540
541   // Emit a MOV to put the first operand into the appropriately-sized
542   // subreg of EAX.
543   BuildMI (BB, MovOpcode[Class], 1, Reg).addReg (op0Reg);
544   
545   // Emit the appropriate multiply instruction.
546   BuildMI (BB, MulOpcode[Class], 1).addReg (op1Reg);
547
548   // Emit another MOV to put the result into the destination register.
549   BuildMI (BB, MovOpcode[Class], 1, destReg).addReg (Reg);
550 }
551
552 /// visitMul - Multiplies are not simple binary operators because they must deal
553 /// with the EAX register explicitly.
554 ///
555 void ISel::visitMul(BinaryOperator &I) {
556   doMultiply (getReg (I), I.getType (),
557               getReg (I.getOperand (0)), getReg (I.getOperand (1)));
558 }
559
560
561 /// visitDivRem - Handle division and remainder instructions... these
562 /// instruction both require the same instructions to be generated, they just
563 /// select the result from a different register.  Note that both of these
564 /// instructions work differently for signed and unsigned operands.
565 ///
566 void ISel::visitDivRem(BinaryOperator &I) {
567   unsigned Class = getClass(I.getType());
568   if (Class > 2)  // FIXME: Handle longs
569     visitInstruction(I);
570
571   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
572   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
573   static const unsigned ExtOpcode[]={ X86::CBW   , X86::CWD    , X86::CDQ     };
574   static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
575   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
576
577   static const unsigned DivOpcode[][4] = {
578     { X86::DIVrr8 , X86::DIVrr16 , X86::DIVrr32 , 0 },  // Unsigned division
579     { X86::IDIVrr8, X86::IDIVrr16, X86::IDIVrr32, 0 },  // Signed division
580   };
581
582   bool isSigned   = I.getType()->isSigned();
583   unsigned Reg    = Regs[Class];
584   unsigned ExtReg = ExtRegs[Class];
585   unsigned Op0Reg = getReg(I.getOperand(0));
586   unsigned Op1Reg = getReg(I.getOperand(1));
587
588   // Put the first operand into one of the A registers...
589   BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
590
591   if (isSigned) {
592     // Emit a sign extension instruction...
593     BuildMI(BB, ExtOpcode[Class], 0);
594   } else {
595     // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
596     BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
597   }
598
599   // Emit the appropriate divide or remainder instruction...
600   BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
601
602   // Figure out which register we want to pick the result out of...
603   unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
604   
605   // Put the result into the destination register...
606   BuildMI(BB, MovOpcode[Class], 1, getReg(I)).addReg(DestReg);
607 }
608
609
610 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
611 /// for constant immediate shift values, and for constant immediate
612 /// shift values equal to 1. Even the general case is sort of special,
613 /// because the shift amount has to be in CL, not just any old register.
614 ///
615 void ISel::visitShiftInst (ShiftInst &I) {
616   unsigned Op0r = getReg (I.getOperand(0));
617   unsigned DestReg = getReg(I);
618   bool isLeftShift = I.getOpcode() == Instruction::Shl;
619   bool isOperandSigned = I.getType()->isUnsigned();
620   unsigned OperandClass = getClass(I.getType());
621
622   if (OperandClass > 2)
623     visitInstruction(I); // Can't handle longs yet!
624
625   if (ConstantUInt *CUI = dyn_cast <ConstantUInt> (I.getOperand (1)))
626     {
627       // The shift amount is constant, guaranteed to be a ubyte. Get its value.
628       assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
629       unsigned char shAmt = CUI->getValue();
630
631       static const unsigned ConstantOperand[][4] = {
632         { X86::SHRir8, X86::SHRir16, X86::SHRir32, 0 },  // SHR
633         { X86::SARir8, X86::SARir16, X86::SARir32, 0 },  // SAR
634         { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 },  // SHL
635         { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 },  // SAL = SHL
636       };
637
638       const unsigned *OpTab = // Figure out the operand table to use
639         ConstantOperand[isLeftShift*2+isOperandSigned];
640
641       // Emit: <insn> reg, shamt  (shift-by-immediate opcode "ir" form.)
642       BuildMI(BB, OpTab[OperandClass], 2, DestReg).addReg(Op0r).addZImm(shAmt);
643     }
644   else
645     {
646       // The shift amount is non-constant.
647       //
648       // In fact, you can only shift with a variable shift amount if
649       // that amount is already in the CL register, so we have to put it
650       // there first.
651       //
652
653       // Emit: move cl, shiftAmount (put the shift amount in CL.)
654       BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
655
656       // This is a shift right (SHR).
657       static const unsigned NonConstantOperand[][4] = {
658         { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32, 0 },  // SHR
659         { X86::SARrr8, X86::SARrr16, X86::SARrr32, 0 },  // SAR
660         { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 },  // SHL
661         { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 },  // SAL = SHL
662       };
663
664       const unsigned *OpTab = // Figure out the operand table to use
665         NonConstantOperand[isLeftShift*2+isOperandSigned];
666
667       BuildMI(BB, OpTab[OperandClass], 1, DestReg).addReg(Op0r);
668     }
669 }
670
671
672 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
673 /// instruction.
674 ///
675 void ISel::visitLoadInst(LoadInst &I) {
676   unsigned Class = getClass(I.getType());
677   if (Class > 2)  // FIXME: Handle longs and others...
678     visitInstruction(I);
679
680   static const unsigned Opcode[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
681
682   unsigned AddressReg = getReg(I.getOperand(0));
683   addDirectMem(BuildMI(BB, Opcode[Class], 4, getReg(I)), AddressReg);
684 }
685
686
687 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
688 /// instruction.
689 ///
690 void ISel::visitStoreInst(StoreInst &I) {
691   unsigned Class = getClass(I.getOperand(0)->getType());
692   if (Class > 2)  // FIXME: Handle longs and others...
693     visitInstruction(I);
694
695   static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
696
697   unsigned ValReg = getReg(I.getOperand(0));
698   unsigned AddressReg = getReg(I.getOperand(1));
699   addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
700 }
701
702
703 /// visitPHINode - Turn an LLVM PHI node into an X86 PHI node...
704 ///
705 void ISel::visitPHINode(PHINode &PN) {
706   MachineInstr *MI = BuildMI(BB, X86::PHI, PN.getNumOperands(), getReg(PN));
707
708   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
709     // FIXME: This will put constants after the PHI nodes in the block, which
710     // is invalid.  They should be put inline into the PHI node eventually.
711     //
712     MI->addRegOperand(getReg(PN.getIncomingValue(i)));
713     MI->addPCDispOperand(PN.getIncomingBlock(i));
714   }
715 }
716
717 /// visitCastInst - Here we have various kinds of copying with or without
718 /// sign extension going on.
719 void
720 ISel::visitCastInst (CastInst &CI)
721 {
722   const Type *targetType = CI.getType ();
723   Value *operand = CI.getOperand (0);
724   unsigned int operandReg = getReg (operand);
725   const Type *sourceType = operand->getType ();
726   unsigned int destReg = getReg (CI);
727   //
728   // Currently we handle:
729   //
730   // 1) cast * to bool
731   //
732   // 2) cast {sbyte, ubyte} to {sbyte, ubyte}
733   //    cast {short, ushort} to {ushort, short}
734   //    cast {int, uint, ptr} to {int, uint, ptr}
735   //
736   // 3) cast {sbyte, ubyte} to {ushort, short}
737   //    cast {sbyte, ubyte} to {int, uint, ptr}
738   //    cast {short, ushort} to {int, uint, ptr}
739   //
740   // 4) cast {int, uint, ptr} to {short, ushort}
741   //    cast {int, uint, ptr} to {sbyte, ubyte}
742   //    cast {short, ushort} to {sbyte, ubyte}
743   //
744   // 1) Implement casts to bool by using compare on the operand followed
745   // by set if not zero on the result.
746   if (targetType == Type::BoolTy)
747     {
748       BuildMI (BB, X86::CMPri8, 2).addReg (operandReg).addZImm (0);
749       BuildMI (BB, X86::SETNEr, 1, destReg);
750       return;
751     }
752   // 2) Implement casts between values of the same type class (as determined
753   // by getClass) by using a register-to-register move.
754   unsigned int srcClass = getClass (sourceType);
755   unsigned int targClass = getClass (targetType);
756   static const unsigned regRegMove[] = {
757     X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
758   };
759   if ((srcClass < 3) && (targClass < 3) && (srcClass == targClass))
760     {
761       BuildMI (BB, regRegMove[srcClass], 1, destReg).addReg (operandReg);
762       return;
763     }
764   // 3) Handle cast of SMALLER int to LARGER int using a move with sign
765   // extension or zero extension, depending on whether the source type
766   // was signed.
767   if ((srcClass < 3) && (targClass < 3) && (srcClass < targClass))
768     {
769       static const unsigned ops[] = {
770         X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16,
771         X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16
772       };
773       unsigned srcSigned = sourceType->isSigned ();
774       BuildMI (BB, ops[3 * srcSigned + srcClass + targClass - 1], 1,
775                destReg).addReg (operandReg);
776       return;
777     }
778   // 4) Handle cast of LARGER int to SMALLER int using a move to EAX
779   // followed by a move out of AX or AL.
780   if ((srcClass < 3) && (targClass < 3) && (srcClass > targClass))
781     {
782       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
783       BuildMI (BB, regRegMove[srcClass], 1,
784                AReg[srcClass]).addReg (operandReg);
785       BuildMI (BB, regRegMove[targClass], 1, destReg).addReg (AReg[srcClass]);
786       return;
787     }
788   // Anything we haven't handled already, we can't (yet) handle at all.
789   //
790   // FP to integral casts can be handled with FISTP to store onto the
791   // stack while converting to integer, followed by a MOV to load from
792   // the stack into the result register. Integral to FP casts can be
793   // handled with MOV to store onto the stack, followed by a FILD to
794   // load from the stack while converting to FP. For the moment, I
795   // can't quite get straight in my head how to borrow myself some
796   // stack space and write on it. Otherwise, this would be trivial.
797   visitInstruction (CI);
798 }
799
800 /// visitGetElementPtrInst - I don't know, most programs don't have
801 /// getelementptr instructions, right? That means we can put off
802 /// implementing this, right? Right. This method emits machine
803 /// instructions to perform type-safe pointer arithmetic. I am
804 /// guessing this could be cleaned up somewhat to use fewer temporary
805 /// registers.
806 void
807 ISel::visitGetElementPtrInst (GetElementPtrInst &I)
808 {
809   Value *basePtr = I.getPointerOperand ();
810   const TargetData &TD = TM.DataLayout;
811   unsigned basePtrReg = getReg (basePtr);
812   unsigned resultReg = getReg (I);
813   const Type *Ty = basePtr->getType();
814   // GEPs have zero or more indices; we must perform a struct access
815   // or array access for each one.
816   for (GetElementPtrInst::op_iterator oi = I.idx_begin (),
817          oe = I.idx_end (); oi != oe; ++oi) {
818     Value *idx = *oi;
819     unsigned nextBasePtrReg = makeAnotherReg ();
820     if (const StructType *StTy = dyn_cast <StructType> (Ty)) {
821       // It's a struct access.  idx is the index into the structure,
822       // which names the field. This index must have ubyte type.
823       const ConstantUInt *CUI = cast <ConstantUInt> (idx);
824       assert (CUI->getType () == Type::UByteTy
825               && "Funny-looking structure index in GEP");
826       // Use the TargetData structure to pick out what the layout of
827       // the structure is in memory.  Since the structure index must
828       // be constant, we can get its value and use it to find the
829       // right byte offset from the StructLayout class's list of
830       // structure member offsets.
831       unsigned idxValue = CUI->getValue ();
832       unsigned memberOffset =
833         TD.getStructLayout (StTy)->MemberOffsets[idxValue];
834       // Emit an ADD to add memberOffset to the basePtr.
835       BuildMI (BB, X86::ADDri32, 2,
836                nextBasePtrReg).addReg (basePtrReg).addZImm (memberOffset);
837       // The next type is the member of the structure selected by the
838       // index.
839       Ty = StTy->getElementTypes ()[idxValue];
840     } else if (const SequentialType *SqTy = cast <SequentialType> (Ty)) {
841       // It's an array or pointer access: [ArraySize x ElementType].
842       // The documentation does not seem to match the code on the type
843       // of array indices. The code seems to use long, and the docs
844       // (and the comments) say uint. If it is long, I don't know what
845       // we are going to do, because the X86 loves 64-bit types.
846       const Type *typeOfSequentialTypeIndex = SqTy->getIndexType ();
847       // idx is the index into the array.  Unlike with structure
848       // indices, we may not know its actual value at code-generation
849       // time.
850       assert (idx->getType () == typeOfSequentialTypeIndex
851               && "Funny-looking array index in GEP");
852       // We want to add basePtrReg to (idxReg * sizeof
853       // ElementType). First, we must find the size of the pointed-to
854       // type.  (Not coincidentally, the next type is the type of the
855       // elements in the array.)
856       Ty = SqTy->getElementType ();
857       unsigned elementSize = TD.getTypeSize (Ty);
858       unsigned elementSizeReg = makeAnotherReg ();
859       copyConstantToRegister (ConstantInt::get (typeOfSequentialTypeIndex,
860                                                 elementSize),
861                               elementSizeReg);
862       unsigned idxReg = getReg (idx);
863       // Emit a MUL to multiply the register holding the index by
864       // elementSize, putting the result in memberOffsetReg.
865       unsigned memberOffsetReg = makeAnotherReg ();
866       doMultiply (memberOffsetReg, typeOfSequentialTypeIndex,
867                   elementSizeReg, idxReg);
868       // Emit an ADD to add memberOffsetReg to the basePtr.
869       BuildMI (BB, X86::ADDrr32, 2,
870                nextBasePtrReg).addReg (basePtrReg).addReg (memberOffsetReg);
871     }
872     // Now that we are here, further indices refer to subtypes of this
873     // one, so we don't need to worry about basePtrReg itself, anymore.
874     basePtrReg = nextBasePtrReg;
875   }
876   // After we have processed all the indices, the result is left in
877   // basePtrReg.  Move it to the register where we were expected to
878   // put the answer.  A 32-bit move should do it, because we are in
879   // ILP32 land.
880   BuildMI (BB, X86::MOVrr32, 1, getReg (I)).addReg (basePtrReg);
881 }
882
883
884 /// visitMallocInst - I know that personally, whenever I want to remember
885 /// something, I have to clear off some space in my brain.
886 void
887 ISel::visitMallocInst (MallocInst &I)
888 {
889   // We assume that by this point, malloc instructions have been
890   // lowered to calls, and dlsym will magically find malloc for us.
891   // So we do not want to see malloc instructions here.
892   visitInstruction (I);
893 }
894
895
896 /// visitFreeInst - same story as MallocInst
897 void
898 ISel::visitFreeInst (FreeInst &I)
899 {
900   // We assume that by this point, free instructions have been
901   // lowered to calls, and dlsym will magically find free for us.
902   // So we do not want to see free instructions here.
903   visitInstruction (I);
904 }
905
906
907 /// visitAllocaInst - I want some stack space. Come on, man, I said I
908 /// want some freakin' stack space.
909 void
910 ISel::visitAllocaInst (AllocaInst &I)
911 {
912   // Find the data size of the alloca inst's getAllocatedType.
913   const Type *allocatedType = I.getAllocatedType ();
914   const TargetData &TD = TM.DataLayout;
915   unsigned allocatedTypeSize = TD.getTypeSize (allocatedType);
916   // Keep stack 32-bit aligned.
917   unsigned int allocatedTypeWords = allocatedTypeSize / 4;
918   if (allocatedTypeSize % 4 != 0) { allocatedTypeWords++; }
919   // Subtract size from stack pointer, thereby allocating some space.
920   BuildMI (BB, X86::SUBri32, 1, X86::ESP).addZImm (allocatedTypeWords * 4);
921   // Put a pointer to the space into the result register, by copying
922   // the stack pointer.
923   BuildMI (BB, X86::MOVrr32, 1, getReg (I)).addReg (X86::ESP);
924 }
925     
926
927 /// createSimpleX86InstructionSelector - This pass converts an LLVM function
928 /// into a machine code representation is a very simple peep-hole fashion.  The
929 /// generated code sucks but the implementation is nice and simple.
930 ///
931 Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
932   return new ISel(TM);
933 }