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