blob: 52472149ad2b4d6fff0daed9f710782c480a02ac [file] [log] [blame]
Chris Lattner72614082002-10-25 22:55:53 +00001//===-- 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"
Chris Lattner055c9652002-10-29 21:05:24 +00008#include "X86InstrInfo.h"
Chris Lattner6fc3c522002-11-17 21:11:55 +00009#include "X86InstrBuilder.h"
Chris Lattner72614082002-10-25 22:55:53 +000010#include "llvm/Function.h"
11#include "llvm/iTerminators.h"
Brian Gaeke1749d632002-11-07 17:59:21 +000012#include "llvm/iOperators.h"
Brian Gaekea1719c92002-10-31 23:03:59 +000013#include "llvm/iOther.h"
Chris Lattner51b49a92002-11-02 19:45:49 +000014#include "llvm/iPHINode.h"
Chris Lattner6fc3c522002-11-17 21:11:55 +000015#include "llvm/iMemory.h"
Chris Lattner72614082002-10-25 22:55:53 +000016#include "llvm/Type.h"
Brian Gaeke20244b72002-12-12 15:33:40 +000017#include "llvm/DerivedTypes.h"
Chris Lattnerc5291f52002-10-27 21:16:59 +000018#include "llvm/Constants.h"
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000019#include "llvm/Pass.h"
Chris Lattner341a9372002-10-29 17:43:55 +000020#include "llvm/CodeGen/MachineFunction.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000021#include "llvm/CodeGen/MachineInstrBuilder.h"
22#include "llvm/Target/TargetMachine.h"
Chris Lattner72614082002-10-25 22:55:53 +000023#include "llvm/Support/InstVisitor.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000024#include "llvm/Target/MRegisterInfo.h"
25#include <map>
Chris Lattner72614082002-10-25 22:55:53 +000026
Chris Lattner06925362002-11-17 21:56:38 +000027using namespace MOTy; // Get Use, Def, UseAndDef
28
Chris Lattner72614082002-10-25 22:55:53 +000029namespace {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000030 struct ISel : public FunctionPass, InstVisitor<ISel> {
31 TargetMachine &TM;
Chris Lattner341a9372002-10-29 17:43:55 +000032 MachineFunction *F; // The function we are compiling into
33 MachineBasicBlock *BB; // The current MBB we are compiling
Chris Lattner72614082002-10-25 22:55:53 +000034
35 unsigned CurReg;
36 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
37
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000038 ISel(TargetMachine &tm)
39 : TM(tm), F(0), BB(0), CurReg(MRegisterInfo::FirstVirtualRegister) {}
Chris Lattner72614082002-10-25 22:55:53 +000040
41 /// runOnFunction - Top level implementation of instruction selection for
42 /// the entire function.
43 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000044 bool runOnFunction(Function &Fn) {
Chris Lattner36b36032002-10-29 23:40:58 +000045 F = &MachineFunction::construct(&Fn, TM);
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000046 visit(Fn);
Chris Lattner72614082002-10-25 22:55:53 +000047 RegMap.clear();
Chris Lattner94e8ee22002-11-21 17:26:58 +000048 CurReg = MRegisterInfo::FirstVirtualRegister;
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000049 F = 0;
Chris Lattner72614082002-10-25 22:55:53 +000050 return false; // We never modify the LLVM itself.
51 }
52
53 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +000054 /// 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.
Chris Lattner72614082002-10-25 22:55:53 +000057 ///
58 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner42c77862002-10-30 00:47:40 +000059 BB = new MachineBasicBlock(&LLVM_BB);
Chris Lattner72614082002-10-25 22:55:53 +000060 // 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 //
Brian Gaekefa8d5712002-11-22 11:07:01 +000067
68 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +000069 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +000070 void visitBranchInst(BranchInst &BI);
Brian Gaekefa8d5712002-11-22 11:07:01 +000071 void visitCallInst(CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +000072
73 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +000074 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +000075 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
76 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Brian Gaeke20244b72002-12-12 15:33:40 +000077 void doMultiply(unsigned destReg, const Type *resultType,
78 unsigned op0Reg, unsigned op1Reg);
Chris Lattnerca9671d2002-11-02 20:28:58 +000079 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +000080
Chris Lattnerf01729e2002-11-02 20:54:46 +000081 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
82 void visitRem(BinaryOperator &B) { visitDivRem(B); }
83 void visitDivRem(BinaryOperator &B);
84
Chris Lattnere2954c82002-11-02 20:04:26 +000085 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +000086 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
87 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
88 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +000089
90 // Binary comparison operators
Chris Lattner05093a52002-11-21 15:52:38 +000091 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); }
Chris Lattner6fc3c522002-11-17 21:11:55 +000098
99 // Memory Instructions
100 void visitLoadInst(LoadInst &I);
101 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000102 void visitGetElementPtrInst(GetElementPtrInst &I);
103 void visitMallocInst(MallocInst &I);
104 void visitAllocaInst(AllocaInst &I);
105
Chris Lattnere2954c82002-11-02 20:04:26 +0000106 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000107 void visitShiftInst(ShiftInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000108 void visitPHINode(PHINode &I);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000109 void visitCastInst(CastInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000110
111 void visitInstruction(Instruction &I) {
112 std::cerr << "Cannot instruction select: " << I;
113 abort();
114 }
115
Brian Gaekec2505982002-11-30 11:57:28 +0000116 void promote32 (const unsigned targetReg, Value *v);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000117
118 /// copyConstantToRegister - Output the instructions required to put the
119 /// specified constant into the specified register.
120 ///
121 void copyConstantToRegister(Constant *C, unsigned Reg);
122
Brian Gaeke20244b72002-12-12 15:33:40 +0000123 /// makeAnotherReg - This method returns the next register number
124 /// we haven't yet used.
125 unsigned makeAnotherReg (void) {
126 unsigned Reg = CurReg++;
127 return Reg;
128 }
129
Chris Lattner72614082002-10-25 22:55:53 +0000130 /// getReg - This method turns an LLVM value into a register number. This
131 /// is guaranteed to produce the same register number for a particular value
132 /// every time it is queried.
133 ///
134 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
135 unsigned getReg(Value *V) {
136 unsigned &Reg = RegMap[V];
Misha Brukmand2cc0172002-11-20 00:58:23 +0000137 if (Reg == 0) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000138 Reg = makeAnotherReg ();
Misha Brukmand2cc0172002-11-20 00:58:23 +0000139 RegMap[V] = Reg;
140
141 // Add the mapping of regnumber => reg class to MachineFunction
142 F->addRegMap(Reg,
143 TM.getRegisterInfo()->getRegClassForType(V->getType()));
144 }
Chris Lattner72614082002-10-25 22:55:53 +0000145
Chris Lattner6f8fd252002-10-27 21:23:43 +0000146 // If this operand is a constant, emit the code to copy the constant into
147 // the register here...
148 //
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000149 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerc5291f52002-10-27 21:16:59 +0000150 copyConstantToRegister(C, Reg);
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000151 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
152 // Move the address of the global into the register
153 BuildMI(BB, X86::MOVir32, 1, Reg).addReg(GV);
Chris Lattnerd6c4cfa2002-12-04 17:15:34 +0000154 } else if (Argument *A = dyn_cast<Argument>(V)) {
155 std::cerr << "ERROR: Arguments not implemented in SimpleInstSel\n";
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000156 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000157
Chris Lattner72614082002-10-25 22:55:53 +0000158 return Reg;
159 }
Chris Lattner72614082002-10-25 22:55:53 +0000160 };
161}
162
Chris Lattner43189d12002-11-17 20:07:45 +0000163/// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
164/// Representation.
165///
166enum TypeClass {
167 cByte, cShort, cInt, cLong, cFloat, cDouble
168};
169
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000170/// getClass - Turn a primitive type into a "class" number which is based on the
171/// size of the type, and whether or not it is floating point.
172///
Chris Lattner43189d12002-11-17 20:07:45 +0000173static inline TypeClass getClass(const Type *Ty) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000174 switch (Ty->getPrimitiveID()) {
175 case Type::SByteTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000176 case Type::UByteTyID: return cByte; // Byte operands are class #0
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000177 case Type::ShortTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000178 case Type::UShortTyID: return cShort; // Short operands are class #1
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000179 case Type::IntTyID:
180 case Type::UIntTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000181 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000182
183 case Type::LongTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000184 case Type::ULongTyID: return cLong; // Longs are class #3
185 case Type::FloatTyID: return cFloat; // Float is class #4
186 case Type::DoubleTyID: return cDouble; // Doubles are class #5
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000187 default:
188 assert(0 && "Invalid type to getClass!");
Chris Lattner43189d12002-11-17 20:07:45 +0000189 return cByte; // not reached
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000190 }
191}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000192
Chris Lattner06925362002-11-17 21:56:38 +0000193
Chris Lattnerc5291f52002-10-27 21:16:59 +0000194/// copyConstantToRegister - Output the instructions required to put the
195/// specified constant into the specified register.
196///
197void ISel::copyConstantToRegister(Constant *C, unsigned R) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000198 if (isa<ConstantExpr> (C)) {
199 // FIXME: We really need to handle getelementptr exprs, among
200 // other things.
201 std::cerr << "Offending expr: " << C << "\n";
202 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000203 assert (!isa<ConstantExpr>(C) && "Constant expressions not yet handled!\n");
204
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000205 if (C->getType()->isIntegral()) {
206 unsigned Class = getClass(C->getType());
207 assert(Class != 3 && "Type not handled yet!");
208
209 static const unsigned IntegralOpcodeTab[] = {
210 X86::MOVir8, X86::MOVir16, X86::MOVir32
211 };
212
213 if (C->getType()->isSigned()) {
214 ConstantSInt *CSI = cast<ConstantSInt>(C);
215 BuildMI(BB, IntegralOpcodeTab[Class], 1, R).addSImm(CSI->getValue());
216 } else {
217 ConstantUInt *CUI = cast<ConstantUInt>(C);
218 BuildMI(BB, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
219 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000220 } else if (isa <ConstantPointerNull> (C)) {
221 // Copy zero (null pointer) to the register.
222 BuildMI (BB, X86::MOVir32, 1, R).addZImm(0);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000223 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000224 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000225 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000226 }
227}
228
Chris Lattner06925362002-11-17 21:56:38 +0000229
Brian Gaeke1749d632002-11-07 17:59:21 +0000230/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
231/// register, then move it to wherever the result should be.
232/// We handle FP setcc instructions by pushing them, doing a
233/// compare-and-pop-twice, and then copying the concodes to the main
234/// processor's concodes (I didn't make this up, it's in the Intel manual)
235///
Chris Lattner05093a52002-11-21 15:52:38 +0000236void ISel::visitSetCCInst(SetCondInst &I, unsigned OpNum) {
Brian Gaeke1749d632002-11-07 17:59:21 +0000237 // The arguments are already supposed to be of the same type.
Chris Lattner05093a52002-11-21 15:52:38 +0000238 const Type *CompTy = I.getOperand(0)->getType();
239 unsigned reg1 = getReg(I.getOperand(0));
240 unsigned reg2 = getReg(I.getOperand(1));
241
242 unsigned Class = getClass(CompTy);
243 switch (Class) {
244 // Emit: cmp <var1>, <var2> (do the comparison). We can
245 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
246 // 32-bit.
247 case cByte:
248 BuildMI (BB, X86::CMPrr8, 2).addReg (reg1).addReg (reg2);
249 break;
250 case cShort:
251 BuildMI (BB, X86::CMPrr16, 2).addReg (reg1).addReg (reg2);
252 break;
253 case cInt:
254 BuildMI (BB, X86::CMPrr32, 2).addReg (reg1).addReg (reg2);
255 break;
256
257 // Push the variables on the stack with fldl opcodes.
258 // FIXME: assuming var1, var2 are in memory, if not, spill to
259 // stack first
260 case cFloat: // Floats
Brian Gaeke20244b72002-12-12 15:33:40 +0000261 BuildMI (BB, X86::FLDr32, 1).addReg (reg1);
262 BuildMI (BB, X86::FLDr32, 1).addReg (reg2);
Chris Lattner05093a52002-11-21 15:52:38 +0000263 break;
264 case cDouble: // Doubles
Brian Gaeke20244b72002-12-12 15:33:40 +0000265 BuildMI (BB, X86::FLDr64, 1).addReg (reg1);
266 BuildMI (BB, X86::FLDr64, 1).addReg (reg2);
Chris Lattner05093a52002-11-21 15:52:38 +0000267 break;
268 case cLong:
269 default:
270 visitInstruction(I);
271 }
272
273 if (CompTy->isFloatingPoint()) {
274 // (Non-trapping) compare and pop twice.
275 BuildMI (BB, X86::FUCOMPP, 0);
276 // Move fp status word (concodes) to ax.
277 BuildMI (BB, X86::FNSTSWr8, 1, X86::AX);
278 // Load real concodes from ax.
279 BuildMI (BB, X86::SAHF, 1).addReg(X86::AH);
280 }
281
Brian Gaeke1749d632002-11-07 17:59:21 +0000282 // Emit setOp instruction (extract concode; clobbers ax),
283 // using the following mapping:
284 // LLVM -> X86 signed X86 unsigned
285 // ----- ----- -----
286 // seteq -> sete sete
287 // setne -> setne setne
288 // setlt -> setl setb
289 // setgt -> setg seta
290 // setle -> setle setbe
291 // setge -> setge setae
Chris Lattner05093a52002-11-21 15:52:38 +0000292
293 static const unsigned OpcodeTab[2][6] = {
Chris Lattner4b4e9dd2002-11-21 16:19:42 +0000294 {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAr, X86::SETBEr, X86::SETAEr},
295 {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGr, X86::SETLEr, X86::SETGEr},
Chris Lattner05093a52002-11-21 15:52:38 +0000296 };
297
298 BuildMI(BB, OpcodeTab[CompTy->isSigned()][OpNum], 0, X86::AL);
299
Brian Gaeke1749d632002-11-07 17:59:21 +0000300 // Put it in the result using a move.
Chris Lattner05093a52002-11-21 15:52:38 +0000301 BuildMI (BB, X86::MOVrr8, 1, getReg(I)).addReg(X86::AL);
Brian Gaeke1749d632002-11-07 17:59:21 +0000302}
Chris Lattner51b49a92002-11-02 19:45:49 +0000303
Brian Gaekec2505982002-11-30 11:57:28 +0000304/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
305/// operand, in the specified target register.
306void
307ISel::promote32 (const unsigned targetReg, Value *v)
308{
309 unsigned vReg = getReg (v);
310 unsigned Class = getClass (v->getType ());
311 bool isUnsigned = v->getType ()->isUnsigned ();
312 assert (((Class == cByte) || (Class == cShort) || (Class == cInt))
313 && "Unpromotable operand class in promote32");
314 switch (Class)
315 {
316 case cByte:
317 // Extend value into target register (8->32)
318 if (isUnsigned)
319 BuildMI (BB, X86::MOVZXr32r8, 1, targetReg).addReg (vReg);
320 else
321 BuildMI (BB, X86::MOVSXr32r8, 1, targetReg).addReg (vReg);
322 break;
323 case cShort:
324 // Extend value into target register (16->32)
325 if (isUnsigned)
326 BuildMI (BB, X86::MOVZXr32r16, 1, targetReg).addReg (vReg);
327 else
328 BuildMI (BB, X86::MOVSXr32r16, 1, targetReg).addReg (vReg);
329 break;
330 case cInt:
331 // Move value into target register (32->32)
332 BuildMI (BB, X86::MOVrr32, 1, targetReg).addReg (vReg);
333 break;
334 }
335}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000336
Chris Lattner72614082002-10-25 22:55:53 +0000337/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
338/// we have the following possibilities:
339///
340/// ret void: No return value, simply emit a 'ret' instruction
341/// ret sbyte, ubyte : Extend value into EAX and return
342/// ret short, ushort: Extend value into EAX and return
343/// ret int, uint : Move value into EAX and return
344/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +0000345/// ret long, ulong : Move value into EAX/EDX and return
346/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +0000347///
Brian Gaekec2505982002-11-30 11:57:28 +0000348void
349ISel::visitReturnInst (ReturnInst &I)
350{
351 if (I.getNumOperands () == 0)
352 {
353 // Emit a 'ret' instruction
354 BuildMI (BB, X86::RET, 0);
355 return;
356 }
357 Value *rv = I.getOperand (0);
358 unsigned Class = getClass (rv->getType ());
359 switch (Class)
360 {
361 // integral return values: extend or move into EAX and return.
362 case cByte:
363 case cShort:
364 case cInt:
365 promote32 (X86::EAX, rv);
366 break;
367 // ret float/double: top of FP stack
368 // FLD <val>
369 case cFloat: // Floats
Brian Gaeke20244b72002-12-12 15:33:40 +0000370 BuildMI (BB, X86::FLDr32, 1).addReg (getReg (rv));
Brian Gaekec2505982002-11-30 11:57:28 +0000371 break;
372 case cDouble: // Doubles
Brian Gaeke20244b72002-12-12 15:33:40 +0000373 BuildMI (BB, X86::FLDr64, 1).addReg (getReg (rv));
Brian Gaekec2505982002-11-30 11:57:28 +0000374 break;
375 case cLong:
376 // ret long: use EAX(least significant 32 bits)/EDX (most
377 // significant 32)...uh, I think so Brain, but how do i call
378 // up the two parts of the value from inside this mouse
379 // cage? *zort*
380 default:
381 visitInstruction (I);
382 }
Chris Lattner43189d12002-11-17 20:07:45 +0000383 // Emit a 'ret' instruction
Brian Gaekec2505982002-11-30 11:57:28 +0000384 BuildMI (BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +0000385}
386
Chris Lattner51b49a92002-11-02 19:45:49 +0000387/// visitBranchInst - Handle conditional and unconditional branches here. Note
388/// that since code layout is frozen at this point, that if we are trying to
389/// jump to a block that is the immediate successor of the current block, we can
390/// just make a fall-through. (but we don't currently).
391///
Brian Gaekec03a0cb2002-11-19 09:08:47 +0000392void
393ISel::visitBranchInst (BranchInst & BI)
394{
395 if (BI.isConditional ())
396 {
397 BasicBlock *ifTrue = BI.getSuccessor (0);
398 BasicBlock *ifFalse = BI.getSuccessor (1); // this is really unobvious
Chris Lattner2df035b2002-11-02 19:27:56 +0000399
Brian Gaekec03a0cb2002-11-19 09:08:47 +0000400 // simplest thing I can think of: compare condition with zero,
401 // followed by jump-if-equal to ifFalse, and jump-if-nonequal to
402 // ifTrue
403 unsigned int condReg = getReg (BI.getCondition ());
Chris Lattner97ad9e12002-11-21 01:59:50 +0000404 BuildMI (BB, X86::CMPri8, 2).addReg (condReg).addZImm (0);
Brian Gaekec03a0cb2002-11-19 09:08:47 +0000405 BuildMI (BB, X86::JNE, 1).addPCDisp (BI.getSuccessor (0));
406 BuildMI (BB, X86::JE, 1).addPCDisp (BI.getSuccessor (1));
407 }
408 else // unconditional branch
409 {
410 BuildMI (BB, X86::JMP, 1).addPCDisp (BI.getSuccessor (0));
411 }
Chris Lattner2df035b2002-11-02 19:27:56 +0000412}
413
Brian Gaeke18a20212002-11-29 12:01:58 +0000414/// visitCallInst - Push args on stack and do a procedure call instruction.
415void
416ISel::visitCallInst (CallInst & CI)
417{
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000418 // keep a counter of how many bytes we pushed on the stack
419 unsigned bytesPushed = 0;
420
Brian Gaeke18a20212002-11-29 12:01:58 +0000421 // Push the arguments on the stack in reverse order, as specified by
422 // the ABI.
Chris Lattnerd852c152002-12-03 20:30:12 +0000423 for (unsigned i = CI.getNumOperands()-1; i >= 1; --i)
Brian Gaeke18a20212002-11-29 12:01:58 +0000424 {
425 Value *v = CI.getOperand (i);
Brian Gaeke18a20212002-11-29 12:01:58 +0000426 switch (getClass (v->getType ()))
427 {
Brian Gaekec2505982002-11-30 11:57:28 +0000428 case cByte:
429 case cShort:
Brian Gaekebb25f2f2002-12-03 00:51:09 +0000430 // Promote V to 32 bits wide, and move the result into EAX,
431 // then push EAX.
Brian Gaekec2505982002-11-30 11:57:28 +0000432 promote32 (X86::EAX, v);
433 BuildMI (BB, X86::PUSHr32, 1).addReg (X86::EAX);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000434 bytesPushed += 4;
Brian Gaekec2505982002-11-30 11:57:28 +0000435 break;
Brian Gaeke18a20212002-11-29 12:01:58 +0000436 case cInt:
Chris Lattner33ced562002-12-04 06:56:56 +0000437 case cFloat: {
438 unsigned Reg = getReg(v);
439 BuildMI (BB, X86::PUSHr32, 1).addReg(Reg);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000440 bytesPushed += 4;
Brian Gaeke18a20212002-11-29 12:01:58 +0000441 break;
Chris Lattner33ced562002-12-04 06:56:56 +0000442 }
Brian Gaeke18a20212002-11-29 12:01:58 +0000443 default:
Brian Gaekebb25f2f2002-12-03 00:51:09 +0000444 // FIXME: long/ulong/double args not handled.
Brian Gaeke18a20212002-11-29 12:01:58 +0000445 visitInstruction (CI);
446 break;
447 }
448 }
449 // Emit a CALL instruction with PC-relative displacement.
450 BuildMI (BB, X86::CALLpcrel32, 1).addPCDisp (CI.getCalledValue ());
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000451
452 // Adjust the stack by `bytesPushed' amount if non-zero
453 if (bytesPushed > 0)
454 BuildMI (BB, X86::ADDri32, 2).addReg(X86::ESP).addZImm(bytesPushed);
Chris Lattnera3243642002-12-04 23:45:28 +0000455
456 // If there is a return value, scavenge the result from the location the call
457 // leaves it in...
458 //
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000459 if (CI.getType() != Type::VoidTy) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000460 unsigned resultTypeClass = getClass (CI.getType ());
461 switch (resultTypeClass) {
462 case cByte:
463 case cShort:
464 case cInt: {
465 // Integral results are in %eax, or the appropriate portion
466 // thereof.
467 static const unsigned regRegMove[] = {
468 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
469 };
470 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
471 BuildMI (BB, regRegMove[resultTypeClass], 1,
472 getReg (CI)).addReg (AReg[resultTypeClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000473 break;
Brian Gaeke20244b72002-12-12 15:33:40 +0000474 }
475 case cFloat:
476 // Floating-point return values live in %st(0) (i.e., the top of
477 // the FP stack.) The general way to approach this is to do a
478 // FSTP to save the top of the FP stack on the real stack, then
479 // do a MOV to load the top of the real stack into the target
480 // register.
481 visitInstruction (CI); // FIXME: add the right args for the calls below
482 // BuildMI (BB, X86::FSTPm32, 0);
483 // BuildMI (BB, X86::MOVmr32, 0);
484 break;
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000485 default:
486 std::cerr << "Cannot get return value for call of type '"
487 << *CI.getType() << "'\n";
488 visitInstruction(CI);
489 }
Chris Lattnera3243642002-12-04 23:45:28 +0000490 }
Brian Gaekefa8d5712002-11-22 11:07:01 +0000491}
Chris Lattner2df035b2002-11-02 19:27:56 +0000492
Chris Lattner68aad932002-11-02 20:13:22 +0000493/// visitSimpleBinary - Implement simple binary operators for integral types...
494/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
495/// 4 for Xor.
496///
497void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
498 if (B.getType() == Type::BoolTy) // FIXME: Handle bools for logicals
Chris Lattnere2954c82002-11-02 20:04:26 +0000499 visitInstruction(B);
500
501 unsigned Class = getClass(B.getType());
502 if (Class > 2) // FIXME: Handle longs
503 visitInstruction(B);
504
505 static const unsigned OpcodeTab[][4] = {
Chris Lattner68aad932002-11-02 20:13:22 +0000506 // Arithmetic operators
507 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, 0 }, // ADD
508 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, 0 }, // SUB
509
510 // Bitwise operators
Chris Lattnere2954c82002-11-02 20:04:26 +0000511 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
512 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
513 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
514 };
515
516 unsigned Opcode = OpcodeTab[OperatorClass][Class];
517 unsigned Op0r = getReg(B.getOperand(0));
518 unsigned Op1r = getReg(B.getOperand(1));
519 BuildMI(BB, Opcode, 2, getReg(B)).addReg(Op0r).addReg(Op1r);
520}
521
Brian Gaeke20244b72002-12-12 15:33:40 +0000522/// doMultiply - Emit appropriate instructions to multiply together
523/// the registers op0Reg and op1Reg, and put the result in destReg.
524/// The type of the result should be given as resultType.
525void
526ISel::doMultiply(unsigned destReg, const Type *resultType,
527 unsigned op0Reg, unsigned op1Reg)
528{
529 unsigned Class = getClass (resultType);
530
531 // FIXME:
532 assert (Class <= 2 && "Someday, we will learn how to multiply"
533 "longs and floating-point numbers. This is not that day.");
534
535 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
536 static const unsigned MulOpcode[]={ X86::MULrr8, X86::MULrr16, X86::MULrr32 };
537 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
538 unsigned Reg = Regs[Class];
539
540 // Emit a MOV to put the first operand into the appropriately-sized
541 // subreg of EAX.
542 BuildMI (BB, MovOpcode[Class], 1, Reg).addReg (op0Reg);
543
544 // Emit the appropriate multiply instruction.
545 BuildMI (BB, MulOpcode[Class], 1).addReg (op1Reg);
546
547 // Emit another MOV to put the result into the destination register.
548 BuildMI (BB, MovOpcode[Class], 1, destReg).addReg (Reg);
549}
550
Chris Lattnerca9671d2002-11-02 20:28:58 +0000551/// visitMul - Multiplies are not simple binary operators because they must deal
552/// with the EAX register explicitly.
553///
554void ISel::visitMul(BinaryOperator &I) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000555 doMultiply (getReg (I), I.getType (),
556 getReg (I.getOperand (0)), getReg (I.getOperand (1)));
Chris Lattnerf01729e2002-11-02 20:54:46 +0000557}
Chris Lattnerca9671d2002-11-02 20:28:58 +0000558
Chris Lattner06925362002-11-17 21:56:38 +0000559
Chris Lattnerf01729e2002-11-02 20:54:46 +0000560/// visitDivRem - Handle division and remainder instructions... these
561/// instruction both require the same instructions to be generated, they just
562/// select the result from a different register. Note that both of these
563/// instructions work differently for signed and unsigned operands.
564///
565void ISel::visitDivRem(BinaryOperator &I) {
566 unsigned Class = getClass(I.getType());
567 if (Class > 2) // FIXME: Handle longs
568 visitInstruction(I);
569
570 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
571 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
Brian Gaeke6559bb92002-11-14 22:32:30 +0000572 static const unsigned ExtOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
Chris Lattnerf01729e2002-11-02 20:54:46 +0000573 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
574 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
575
576 static const unsigned DivOpcode[][4] = {
577 { X86::DIVrr8 , X86::DIVrr16 , X86::DIVrr32 , 0 }, // Unsigned division
578 { X86::IDIVrr8, X86::IDIVrr16, X86::IDIVrr32, 0 }, // Signed division
579 };
580
581 bool isSigned = I.getType()->isSigned();
582 unsigned Reg = Regs[Class];
583 unsigned ExtReg = ExtRegs[Class];
Chris Lattner6fc3c522002-11-17 21:11:55 +0000584 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattnerf01729e2002-11-02 20:54:46 +0000585 unsigned Op1Reg = getReg(I.getOperand(1));
586
587 // Put the first operand into one of the A registers...
588 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
589
590 if (isSigned) {
591 // Emit a sign extension instruction...
Chris Lattnera4978cc2002-12-01 23:24:58 +0000592 BuildMI(BB, ExtOpcode[Class], 0);
Chris Lattnerf01729e2002-11-02 20:54:46 +0000593 } else {
594 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
595 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
596 }
597
Chris Lattner06925362002-11-17 21:56:38 +0000598 // Emit the appropriate divide or remainder instruction...
Chris Lattner92845e32002-11-21 18:54:29 +0000599 BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
Chris Lattner06925362002-11-17 21:56:38 +0000600
Chris Lattnerf01729e2002-11-02 20:54:46 +0000601 // Figure out which register we want to pick the result out of...
602 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
603
Chris Lattnerf01729e2002-11-02 20:54:46 +0000604 // Put the result into the destination register...
605 BuildMI(BB, MovOpcode[Class], 1, getReg(I)).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +0000606}
Chris Lattnere2954c82002-11-02 20:04:26 +0000607
Chris Lattner06925362002-11-17 21:56:38 +0000608
Brian Gaekea1719c92002-10-31 23:03:59 +0000609/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
610/// for constant immediate shift values, and for constant immediate
611/// shift values equal to 1. Even the general case is sort of special,
612/// because the shift amount has to be in CL, not just any old register.
613///
Chris Lattnerf01729e2002-11-02 20:54:46 +0000614void ISel::visitShiftInst (ShiftInst &I) {
615 unsigned Op0r = getReg (I.getOperand(0));
616 unsigned DestReg = getReg(I);
Chris Lattnere9913f22002-11-02 01:41:55 +0000617 bool isLeftShift = I.getOpcode() == Instruction::Shl;
618 bool isOperandSigned = I.getType()->isUnsigned();
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000619 unsigned OperandClass = getClass(I.getType());
620
621 if (OperandClass > 2)
622 visitInstruction(I); // Can't handle longs yet!
Chris Lattner796df732002-11-02 00:44:25 +0000623
Brian Gaekea1719c92002-10-31 23:03:59 +0000624 if (ConstantUInt *CUI = dyn_cast <ConstantUInt> (I.getOperand (1)))
625 {
Chris Lattner796df732002-11-02 00:44:25 +0000626 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
627 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
628 unsigned char shAmt = CUI->getValue();
629
Chris Lattnere9913f22002-11-02 01:41:55 +0000630 static const unsigned ConstantOperand[][4] = {
631 { X86::SHRir8, X86::SHRir16, X86::SHRir32, 0 }, // SHR
632 { X86::SARir8, X86::SARir16, X86::SARir32, 0 }, // SAR
633 { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 }, // SHL
634 { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 }, // SAL = SHL
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000635 };
636
Chris Lattnere9913f22002-11-02 01:41:55 +0000637 const unsigned *OpTab = // Figure out the operand table to use
638 ConstantOperand[isLeftShift*2+isOperandSigned];
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000639
Brian Gaekea1719c92002-10-31 23:03:59 +0000640 // Emit: <insn> reg, shamt (shift-by-immediate opcode "ir" form.)
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000641 BuildMI(BB, OpTab[OperandClass], 2, DestReg).addReg(Op0r).addZImm(shAmt);
Brian Gaekea1719c92002-10-31 23:03:59 +0000642 }
643 else
644 {
645 // The shift amount is non-constant.
646 //
647 // In fact, you can only shift with a variable shift amount if
648 // that amount is already in the CL register, so we have to put it
649 // there first.
650 //
Chris Lattnere9913f22002-11-02 01:41:55 +0000651
Brian Gaekea1719c92002-10-31 23:03:59 +0000652 // Emit: move cl, shiftAmount (put the shift amount in CL.)
Chris Lattnerca9671d2002-11-02 20:28:58 +0000653 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000654
655 // This is a shift right (SHR).
Chris Lattnere9913f22002-11-02 01:41:55 +0000656 static const unsigned NonConstantOperand[][4] = {
657 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32, 0 }, // SHR
658 { X86::SARrr8, X86::SARrr16, X86::SARrr32, 0 }, // SAR
659 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 }, // SHL
660 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 }, // SAL = SHL
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000661 };
662
Chris Lattnere9913f22002-11-02 01:41:55 +0000663 const unsigned *OpTab = // Figure out the operand table to use
664 NonConstantOperand[isLeftShift*2+isOperandSigned];
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000665
Chris Lattner3a9a6932002-11-21 22:49:20 +0000666 BuildMI(BB, OpTab[OperandClass], 1, DestReg).addReg(Op0r);
Brian Gaekea1719c92002-10-31 23:03:59 +0000667 }
668}
669
Chris Lattner06925362002-11-17 21:56:38 +0000670
Chris Lattner6fc3c522002-11-17 21:11:55 +0000671/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
672/// instruction.
673///
674void ISel::visitLoadInst(LoadInst &I) {
675 unsigned Class = getClass(I.getType());
676 if (Class > 2) // FIXME: Handle longs and others...
677 visitInstruction(I);
678
679 static const unsigned Opcode[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
680
681 unsigned AddressReg = getReg(I.getOperand(0));
682 addDirectMem(BuildMI(BB, Opcode[Class], 4, getReg(I)), AddressReg);
683}
684
Chris Lattner06925362002-11-17 21:56:38 +0000685
Chris Lattner6fc3c522002-11-17 21:11:55 +0000686/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
687/// instruction.
688///
689void ISel::visitStoreInst(StoreInst &I) {
690 unsigned Class = getClass(I.getOperand(0)->getType());
691 if (Class > 2) // FIXME: Handle longs and others...
692 visitInstruction(I);
693
694 static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
695
696 unsigned ValReg = getReg(I.getOperand(0));
697 unsigned AddressReg = getReg(I.getOperand(1));
698 addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
699}
700
701
Chris Lattnere2954c82002-11-02 20:04:26 +0000702/// visitPHINode - Turn an LLVM PHI node into an X86 PHI node...
703///
704void ISel::visitPHINode(PHINode &PN) {
705 MachineInstr *MI = BuildMI(BB, X86::PHI, PN.getNumOperands(), getReg(PN));
Chris Lattner72614082002-10-25 22:55:53 +0000706
Chris Lattnere2954c82002-11-02 20:04:26 +0000707 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
708 // FIXME: This will put constants after the PHI nodes in the block, which
709 // is invalid. They should be put inline into the PHI node eventually.
710 //
711 MI->addRegOperand(getReg(PN.getIncomingValue(i)));
712 MI->addPCDispOperand(PN.getIncomingBlock(i));
713 }
Chris Lattner72614082002-10-25 22:55:53 +0000714}
715
Brian Gaekec11232a2002-11-26 10:43:30 +0000716/// visitCastInst - Here we have various kinds of copying with or without
717/// sign extension going on.
Brian Gaekefa8d5712002-11-22 11:07:01 +0000718void
719ISel::visitCastInst (CastInst &CI)
720{
Chris Lattnerf18a36e2002-12-03 18:15:59 +0000721 const Type *targetType = CI.getType ();
Brian Gaeke07f02612002-12-03 07:36:03 +0000722 Value *operand = CI.getOperand (0);
723 unsigned int operandReg = getReg (operand);
Chris Lattnerf18a36e2002-12-03 18:15:59 +0000724 const Type *sourceType = operand->getType ();
Brian Gaeke07f02612002-12-03 07:36:03 +0000725 unsigned int destReg = getReg (CI);
Brian Gaeked474e9c2002-12-06 10:49:33 +0000726 //
727 // Currently we handle:
728 //
729 // 1) cast * to bool
730 //
731 // 2) cast {sbyte, ubyte} to {sbyte, ubyte}
732 // cast {short, ushort} to {ushort, short}
733 // cast {int, uint, ptr} to {int, uint, ptr}
734 //
735 // 3) cast {sbyte, ubyte} to {ushort, short}
736 // cast {sbyte, ubyte} to {int, uint, ptr}
737 // cast {short, ushort} to {int, uint, ptr}
738 //
739 // 4) cast {int, uint, ptr} to {short, ushort}
740 // cast {int, uint, ptr} to {sbyte, ubyte}
741 // cast {short, ushort} to {sbyte, ubyte}
742 //
743 // 1) Implement casts to bool by using compare on the operand followed
744 // by set if not zero on the result.
745 if (targetType == Type::BoolTy)
746 {
747 BuildMI (BB, X86::CMPri8, 2).addReg (operandReg).addZImm (0);
748 BuildMI (BB, X86::SETNEr, 1, destReg);
749 return;
750 }
751 // 2) Implement casts between values of the same type class (as determined
752 // by getClass) by using a register-to-register move.
753 unsigned int srcClass = getClass (sourceType);
754 unsigned int targClass = getClass (targetType);
755 static const unsigned regRegMove[] = {
756 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
757 };
758 if ((srcClass < 3) && (targClass < 3) && (srcClass == targClass))
759 {
760 BuildMI (BB, regRegMove[srcClass], 1, destReg).addReg (operandReg);
761 return;
762 }
763 // 3) Handle cast of SMALLER int to LARGER int using a move with sign
764 // extension or zero extension, depending on whether the source type
765 // was signed.
766 if ((srcClass < 3) && (targClass < 3) && (srcClass < targClass))
767 {
768 static const unsigned ops[] = {
769 X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16,
770 X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16
771 };
772 unsigned srcSigned = sourceType->isSigned ();
773 BuildMI (BB, ops[3 * srcSigned + srcClass + targClass - 1], 1,
774 destReg).addReg (operandReg);
775 return;
776 }
777 // 4) Handle cast of LARGER int to SMALLER int using a move to EAX
778 // followed by a move out of AX or AL.
779 if ((srcClass < 3) && (targClass < 3) && (srcClass > targClass))
780 {
781 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
782 BuildMI (BB, regRegMove[srcClass], 1,
783 AReg[srcClass]).addReg (operandReg);
784 BuildMI (BB, regRegMove[targClass], 1, destReg).addReg (AReg[srcClass]);
785 return;
786 }
787 // Anything we haven't handled already, we can't (yet) handle at all.
Brian Gaeke20244b72002-12-12 15:33:40 +0000788 //
789 // FP to integral casts can be handled with FISTP to store onto the
790 // stack while converting to integer, followed by a MOV to load from
791 // the stack into the result register. Integral to FP casts can be
792 // handled with MOV to store onto the stack, followed by a FILD to
793 // load from the stack while converting to FP. For the moment, I
794 // can't quite get straight in my head how to borrow myself some
795 // stack space and write on it. Otherwise, this would be trivial.
Brian Gaekefa8d5712002-11-22 11:07:01 +0000796 visitInstruction (CI);
797}
Brian Gaekea1719c92002-10-31 23:03:59 +0000798
Brian Gaeke20244b72002-12-12 15:33:40 +0000799/// visitGetElementPtrInst - I don't know, most programs don't have
800/// getelementptr instructions, right? That means we can put off
801/// implementing this, right? Right. This method emits machine
802/// instructions to perform type-safe pointer arithmetic. I am
803/// guessing this could be cleaned up somewhat to use fewer temporary
804/// registers.
805void
806ISel::visitGetElementPtrInst (GetElementPtrInst &I)
807{
808 Value *basePtr = I.getPointerOperand ();
809 const TargetData &TD = TM.DataLayout;
810 unsigned basePtrReg = getReg (basePtr);
811 unsigned resultReg = getReg (I);
812 const Type *Ty = basePtr->getType();
813 // GEPs have zero or more indices; we must perform a struct access
814 // or array access for each one.
815 for (GetElementPtrInst::op_iterator oi = I.idx_begin (),
816 oe = I.idx_end (); oi != oe; ++oi) {
817 Value *idx = *oi;
818 unsigned nextBasePtrReg = makeAnotherReg ();
819 if (const StructType *StTy = dyn_cast <StructType> (Ty)) {
820 // It's a struct access. idx is the index into the structure,
821 // which names the field. This index must have ubyte type.
822 const ConstantUInt *CUI = cast <ConstantUInt> (idx);
823 assert (CUI->getType () == Type::UByteTy
824 && "Funny-looking structure index in GEP");
825 // Use the TargetData structure to pick out what the layout of
826 // the structure is in memory. Since the structure index must
827 // be constant, we can get its value and use it to find the
828 // right byte offset from the StructLayout class's list of
829 // structure member offsets.
830 unsigned idxValue = CUI->getValue ();
831 unsigned memberOffset =
832 TD.getStructLayout (StTy)->MemberOffsets[idxValue];
833 // Emit an ADD to add memberOffset to the basePtr.
834 BuildMI (BB, X86::ADDri32, 2,
835 nextBasePtrReg).addReg (basePtrReg).addZImm (memberOffset);
836 // The next type is the member of the structure selected by the
837 // index.
838 Ty = StTy->getElementTypes ()[idxValue];
839 } else if (const SequentialType *SqTy = cast <SequentialType> (Ty)) {
840 // It's an array or pointer access: [ArraySize x ElementType].
841 // The documentation does not seem to match the code on the type
842 // of array indices. The code seems to use long, and the docs
843 // (and the comments) say uint. If it is long, I don't know what
844 // we are going to do, because the X86 loves 64-bit types.
845 const Type *typeOfSequentialTypeIndex = SqTy->getIndexType ();
846 // idx is the index into the array. Unlike with structure
847 // indices, we may not know its actual value at code-generation
848 // time.
849 assert (idx->getType () == typeOfSequentialTypeIndex
850 && "Funny-looking array index in GEP");
851 // We want to add basePtrReg to (idxReg * sizeof
852 // ElementType). First, we must find the size of the pointed-to
853 // type. (Not coincidentally, the next type is the type of the
854 // elements in the array.)
855 Ty = SqTy->getElementType ();
856 unsigned elementSize = TD.getTypeSize (Ty);
857 unsigned elementSizeReg = makeAnotherReg ();
858 copyConstantToRegister (ConstantInt::get (typeOfSequentialTypeIndex,
859 elementSize),
860 elementSizeReg);
861 unsigned idxReg = getReg (idx);
862 // Emit a MUL to multiply the register holding the index by
863 // elementSize, putting the result in memberOffsetReg.
864 unsigned memberOffsetReg = makeAnotherReg ();
865 doMultiply (memberOffsetReg, typeOfSequentialTypeIndex,
866 elementSizeReg, idxReg);
867 // Emit an ADD to add memberOffsetReg to the basePtr.
868 BuildMI (BB, X86::ADDrr32, 2,
869 nextBasePtrReg).addReg (basePtrReg).addReg (memberOffsetReg);
870 }
871 // Now that we are here, further indices refer to subtypes of this
872 // one, so we don't need to worry about basePtrReg itself, anymore.
873 basePtrReg = nextBasePtrReg;
874 }
875 // After we have processed all the indices, the result is left in
876 // basePtrReg. Move it to the register where we were expected to
877 // put the answer. A 32-bit move should do it, because we are in
878 // ILP32 land.
879 BuildMI (BB, X86::MOVrr32, 1, getReg (I)).addReg (basePtrReg);
880}
881
882
883/// visitMallocInst - I know that personally, whenever I want to remember
884/// something, I have to clear off some space in my brain.
885void
886ISel::visitMallocInst (MallocInst &I)
887{
888 visitInstruction (I);
889}
890
891
892/// visitAllocaInst - I want some stack space. Come on, man, I said I
893/// want some freakin' stack space.
894void
895ISel::visitAllocaInst (AllocaInst &I)
896{
897 visitInstruction (I);
898}
899
900
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000901/// createSimpleX86InstructionSelector - This pass converts an LLVM function
902/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +0000903/// generated code sucks but the implementation is nice and simple.
904///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000905Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
906 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +0000907}