blob: f14923beddc1b9e7feaf8ef77dd7e0c554f3bbb3 [file] [log] [blame]
Chris Lattner72614082002-10-25 22:55:53 +00001//===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
2//
Chris Lattner3e130a22003-01-13 00:32:26 +00003// This file defines a simple peephole instruction selector for the x86 target
Chris Lattner72614082002-10-25 22:55:53 +00004//
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"
Chris Lattner94af4142002-12-25 05:13:53 +000022#include "llvm/CodeGen/SSARegMap.h"
Chris Lattneraa09b752002-12-28 21:08:28 +000023#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner3e130a22003-01-13 00:32:26 +000024#include "llvm/CodeGen/MachineConstantPool.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000025#include "llvm/Target/TargetMachine.h"
Chris Lattner72614082002-10-25 22:55:53 +000026#include "llvm/Support/InstVisitor.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000027#include "llvm/Target/MRegisterInfo.h"
28#include <map>
Chris Lattner72614082002-10-25 22:55:53 +000029
Chris Lattner333b2fa2002-12-13 10:09:43 +000030/// BMI - A special BuildMI variant that takes an iterator to insert the
31/// instruction at as well as a basic block.
Brian Gaeke71794c02002-12-13 11:22:48 +000032/// this is the version for when you have a destination register in mind.
33inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
Chris Lattner333b2fa2002-12-13 10:09:43 +000034 MachineBasicBlock::iterator &I,
35 MachineOpCode Opcode,
36 unsigned NumOperands,
37 unsigned DestReg) {
Chris Lattnerd7d38722002-12-13 13:04:04 +000038 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
Chris Lattner333b2fa2002-12-13 10:09:43 +000039 MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
Chris Lattnere8f0d922002-12-24 00:03:11 +000040 I = MBB->insert(I, MI)+1;
Chris Lattner333b2fa2002-12-13 10:09:43 +000041 return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
42}
43
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000044/// BMI - A special BuildMI variant that takes an iterator to insert the
45/// instruction at as well as a basic block.
Brian Gaeke71794c02002-12-13 11:22:48 +000046inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000047 MachineBasicBlock::iterator &I,
48 MachineOpCode Opcode,
49 unsigned NumOperands) {
Chris Lattnerd7d38722002-12-13 13:04:04 +000050 assert(I > MBB->begin() && I <= MBB->end() && "Bad iterator!");
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000051 MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
Chris Lattnere8f0d922002-12-24 00:03:11 +000052 I = MBB->insert(I, MI)+1;
Chris Lattnerf08ad9f2002-12-13 10:50:40 +000053 return MachineInstrBuilder(MI);
54}
55
Chris Lattner333b2fa2002-12-13 10:09:43 +000056
Chris Lattner72614082002-10-25 22:55:53 +000057namespace {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000058 struct ISel : public FunctionPass, InstVisitor<ISel> {
59 TargetMachine &TM;
Chris Lattner341a9372002-10-29 17:43:55 +000060 MachineFunction *F; // The function we are compiling into
61 MachineBasicBlock *BB; // The current MBB we are compiling
Chris Lattner72614082002-10-25 22:55:53 +000062
Chris Lattner72614082002-10-25 22:55:53 +000063 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
64
Chris Lattner333b2fa2002-12-13 10:09:43 +000065 // MBBMap - Mapping between LLVM BB -> Machine BB
66 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
67
Chris Lattner3e130a22003-01-13 00:32:26 +000068 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
Chris Lattner72614082002-10-25 22:55:53 +000069
70 /// runOnFunction - Top level implementation of instruction selection for
71 /// the entire function.
72 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000073 bool runOnFunction(Function &Fn) {
Chris Lattner36b36032002-10-29 23:40:58 +000074 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +000075
Chris Lattner065faeb2002-12-28 20:24:02 +000076 // Create all of the machine basic blocks for the function...
Chris Lattner333b2fa2002-12-13 10:09:43 +000077 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
78 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
79
Chris Lattner14aa7fe2002-12-16 22:54:46 +000080 BB = &F->front();
Chris Lattner065faeb2002-12-28 20:24:02 +000081 LoadArgumentsToVirtualRegs(Fn);
Chris Lattner14aa7fe2002-12-16 22:54:46 +000082
Chris Lattner333b2fa2002-12-13 10:09:43 +000083 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000084 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +000085
86 // Select the PHI nodes
87 SelectPHINodes();
88
Chris Lattner72614082002-10-25 22:55:53 +000089 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +000090 MBBMap.clear();
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000091 F = 0;
Chris Lattner72614082002-10-25 22:55:53 +000092 return false; // We never modify the LLVM itself.
93 }
94
Chris Lattnerf0eb7be2002-12-15 21:13:40 +000095 virtual const char *getPassName() const {
96 return "X86 Simple Instruction Selection";
97 }
98
Chris Lattner72614082002-10-25 22:55:53 +000099 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +0000100 /// block. This simply creates a new MachineBasicBlock to emit code into
101 /// and adds it to the current MachineFunction. Subsequent visit* for
102 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +0000103 ///
104 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000105 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +0000106 }
107
Chris Lattner065faeb2002-12-28 20:24:02 +0000108 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
109 /// from the stack into virtual registers.
110 ///
111 void LoadArgumentsToVirtualRegs(Function &F);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000112
113 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
114 /// because we have to generate our sources into the source basic blocks,
115 /// not the current one.
116 ///
117 void SelectPHINodes();
118
Chris Lattner72614082002-10-25 22:55:53 +0000119 // Visitation methods for various instructions. These methods simply emit
120 // fixed X86 code for each instruction.
121 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000122
123 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000124 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000125 void visitBranchInst(BranchInst &BI);
Chris Lattner3e130a22003-01-13 00:32:26 +0000126
127 struct ValueRecord {
128 unsigned Reg;
129 const Type *Ty;
130 ValueRecord(unsigned R, const Type *T) : Reg(R), Ty(T) {}
131 };
132 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
133 const std::vector<ValueRecord> &Args);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000134 void visitCallInst(CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000135
136 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000137 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000138 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
139 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Chris Lattner8a307e82002-12-16 19:32:50 +0000140 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +0000141 unsigned DestReg, const Type *DestTy,
142 unsigned Op0Reg, unsigned Op1Reg);
Chris Lattnerca9671d2002-11-02 20:28:58 +0000143 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000144
Chris Lattnerf01729e2002-11-02 20:54:46 +0000145 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
146 void visitRem(BinaryOperator &B) { visitDivRem(B); }
147 void visitDivRem(BinaryOperator &B);
148
Chris Lattnere2954c82002-11-02 20:04:26 +0000149 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000150 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
151 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
152 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000153
Chris Lattner6d40c192003-01-16 16:43:00 +0000154 // Comparison operators...
155 void visitSetCondInst(SetCondInst &I);
156 bool EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1);
Chris Lattner6fc3c522002-11-17 21:11:55 +0000157
158 // Memory Instructions
Chris Lattner3e130a22003-01-13 00:32:26 +0000159 MachineInstr *doFPLoad(MachineBasicBlock *MBB,
160 MachineBasicBlock::iterator &MBBI,
161 const Type *Ty, unsigned DestReg);
Chris Lattner6fc3c522002-11-17 21:11:55 +0000162 void visitLoadInst(LoadInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000163 void doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg);
Chris Lattner6fc3c522002-11-17 21:11:55 +0000164 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000165 void visitGetElementPtrInst(GetElementPtrInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000166 void visitAllocaInst(AllocaInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000167 void visitMallocInst(MallocInst &I);
168 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000169
Chris Lattnere2954c82002-11-02 20:04:26 +0000170 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000171 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000172 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000173 void visitCastInst(CastInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000174
175 void visitInstruction(Instruction &I) {
176 std::cerr << "Cannot instruction select: " << I;
177 abort();
178 }
179
Brian Gaeke95780cc2002-12-13 07:56:18 +0000180 /// promote32 - Make a value 32-bits wide, and put it somewhere.
Chris Lattner3e130a22003-01-13 00:32:26 +0000181 ///
182 void promote32(unsigned targetReg, const ValueRecord &VR);
183
184 /// EmitByteSwap - Byteswap SrcReg into DestReg.
185 ///
186 void EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class);
Brian Gaeke95780cc2002-12-13 07:56:18 +0000187
Chris Lattner3e130a22003-01-13 00:32:26 +0000188 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
189 /// constant expression GEP support.
190 ///
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000191 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000192 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000193 User::op_iterator IdxEnd, unsigned TargetReg);
194
Chris Lattnerc5291f52002-10-27 21:16:59 +0000195 /// copyConstantToRegister - Output the instructions required to put the
196 /// specified constant into the specified register.
197 ///
Chris Lattner8a307e82002-12-16 19:32:50 +0000198 void copyConstantToRegister(MachineBasicBlock *MBB,
199 MachineBasicBlock::iterator &MBBI,
200 Constant *C, unsigned Reg);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000201
Chris Lattner3e130a22003-01-13 00:32:26 +0000202 /// makeAnotherReg - This method returns the next register number we haven't
203 /// yet used.
204 ///
205 /// Long values are handled somewhat specially. They are always allocated
206 /// as pairs of 32 bit integer values. The register number returned is the
207 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
208 /// of the long value.
209 ///
Chris Lattnerc0812d82002-12-13 06:56:29 +0000210 unsigned makeAnotherReg(const Type *Ty) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000211 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
212 const TargetRegisterClass *RC =
213 TM.getRegisterInfo()->getRegClassForType(Type::IntTy);
214 // Create the lower part
215 F->getSSARegMap()->createVirtualRegister(RC);
216 // Create the upper part.
217 return F->getSSARegMap()->createVirtualRegister(RC)-1;
218 }
219
Chris Lattnerc0812d82002-12-13 06:56:29 +0000220 // Add the mapping of regnumber => reg class to MachineFunction
Chris Lattner94af4142002-12-25 05:13:53 +0000221 const TargetRegisterClass *RC =
222 TM.getRegisterInfo()->getRegClassForType(Ty);
Chris Lattner3e130a22003-01-13 00:32:26 +0000223 return F->getSSARegMap()->createVirtualRegister(RC);
Brian Gaeke20244b72002-12-12 15:33:40 +0000224 }
225
Chris Lattner72614082002-10-25 22:55:53 +0000226 /// getReg - This method turns an LLVM value into a register number. This
227 /// is guaranteed to produce the same register number for a particular value
228 /// every time it is queried.
229 ///
230 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000231 unsigned getReg(Value *V) {
232 // Just append to the end of the current bb.
233 MachineBasicBlock::iterator It = BB->end();
234 return getReg(V, BB, It);
235 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000236 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000237 MachineBasicBlock::iterator &IPt) {
Chris Lattner72614082002-10-25 22:55:53 +0000238 unsigned &Reg = RegMap[V];
Misha Brukmand2cc0172002-11-20 00:58:23 +0000239 if (Reg == 0) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000240 Reg = makeAnotherReg(V->getType());
Misha Brukmand2cc0172002-11-20 00:58:23 +0000241 RegMap[V] = Reg;
Misha Brukmand2cc0172002-11-20 00:58:23 +0000242 }
Chris Lattner72614082002-10-25 22:55:53 +0000243
Chris Lattner6f8fd252002-10-27 21:23:43 +0000244 // If this operand is a constant, emit the code to copy the constant into
245 // the register here...
246 //
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000247 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner8a307e82002-12-16 19:32:50 +0000248 copyConstantToRegister(MBB, IPt, C, Reg);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000249 RegMap.erase(V); // Assign a new name to this constant if ref'd again
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000250 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
251 // Move the address of the global into the register
Chris Lattner3e130a22003-01-13 00:32:26 +0000252 BMI(MBB, IPt, X86::MOVir32, 1, Reg).addGlobalAddress(GV);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000253 RegMap.erase(V); // Assign a new name to this address if ref'd again
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000254 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000255
Chris Lattner72614082002-10-25 22:55:53 +0000256 return Reg;
257 }
Chris Lattner72614082002-10-25 22:55:53 +0000258 };
259}
260
Chris Lattner43189d12002-11-17 20:07:45 +0000261/// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
262/// Representation.
263///
264enum TypeClass {
Chris Lattner94af4142002-12-25 05:13:53 +0000265 cByte, cShort, cInt, cFP, cLong
Chris Lattner43189d12002-11-17 20:07:45 +0000266};
267
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000268/// getClass - Turn a primitive type into a "class" number which is based on the
269/// size of the type, and whether or not it is floating point.
270///
Chris Lattner43189d12002-11-17 20:07:45 +0000271static inline TypeClass getClass(const Type *Ty) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000272 switch (Ty->getPrimitiveID()) {
273 case Type::SByteTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000274 case Type::UByteTyID: return cByte; // Byte operands are class #0
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000275 case Type::ShortTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000276 case Type::UShortTyID: return cShort; // Short operands are class #1
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000277 case Type::IntTyID:
278 case Type::UIntTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000279 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000280
Chris Lattner94af4142002-12-25 05:13:53 +0000281 case Type::FloatTyID:
282 case Type::DoubleTyID: return cFP; // Floating Point is #3
Chris Lattner3e130a22003-01-13 00:32:26 +0000283
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000284 case Type::LongTyID:
Chris Lattner3e130a22003-01-13 00:32:26 +0000285 case Type::ULongTyID: return cLong; // Longs are class #4
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000286 default:
287 assert(0 && "Invalid type to getClass!");
Chris Lattner43189d12002-11-17 20:07:45 +0000288 return cByte; // not reached
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000289 }
290}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000291
Chris Lattner6b993cc2002-12-15 08:02:15 +0000292// getClassB - Just like getClass, but treat boolean values as bytes.
293static inline TypeClass getClassB(const Type *Ty) {
294 if (Ty == Type::BoolTy) return cByte;
295 return getClass(Ty);
296}
297
Chris Lattner06925362002-11-17 21:56:38 +0000298
Chris Lattnerc5291f52002-10-27 21:16:59 +0000299/// copyConstantToRegister - Output the instructions required to put the
300/// specified constant into the specified register.
301///
Chris Lattner8a307e82002-12-16 19:32:50 +0000302void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
303 MachineBasicBlock::iterator &IP,
304 Constant *C, unsigned R) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000305 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
306 if (CE->getOpcode() == Instruction::GetElementPtr) {
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000307 emitGEPOperation(MBB, IP, CE->getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000308 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000309 return;
310 }
311
Brian Gaeke20244b72002-12-12 15:33:40 +0000312 std::cerr << "Offending expr: " << C << "\n";
Chris Lattner94af4142002-12-25 05:13:53 +0000313 assert(0 && "Constant expressions not yet handled!\n");
Brian Gaeke20244b72002-12-12 15:33:40 +0000314 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000315
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000316 if (C->getType()->isIntegral()) {
Chris Lattner6b993cc2002-12-15 08:02:15 +0000317 unsigned Class = getClassB(C->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +0000318
319 if (Class == cLong) {
320 // Copy the value into the register pair.
321 uint64_t Val;
322 if (C->getType()->isSigned())
323 Val = cast<ConstantSInt>(C)->getValue();
324 else
325 Val = cast<ConstantUInt>(C)->getValue();
326
327 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(Val & 0xFFFFFFFF);
328 BMI(MBB, IP, X86::MOVir32, 1, R+1).addZImm(Val >> 32);
329 return;
330 }
331
Chris Lattner94af4142002-12-25 05:13:53 +0000332 assert(Class <= cInt && "Type not handled yet!");
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000333
334 static const unsigned IntegralOpcodeTab[] = {
335 X86::MOVir8, X86::MOVir16, X86::MOVir32
336 };
337
Chris Lattner6b993cc2002-12-15 08:02:15 +0000338 if (C->getType() == Type::BoolTy) {
339 BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
340 } else if (C->getType()->isSigned()) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000341 ConstantSInt *CSI = cast<ConstantSInt>(C);
Chris Lattner3e130a22003-01-13 00:32:26 +0000342 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CSI->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000343 } else {
344 ConstantUInt *CUI = cast<ConstantUInt>(C);
Brian Gaeke71794c02002-12-13 11:22:48 +0000345 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000346 }
Chris Lattner94af4142002-12-25 05:13:53 +0000347 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
348 double Value = CFP->getValue();
349 if (Value == +0.0)
350 BMI(MBB, IP, X86::FLD0, 0, R);
351 else if (Value == +1.0)
352 BMI(MBB, IP, X86::FLD1, 0, R);
353 else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000354 // Otherwise we need to spill the constant to memory...
355 MachineConstantPool *CP = F->getConstantPool();
356 unsigned CPI = CP->getConstantPoolIndex(CFP);
357 addConstantPoolReference(doFPLoad(MBB, IP, CFP->getType(), R), CPI);
Chris Lattner94af4142002-12-25 05:13:53 +0000358 }
359
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000360 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000361 // Copy zero (null pointer) to the register.
Brian Gaeke71794c02002-12-13 11:22:48 +0000362 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000363 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000364 unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
Brian Gaeke71794c02002-12-13 11:22:48 +0000365 BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000366 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000367 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000368 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000369 }
370}
371
Chris Lattner065faeb2002-12-28 20:24:02 +0000372/// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
373/// the stack into virtual registers.
374///
375void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
376 // Emit instructions to load the arguments... On entry to a function on the
377 // X86, the stack frame looks like this:
378 //
379 // [ESP] -- return address
Chris Lattner3e130a22003-01-13 00:32:26 +0000380 // [ESP + 4] -- first argument (leftmost lexically)
381 // [ESP + 8] -- second argument, if first argument is four bytes in size
Chris Lattner065faeb2002-12-28 20:24:02 +0000382 // ...
383 //
Chris Lattnerf158da22003-01-16 02:20:12 +0000384 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
Chris Lattneraa09b752002-12-28 21:08:28 +0000385 MachineFrameInfo *MFI = F->getFrameInfo();
Chris Lattner065faeb2002-12-28 20:24:02 +0000386
387 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
388 unsigned Reg = getReg(*I);
389
Chris Lattner065faeb2002-12-28 20:24:02 +0000390 int FI; // Frame object index
Chris Lattner065faeb2002-12-28 20:24:02 +0000391 switch (getClassB(I->getType())) {
392 case cByte:
Chris Lattneraa09b752002-12-28 21:08:28 +0000393 FI = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000394 addFrameReference(BuildMI(BB, X86::MOVmr8, 4, Reg), FI);
395 break;
396 case cShort:
Chris Lattneraa09b752002-12-28 21:08:28 +0000397 FI = MFI->CreateFixedObject(2, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000398 addFrameReference(BuildMI(BB, X86::MOVmr16, 4, Reg), FI);
399 break;
400 case cInt:
Chris Lattneraa09b752002-12-28 21:08:28 +0000401 FI = MFI->CreateFixedObject(4, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000402 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
403 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000404 case cLong:
405 FI = MFI->CreateFixedObject(8, ArgOffset);
406 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
407 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg+1), FI, 4);
408 ArgOffset += 4; // longs require 4 additional bytes
409 break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000410 case cFP:
411 unsigned Opcode;
412 if (I->getType() == Type::FloatTy) {
413 Opcode = X86::FLDr32;
Chris Lattneraa09b752002-12-28 21:08:28 +0000414 FI = MFI->CreateFixedObject(4, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000415 } else {
416 Opcode = X86::FLDr64;
Chris Lattneraa09b752002-12-28 21:08:28 +0000417 FI = MFI->CreateFixedObject(8, ArgOffset);
Chris Lattner3e130a22003-01-13 00:32:26 +0000418 ArgOffset += 4; // doubles require 4 additional bytes
Chris Lattner065faeb2002-12-28 20:24:02 +0000419 }
420 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
421 break;
422 default:
423 assert(0 && "Unhandled argument type!");
424 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000425 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000426 }
427}
428
429
Chris Lattner333b2fa2002-12-13 10:09:43 +0000430/// SelectPHINodes - Insert machine code to generate phis. This is tricky
431/// because we have to generate our sources into the source basic blocks, not
432/// the current one.
433///
434void ISel::SelectPHINodes() {
Chris Lattner3501fea2003-01-14 22:00:31 +0000435 const TargetInstrInfo &TII = TM.getInstrInfo();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000436 const Function &LF = *F->getFunction(); // The LLVM function...
437 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
438 const BasicBlock *BB = I;
439 MachineBasicBlock *MBB = MBBMap[I];
440
441 // Loop over all of the PHI nodes in the LLVM basic block...
442 unsigned NumPHIs = 0;
443 for (BasicBlock::const_iterator I = BB->begin();
444 PHINode *PN = (PHINode*)dyn_cast<PHINode>(&*I); ++I) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000445
Chris Lattner333b2fa2002-12-13 10:09:43 +0000446 // Create a new machine instr PHI node, and insert it.
Chris Lattner3e130a22003-01-13 00:32:26 +0000447 unsigned PHIReg = getReg(*PN);
448 MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
449 MBB->insert(MBB->begin()+NumPHIs++, PhiMI);
450
451 MachineInstr *LongPhiMI = 0;
452 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
453 LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
454 MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
455 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000456
457 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
458 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
459
460 // Get the incoming value into a virtual register. If it is not already
461 // available in a virtual register, insert the computation code into
462 // PredMBB
Chris Lattner92053632002-12-13 11:52:34 +0000463 //
Chris Lattner3e130a22003-01-13 00:32:26 +0000464 MachineBasicBlock::iterator PI = PredMBB->end();
465 while (PI != PredMBB->begin() &&
Chris Lattner3501fea2003-01-14 22:00:31 +0000466 TII.isTerminatorInstr((*(PI-1))->getOpcode()))
Chris Lattner3e130a22003-01-13 00:32:26 +0000467 --PI;
468 unsigned ValReg = getReg(PN->getIncomingValue(i), PredMBB, PI);
469 PhiMI->addRegOperand(ValReg);
470 PhiMI->addMachineBasicBlockOperand(PredMBB);
471 if (LongPhiMI) {
472 LongPhiMI->addRegOperand(ValReg+1);
473 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
474 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000475 }
476 }
477 }
478}
479
Chris Lattner6d40c192003-01-16 16:43:00 +0000480// canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
481// the conditional branch instruction which is the only user of the cc
482// instruction. This is the case if the conditional branch is the only user of
483// the setcc, and if the setcc is in the same basic block as the conditional
484// branch. We also don't handle long arguments below, so we reject them here as
485// well.
486//
487static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
488 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
489 if (SCI->use_size() == 1 && isa<BranchInst>(SCI->use_back()) &&
490 SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
491 const Type *Ty = SCI->getOperand(0)->getType();
492 if (Ty != Type::LongTy && Ty != Type::ULongTy)
493 return SCI;
494 }
495 return 0;
496}
Chris Lattner333b2fa2002-12-13 10:09:43 +0000497
Chris Lattner6d40c192003-01-16 16:43:00 +0000498// Return a fixed numbering for setcc instructions which does not depend on the
499// order of the opcodes.
500//
501static unsigned getSetCCNumber(unsigned Opcode) {
502 switch(Opcode) {
503 default: assert(0 && "Unknown setcc instruction!");
504 case Instruction::SetEQ: return 0;
505 case Instruction::SetNE: return 1;
506 case Instruction::SetLT: return 2;
507 case Instruction::SetGT: return 3;
508 case Instruction::SetLE: return 4;
509 case Instruction::SetGE: return 5;
510 }
511}
Chris Lattner06925362002-11-17 21:56:38 +0000512
Chris Lattner6d40c192003-01-16 16:43:00 +0000513// LLVM -> X86 signed X86 unsigned
514// ----- ---------- ------------
515// seteq -> sete sete
516// setne -> setne setne
517// setlt -> setl setb
518// setgt -> setg seta
519// setle -> setle setbe
520// setge -> setge setae
521static const unsigned SetCCOpcodeTab[2][6] = {
522 {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAr, X86::SETBEr, X86::SETAEr},
523 {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGr, X86::SETLEr, X86::SETGEr},
524};
525
526bool ISel::EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1) {
527
Brian Gaeke1749d632002-11-07 17:59:21 +0000528 // The arguments are already supposed to be of the same type.
Chris Lattner6d40c192003-01-16 16:43:00 +0000529 const Type *CompTy = Op0->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +0000530 bool isSigned = CompTy->isSigned();
Chris Lattner6d40c192003-01-16 16:43:00 +0000531 unsigned reg1 = getReg(Op0);
532 unsigned reg2 = getReg(Op1);
Chris Lattner05093a52002-11-21 15:52:38 +0000533
Chris Lattner3e130a22003-01-13 00:32:26 +0000534 unsigned Class = getClassB(CompTy);
535 switch (Class) {
536 default: assert(0 && "Unknown type class!");
537 // Emit: cmp <var1>, <var2> (do the comparison). We can
538 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
539 // 32-bit.
540 case cByte:
541 BuildMI(BB, X86::CMPrr8, 2).addReg(reg1).addReg(reg2);
542 break;
543 case cShort:
544 BuildMI(BB, X86::CMPrr16, 2).addReg(reg1).addReg(reg2);
545 break;
546 case cInt:
547 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
548 break;
549 case cFP:
550 BuildMI(BB, X86::FpUCOM, 2).addReg(reg1).addReg(reg2);
551 BuildMI(BB, X86::FNSTSWr8, 0);
552 BuildMI(BB, X86::SAHF, 1);
553 isSigned = false; // Compare with unsigned operators
554 break;
555
556 case cLong:
557 if (OpNum < 2) { // seteq, setne
558 unsigned LoTmp = makeAnotherReg(Type::IntTy);
559 unsigned HiTmp = makeAnotherReg(Type::IntTy);
560 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
561 BuildMI(BB, X86::XORrr32, 2, LoTmp).addReg(reg1).addReg(reg2);
562 BuildMI(BB, X86::XORrr32, 2, HiTmp).addReg(reg1+1).addReg(reg2+1);
563 BuildMI(BB, X86::ORrr32, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
564 break; // Allow the sete or setne to be generated from flags set by OR
565 } else {
566 // Emit a sequence of code which compares the high and low parts once
567 // each, then uses a conditional move to handle the overflow case. For
568 // example, a setlt for long would generate code like this:
569 //
570 // AL = lo(op1) < lo(op2) // Signedness depends on operands
571 // BL = hi(op1) < hi(op2) // Always unsigned comparison
572 // dest = hi(op1) == hi(op2) ? AL : BL;
573 //
574
Chris Lattner6d40c192003-01-16 16:43:00 +0000575 // FIXME: This would be much better if we had hierarchical register
Chris Lattner3e130a22003-01-13 00:32:26 +0000576 // classes! Until then, hardcode registers so that we can deal with their
577 // aliases (because we don't have conditional byte moves).
578 //
579 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
Chris Lattner6d40c192003-01-16 16:43:00 +0000580 BuildMI(BB, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
Chris Lattner3e130a22003-01-13 00:32:26 +0000581 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1+1).addReg(reg2+1);
Chris Lattner6d40c192003-01-16 16:43:00 +0000582 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, X86::BL);
Chris Lattner3e130a22003-01-13 00:32:26 +0000583 BuildMI(BB, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
Chris Lattner6d40c192003-01-16 16:43:00 +0000584 // NOTE: visitSetCondInst knows that the value is dumped into the BL
585 // register at this point for long values...
586 return isSigned;
Chris Lattner3e130a22003-01-13 00:32:26 +0000587 }
588 }
Chris Lattner6d40c192003-01-16 16:43:00 +0000589 return isSigned;
590}
Chris Lattner3e130a22003-01-13 00:32:26 +0000591
Chris Lattner6d40c192003-01-16 16:43:00 +0000592
593/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
594/// register, then move it to wherever the result should be.
595///
596void ISel::visitSetCondInst(SetCondInst &I) {
597 if (canFoldSetCCIntoBranch(&I)) return; // Fold this into a branch...
598
599 unsigned OpNum = getSetCCNumber(I.getOpcode());
600 unsigned DestReg = getReg(I);
601 bool isSigned = EmitComparisonGetSignedness(OpNum, I.getOperand(0),
602 I.getOperand(1));
603
604 if (getClassB(I.getOperand(0)->getType()) != cLong || OpNum < 2) {
605 // Handle normal comparisons with a setcc instruction...
606 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, DestReg);
607 } else {
608 // Handle long comparisons by copying the value which is already in BL into
609 // the register we want...
610 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(X86::BL);
611 }
Brian Gaeke1749d632002-11-07 17:59:21 +0000612}
Chris Lattner51b49a92002-11-02 19:45:49 +0000613
Brian Gaekec2505982002-11-30 11:57:28 +0000614/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
615/// operand, in the specified target register.
Chris Lattner3e130a22003-01-13 00:32:26 +0000616void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
617 bool isUnsigned = VR.Ty->isUnsigned();
618 switch (getClassB(VR.Ty)) {
Chris Lattner94af4142002-12-25 05:13:53 +0000619 case cByte:
620 // Extend value into target register (8->32)
621 if (isUnsigned)
Chris Lattner3e130a22003-01-13 00:32:26 +0000622 BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000623 else
Chris Lattner3e130a22003-01-13 00:32:26 +0000624 BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000625 break;
626 case cShort:
627 // Extend value into target register (16->32)
628 if (isUnsigned)
Chris Lattner3e130a22003-01-13 00:32:26 +0000629 BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000630 else
Chris Lattner3e130a22003-01-13 00:32:26 +0000631 BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000632 break;
633 case cInt:
634 // Move value into target register (32->32)
Chris Lattner3e130a22003-01-13 00:32:26 +0000635 BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(VR.Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000636 break;
637 default:
638 assert(0 && "Unpromotable operand class in promote32");
639 }
Brian Gaekec2505982002-11-30 11:57:28 +0000640}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000641
Chris Lattner72614082002-10-25 22:55:53 +0000642/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
643/// we have the following possibilities:
644///
645/// ret void: No return value, simply emit a 'ret' instruction
646/// ret sbyte, ubyte : Extend value into EAX and return
647/// ret short, ushort: Extend value into EAX and return
648/// ret int, uint : Move value into EAX and return
649/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +0000650/// ret long, ulong : Move value into EAX/EDX and return
651/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +0000652///
Chris Lattner3e130a22003-01-13 00:32:26 +0000653void ISel::visitReturnInst(ReturnInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +0000654 if (I.getNumOperands() == 0) {
655 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
656 return;
657 }
658
659 Value *RetVal = I.getOperand(0);
Chris Lattner3e130a22003-01-13 00:32:26 +0000660 unsigned RetReg = getReg(RetVal);
661 switch (getClassB(RetVal->getType())) {
Chris Lattner94af4142002-12-25 05:13:53 +0000662 case cByte: // integral return values: extend or move into EAX and return
663 case cShort:
664 case cInt:
Chris Lattner3e130a22003-01-13 00:32:26 +0000665 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
Chris Lattner94af4142002-12-25 05:13:53 +0000666 break;
667 case cFP: // Floats & Doubles: Return in ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +0000668 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
Chris Lattner94af4142002-12-25 05:13:53 +0000669 break;
670 case cLong:
Chris Lattner3e130a22003-01-13 00:32:26 +0000671 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
672 BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
673 break;
Chris Lattner94af4142002-12-25 05:13:53 +0000674 default:
Chris Lattner3e130a22003-01-13 00:32:26 +0000675 visitInstruction(I);
Chris Lattner94af4142002-12-25 05:13:53 +0000676 }
Chris Lattner43189d12002-11-17 20:07:45 +0000677 // Emit a 'ret' instruction
Chris Lattner94af4142002-12-25 05:13:53 +0000678 BuildMI(BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +0000679}
680
Chris Lattner51b49a92002-11-02 19:45:49 +0000681/// visitBranchInst - Handle conditional and unconditional branches here. Note
682/// that since code layout is frozen at this point, that if we are trying to
683/// jump to a block that is the immediate successor of the current block, we can
Chris Lattner6d40c192003-01-16 16:43:00 +0000684/// just make a fall-through (but we don't currently).
Chris Lattner51b49a92002-11-02 19:45:49 +0000685///
Chris Lattner94af4142002-12-25 05:13:53 +0000686void ISel::visitBranchInst(BranchInst &BI) {
Chris Lattner6d40c192003-01-16 16:43:00 +0000687 if (!BI.isConditional()) {
688 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
689 return;
690 }
691
692 // See if we can fold the setcc into the branch itself...
693 SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
694 if (SCI == 0) {
695 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
696 // computed some other way...
Chris Lattner065faeb2002-12-28 20:24:02 +0000697 unsigned condReg = getReg(BI.getCondition());
Chris Lattner94af4142002-12-25 05:13:53 +0000698 BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +0000699 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
Chris Lattner6d40c192003-01-16 16:43:00 +0000700 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
701 return;
Chris Lattner94af4142002-12-25 05:13:53 +0000702 }
Chris Lattner6d40c192003-01-16 16:43:00 +0000703
704 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
705 bool isSigned = EmitComparisonGetSignedness(OpNum, SCI->getOperand(0),
706 SCI->getOperand(1));
707
708 // LLVM -> X86 signed X86 unsigned
709 // ----- ---------- ------------
710 // seteq -> je je
711 // setne -> jne jne
712 // setlt -> jl jb
713 // setgt -> jg ja
714 // setle -> jle jbe
715 // setge -> jge jae
716 static const unsigned OpcodeTab[2][6] = {
717 { X86::JE, X86::JNE, X86::JB, X86::JA, X86::JBE, X86::JAE },
718 { X86::JE, X86::JNE, X86::JL, X86::JG, X86::JLE, X86::JGE },
719 };
720
721 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
722 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
Chris Lattner2df035b2002-11-02 19:27:56 +0000723}
724
Chris Lattner3e130a22003-01-13 00:32:26 +0000725
726/// doCall - This emits an abstract call instruction, setting up the arguments
727/// and the return value as appropriate. For the actual function call itself,
728/// it inserts the specified CallMI instruction into the stream.
729///
730void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
731 const std::vector<ValueRecord> &Args) {
732
Chris Lattner065faeb2002-12-28 20:24:02 +0000733 // Count how many bytes are to be pushed on the stack...
734 unsigned NumBytes = 0;
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000735
Chris Lattner3e130a22003-01-13 00:32:26 +0000736 if (!Args.empty()) {
737 for (unsigned i = 0, e = Args.size(); i != e; ++i)
738 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +0000739 case cByte: case cShort: case cInt:
Chris Lattner3e130a22003-01-13 00:32:26 +0000740 NumBytes += 4; break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000741 case cLong:
Chris Lattner3e130a22003-01-13 00:32:26 +0000742 NumBytes += 8; break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000743 case cFP:
Chris Lattner3e130a22003-01-13 00:32:26 +0000744 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
Chris Lattner065faeb2002-12-28 20:24:02 +0000745 break;
746 default: assert(0 && "Unknown class!");
747 }
748
749 // Adjust the stack pointer for the new arguments...
750 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
751
752 // Arguments go on the stack in reverse order, as specified by the ABI.
753 unsigned ArgOffset = 0;
Chris Lattner3e130a22003-01-13 00:32:26 +0000754 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
755 unsigned ArgReg = Args[i].Reg;
756 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +0000757 case cByte:
758 case cShort: {
759 // Promote arg to 32 bits wide into a temporary register...
760 unsigned R = makeAnotherReg(Type::UIntTy);
Chris Lattner3e130a22003-01-13 00:32:26 +0000761 promote32(R, Args[i]);
Chris Lattner065faeb2002-12-28 20:24:02 +0000762 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
763 X86::ESP, ArgOffset).addReg(R);
764 break;
765 }
766 case cInt:
767 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
Chris Lattner3e130a22003-01-13 00:32:26 +0000768 X86::ESP, ArgOffset).addReg(ArgReg);
Chris Lattner065faeb2002-12-28 20:24:02 +0000769 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000770 case cLong:
771 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
772 X86::ESP, ArgOffset).addReg(ArgReg);
773 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
774 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
775 ArgOffset += 4; // 8 byte entry, not 4.
776 break;
777
Chris Lattner065faeb2002-12-28 20:24:02 +0000778 case cFP:
Chris Lattner3e130a22003-01-13 00:32:26 +0000779 if (Args[i].Ty == Type::FloatTy) {
Chris Lattner065faeb2002-12-28 20:24:02 +0000780 addRegOffset(BuildMI(BB, X86::FSTr32, 5),
Chris Lattner3e130a22003-01-13 00:32:26 +0000781 X86::ESP, ArgOffset).addReg(ArgReg);
Chris Lattner065faeb2002-12-28 20:24:02 +0000782 } else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000783 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
784 addRegOffset(BuildMI(BB, X86::FSTr64, 5),
785 X86::ESP, ArgOffset).addReg(ArgReg);
786 ArgOffset += 4; // 8 byte entry, not 4.
Chris Lattner065faeb2002-12-28 20:24:02 +0000787 }
788 break;
789
Chris Lattner3e130a22003-01-13 00:32:26 +0000790 default: assert(0 && "Unknown class!");
Chris Lattner065faeb2002-12-28 20:24:02 +0000791 }
792 ArgOffset += 4;
Chris Lattner94af4142002-12-25 05:13:53 +0000793 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000794 } else {
795 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +0000796 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +0000797
Chris Lattner3e130a22003-01-13 00:32:26 +0000798 BB->push_back(CallMI);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +0000799
Chris Lattner065faeb2002-12-28 20:24:02 +0000800 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
Chris Lattnera3243642002-12-04 23:45:28 +0000801
802 // If there is a return value, scavenge the result from the location the call
803 // leaves it in...
804 //
Chris Lattner3e130a22003-01-13 00:32:26 +0000805 if (Ret.Ty != Type::VoidTy) {
806 unsigned DestClass = getClassB(Ret.Ty);
807 switch (DestClass) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000808 case cByte:
809 case cShort:
810 case cInt: {
811 // Integral results are in %eax, or the appropriate portion
812 // thereof.
813 static const unsigned regRegMove[] = {
814 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
815 };
816 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +0000817 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000818 break;
Brian Gaeke20244b72002-12-12 15:33:40 +0000819 }
Chris Lattner94af4142002-12-25 05:13:53 +0000820 case cFP: // Floating-point return values live in %ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +0000821 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000822 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000823 case cLong: // Long values are left in EDX:EAX
824 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
825 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
826 break;
827 default: assert(0 && "Unknown class!");
Chris Lattner4fa1acc2002-12-04 23:50:28 +0000828 }
Chris Lattnera3243642002-12-04 23:45:28 +0000829 }
Brian Gaekefa8d5712002-11-22 11:07:01 +0000830}
Chris Lattner2df035b2002-11-02 19:27:56 +0000831
Chris Lattner3e130a22003-01-13 00:32:26 +0000832
833/// visitCallInst - Push args on stack and do a procedure call instruction.
834void ISel::visitCallInst(CallInst &CI) {
835 MachineInstr *TheCall;
836 if (Function *F = CI.getCalledFunction()) {
837 // Emit a CALL instruction with PC-relative displacement.
838 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
839 } else { // Emit an indirect call...
840 unsigned Reg = getReg(CI.getCalledValue());
841 TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
842 }
843
844 std::vector<ValueRecord> Args;
845 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
846 Args.push_back(ValueRecord(getReg(CI.getOperand(i)),
847 CI.getOperand(i)->getType()));
848
849 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
850 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
851}
852
853
Chris Lattner68aad932002-11-02 20:13:22 +0000854/// visitSimpleBinary - Implement simple binary operators for integral types...
855/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
856/// 4 for Xor.
857///
858void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000859 unsigned Class = getClassB(B.getType());
Chris Lattnere2954c82002-11-02 20:04:26 +0000860
861 static const unsigned OpcodeTab[][4] = {
Chris Lattner68aad932002-11-02 20:13:22 +0000862 // Arithmetic operators
Chris Lattner94af4142002-12-25 05:13:53 +0000863 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD }, // ADD
864 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB }, // SUB
Chris Lattner68aad932002-11-02 20:13:22 +0000865
866 // Bitwise operators
Chris Lattnere2954c82002-11-02 20:04:26 +0000867 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
868 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
869 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
870 };
Chris Lattner3e130a22003-01-13 00:32:26 +0000871
872 bool isLong = false;
873 if (Class == cLong) {
874 isLong = true;
875 Class = cInt; // Bottom 32 bits are handled just like ints
876 }
Chris Lattnere2954c82002-11-02 20:04:26 +0000877
878 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner94af4142002-12-25 05:13:53 +0000879 assert(Opcode && "Floating point arguments to logical inst?");
Chris Lattnere2954c82002-11-02 20:04:26 +0000880 unsigned Op0r = getReg(B.getOperand(0));
881 unsigned Op1r = getReg(B.getOperand(1));
Chris Lattner3e130a22003-01-13 00:32:26 +0000882 unsigned DestReg = getReg(B);
883 BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
884
885 if (isLong) { // Handle the upper 32 bits of long values...
886 static const unsigned TopTab[] = {
887 X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
888 };
889 BuildMI(BB, TopTab[OperatorClass], 2,
890 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
891 }
Chris Lattnere2954c82002-11-02 20:04:26 +0000892}
893
Chris Lattner3e130a22003-01-13 00:32:26 +0000894/// doMultiply - Emit appropriate instructions to multiply together the
895/// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
896/// result should be given as DestTy.
897///
898/// FIXME: doMultiply should use one of the two address IMUL instructions!
899///
Chris Lattner8a307e82002-12-16 19:32:50 +0000900void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +0000901 unsigned DestReg, const Type *DestTy,
Chris Lattner8a307e82002-12-16 19:32:50 +0000902 unsigned op0Reg, unsigned op1Reg) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000903 unsigned Class = getClass(DestTy);
Chris Lattner94af4142002-12-25 05:13:53 +0000904 switch (Class) {
905 case cFP: // Floating point multiply
Chris Lattner3e130a22003-01-13 00:32:26 +0000906 BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000907 return;
908 default:
Chris Lattner3e130a22003-01-13 00:32:26 +0000909 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
Chris Lattner94af4142002-12-25 05:13:53 +0000910 case cByte:
911 case cShort:
912 case cInt: // Small integerals, handled below...
913 break;
914 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000915
916 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +0000917 static const unsigned MulOpcode[]={ X86::MULr8 , X86::MULr16 , X86::MULr32 };
Brian Gaeke20244b72002-12-12 15:33:40 +0000918 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
919 unsigned Reg = Regs[Class];
920
921 // Emit a MOV to put the first operand into the appropriately-sized
922 // subreg of EAX.
Chris Lattner3e130a22003-01-13 00:32:26 +0000923 BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg(op0Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000924
925 // Emit the appropriate multiply instruction.
Chris Lattner3e130a22003-01-13 00:32:26 +0000926 BMI(MBB, MBBI, MulOpcode[Class], 1).addReg(op1Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000927
928 // Emit another MOV to put the result into the destination register.
Chris Lattner3e130a22003-01-13 00:32:26 +0000929 BMI(MBB, MBBI, MovOpcode[Class], 1, DestReg).addReg(Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +0000930}
931
Chris Lattnerca9671d2002-11-02 20:28:58 +0000932/// visitMul - Multiplies are not simple binary operators because they must deal
933/// with the EAX register explicitly.
934///
935void ISel::visitMul(BinaryOperator &I) {
Chris Lattner202a2d02002-12-13 13:07:42 +0000936 unsigned Op0Reg = getReg(I.getOperand(0));
937 unsigned Op1Reg = getReg(I.getOperand(1));
Chris Lattner3e130a22003-01-13 00:32:26 +0000938 unsigned DestReg = getReg(I);
939
940 // Simple scalar multiply?
941 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
942 MachineBasicBlock::iterator MBBI = BB->end();
943 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
944 } else {
945 // Long value. We have to do things the hard way...
946 // Multiply the two low parts... capturing carry into EDX
947 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
948 BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg); // AL*BL
949
950 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
951 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX); // AL*BL
952 BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
953
954 MachineBasicBlock::iterator MBBI = BB->end();
955 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
956 doMultiply(BB, MBBI, AHBLReg, Type::UIntTy, Op0Reg+1, Op1Reg); // AH*BL
957
958 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
959 BuildMI(BB, X86::ADDrr32, 2, // AH*BL+(AL*BL >> 32)
960 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
961
962 MBBI = BB->end();
963 unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
964 doMultiply(BB, MBBI, ALBHReg, Type::UIntTy, Op0Reg, Op1Reg+1); // AL*BH
965
966 BuildMI(BB, X86::ADDrr32, 2, // AL*BH + AH*BL + (AL*BL >> 32)
967 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
968 }
Chris Lattnerf01729e2002-11-02 20:54:46 +0000969}
Chris Lattnerca9671d2002-11-02 20:28:58 +0000970
Chris Lattner06925362002-11-17 21:56:38 +0000971
Chris Lattnerf01729e2002-11-02 20:54:46 +0000972/// visitDivRem - Handle division and remainder instructions... these
973/// instruction both require the same instructions to be generated, they just
974/// select the result from a different register. Note that both of these
975/// instructions work differently for signed and unsigned operands.
976///
977void ISel::visitDivRem(BinaryOperator &I) {
Chris Lattner94af4142002-12-25 05:13:53 +0000978 unsigned Class = getClass(I.getType());
979 unsigned Op0Reg = getReg(I.getOperand(0));
980 unsigned Op1Reg = getReg(I.getOperand(1));
981 unsigned ResultReg = getReg(I);
982
983 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000984 case cFP: // Floating point divide
Chris Lattner94af4142002-12-25 05:13:53 +0000985 if (I.getOpcode() == Instruction::Div)
986 BuildMI(BB, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000987 else { // Floating point remainder...
988 MachineInstr *TheCall =
989 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
990 std::vector<ValueRecord> Args;
991 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
992 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
993 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
994 }
Chris Lattner94af4142002-12-25 05:13:53 +0000995 return;
Chris Lattner3e130a22003-01-13 00:32:26 +0000996 case cLong: {
997 static const char *FnName[] =
998 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
999
1000 unsigned NameIdx = I.getType()->isUnsigned()*2;
1001 NameIdx += I.getOpcode() == Instruction::Div;
1002 MachineInstr *TheCall =
1003 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1004
1005 std::vector<ValueRecord> Args;
1006 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1007 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1008 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1009 return;
1010 }
1011 case cByte: case cShort: case cInt:
1012 break; // Small integerals, handled below...
1013 default: assert(0 && "Unknown class!");
Chris Lattner94af4142002-12-25 05:13:53 +00001014 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00001015
1016 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
1017 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
Brian Gaeke6559bb92002-11-14 22:32:30 +00001018 static const unsigned ExtOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
Chris Lattnerf01729e2002-11-02 20:54:46 +00001019 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
1020 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1021
1022 static const unsigned DivOpcode[][4] = {
Chris Lattner3e130a22003-01-13 00:32:26 +00001023 { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 }, // Unsigned division
1024 { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 }, // Signed division
Chris Lattnerf01729e2002-11-02 20:54:46 +00001025 };
1026
1027 bool isSigned = I.getType()->isSigned();
1028 unsigned Reg = Regs[Class];
1029 unsigned ExtReg = ExtRegs[Class];
Chris Lattnerf01729e2002-11-02 20:54:46 +00001030
1031 // Put the first operand into one of the A registers...
1032 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1033
1034 if (isSigned) {
1035 // Emit a sign extension instruction...
Chris Lattnera4978cc2002-12-01 23:24:58 +00001036 BuildMI(BB, ExtOpcode[Class], 0);
Chris Lattnerf01729e2002-11-02 20:54:46 +00001037 } else {
1038 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
1039 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
1040 }
1041
Chris Lattner06925362002-11-17 21:56:38 +00001042 // Emit the appropriate divide or remainder instruction...
Chris Lattner92845e32002-11-21 18:54:29 +00001043 BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
Chris Lattner06925362002-11-17 21:56:38 +00001044
Chris Lattnerf01729e2002-11-02 20:54:46 +00001045 // Figure out which register we want to pick the result out of...
1046 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
1047
Chris Lattnerf01729e2002-11-02 20:54:46 +00001048 // Put the result into the destination register...
Chris Lattner94af4142002-12-25 05:13:53 +00001049 BuildMI(BB, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +00001050}
Chris Lattnere2954c82002-11-02 20:04:26 +00001051
Chris Lattner06925362002-11-17 21:56:38 +00001052
Brian Gaekea1719c92002-10-31 23:03:59 +00001053/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1054/// for constant immediate shift values, and for constant immediate
1055/// shift values equal to 1. Even the general case is sort of special,
1056/// because the shift amount has to be in CL, not just any old register.
1057///
Chris Lattner3e130a22003-01-13 00:32:26 +00001058void ISel::visitShiftInst(ShiftInst &I) {
1059 unsigned SrcReg = getReg(I.getOperand(0));
Chris Lattnerf01729e2002-11-02 20:54:46 +00001060 unsigned DestReg = getReg(I);
Chris Lattnere9913f22002-11-02 01:41:55 +00001061 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3e130a22003-01-13 00:32:26 +00001062 bool isSigned = I.getType()->isSigned();
1063 unsigned Class = getClass(I.getType());
1064
1065 static const unsigned ConstantOperand[][4] = {
1066 { X86::SHRir8, X86::SHRir16, X86::SHRir32, X86::SHRDir32 }, // SHR
1067 { X86::SARir8, X86::SARir16, X86::SARir32, X86::SHRDir32 }, // SAR
1068 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SHL
1069 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SAL = SHL
1070 };
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001071
Chris Lattner3e130a22003-01-13 00:32:26 +00001072 static const unsigned NonConstantOperand[][4] = {
1073 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32 }, // SHR
1074 { X86::SARrr8, X86::SARrr16, X86::SARrr32 }, // SAR
1075 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SHL
1076 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SAL = SHL
1077 };
Chris Lattner796df732002-11-02 00:44:25 +00001078
Chris Lattner3e130a22003-01-13 00:32:26 +00001079 // Longs, as usual, are handled specially...
1080 if (Class == cLong) {
1081 // If we have a constant shift, we can generate much more efficient code
1082 // than otherwise...
1083 //
1084 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1085 unsigned Amount = CUI->getValue();
1086 if (Amount < 32) {
1087 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1088 if (isLeftShift) {
1089 BuildMI(BB, Opc[3], 3,
1090 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1091 BuildMI(BB, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1092 } else {
1093 BuildMI(BB, Opc[3], 3,
1094 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addZImm(Amount);
1095 BuildMI(BB, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1096 }
1097 } else { // Shifting more than 32 bits
1098 Amount -= 32;
1099 if (isLeftShift) {
1100 BuildMI(BB, X86::SHLir32, 2,DestReg+1).addReg(SrcReg).addZImm(Amount);
1101 BuildMI(BB, X86::MOVir32, 1,DestReg ).addZImm(0);
1102 } else {
1103 unsigned Opcode = isSigned ? X86::SARir32 : X86::SHRir32;
1104 BuildMI(BB, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1105 BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1106 }
1107 }
1108 } else {
1109 visitInstruction(I); // FIXME: Implement long shift by non-constant
Brian Gaekea1719c92002-10-31 23:03:59 +00001110 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001111 return;
1112 }
Chris Lattnere9913f22002-11-02 01:41:55 +00001113
Chris Lattner3e130a22003-01-13 00:32:26 +00001114 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1115 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1116 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001117
Chris Lattner3e130a22003-01-13 00:32:26 +00001118 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1119 BuildMI(BB, Opc[Class], 2, DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1120 } else { // The shift amount is non-constant.
1121 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001122
Chris Lattner3e130a22003-01-13 00:32:26 +00001123 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1124 BuildMI(BB, Opc[Class], 1, DestReg).addReg(SrcReg);
1125 }
1126}
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001127
Chris Lattner3e130a22003-01-13 00:32:26 +00001128
1129/// doFPLoad - This method is used to load an FP value from memory using the
1130/// current endianness. NOTE: This method returns a partially constructed load
1131/// instruction which needs to have the memory source filled in still.
1132///
1133MachineInstr *ISel::doFPLoad(MachineBasicBlock *MBB,
1134 MachineBasicBlock::iterator &MBBI,
1135 const Type *Ty, unsigned DestReg) {
1136 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1137 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
1138
1139 if (TM.getTargetData().isLittleEndian()) // fast path...
1140 return BMI(MBB, MBBI, LoadOpcode, 4, DestReg);
1141
1142 // If we are big-endian, start by creating an LEA instruction to represent the
1143 // address of the memory location to load from...
1144 //
1145 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1146 MachineInstr *Result = BMI(MBB, MBBI, X86::LEAr32, 5, SrcAddrReg);
1147
1148 // Allocate a temporary stack slot to transform the value into...
1149 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1150
1151 // Perform the bswaps 32 bits at a time...
1152 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1153 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1154 addDirectMem(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1155 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1156 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1157 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32, 5),
1158 FrameIdx, Offset).addReg(TmpReg2);
1159
1160 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1161 TmpReg1 = makeAnotherReg(Type::UIntTy);
1162 TmpReg2 = makeAnotherReg(Type::UIntTy);
1163
1164 addRegOffset(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1165 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1166 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1167 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32,5), FrameIdx).addReg(TmpReg2);
1168 }
1169
1170 // Now we can reload the final byteswapped result into the final destination.
1171 addFrameReference(BMI(MBB, MBBI, LoadOpcode, 4, DestReg), FrameIdx);
1172 return Result;
1173}
1174
1175/// EmitByteSwap - Byteswap SrcReg into DestReg.
1176///
1177void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
1178 // Emit the byte swap instruction...
1179 switch (Class) {
1180 case cByte:
1181 // No byteswap neccesary for 8 bit value...
1182 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(SrcReg);
1183 break;
1184 case cInt:
1185 // Use the 32 bit bswap instruction to do a 32 bit swap...
1186 BuildMI(BB, X86::BSWAPr32, 1, DestReg).addReg(SrcReg);
1187 break;
1188
1189 case cShort:
1190 // For 16 bit we have to use an xchg instruction, because there is no
1191 // 16-bit bswap. XCHG is neccesarily not in SSA form, so we force things
1192 // into AX to do the xchg.
1193 //
1194 BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(SrcReg);
1195 BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
1196 .addReg(X86::AH, MOTy::UseAndDef);
1197 BuildMI(BB, X86::MOVrr16, 1, DestReg).addReg(X86::AX);
1198 break;
1199 default: assert(0 && "Cannot byteswap this class!");
1200 }
Brian Gaekea1719c92002-10-31 23:03:59 +00001201}
1202
Chris Lattner06925362002-11-17 21:56:38 +00001203
Chris Lattner6fc3c522002-11-17 21:11:55 +00001204/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
Chris Lattnere8f0d922002-12-24 00:03:11 +00001205/// instruction. The load and store instructions are the only place where we
1206/// need to worry about the memory layout of the target machine.
Chris Lattner6fc3c522002-11-17 21:11:55 +00001207///
1208void ISel::visitLoadInst(LoadInst &I) {
Chris Lattnere8f0d922002-12-24 00:03:11 +00001209 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1210 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
Chris Lattner94af4142002-12-25 05:13:53 +00001211 unsigned SrcAddrReg = getReg(I.getOperand(0));
1212 unsigned DestReg = getReg(I);
Chris Lattnere8f0d922002-12-24 00:03:11 +00001213
Chris Lattner6fc3c522002-11-17 21:11:55 +00001214 unsigned Class = getClass(I.getType());
Chris Lattner94af4142002-12-25 05:13:53 +00001215 switch (Class) {
Chris Lattner94af4142002-12-25 05:13:53 +00001216 case cFP: {
Chris Lattner3e130a22003-01-13 00:32:26 +00001217 MachineBasicBlock::iterator MBBI = BB->end();
1218 addDirectMem(doFPLoad(BB, MBBI, I.getType(), DestReg), SrcAddrReg);
Chris Lattner94af4142002-12-25 05:13:53 +00001219 return;
1220 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001221 case cLong: case cInt: case cShort: case cByte:
1222 break; // Integers of various sizes handled below
1223 default: assert(0 && "Unknown memory class!");
Chris Lattner94af4142002-12-25 05:13:53 +00001224 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00001225
Chris Lattnere8f0d922002-12-24 00:03:11 +00001226 // We need to adjust the input pointer if we are emulating a big-endian
1227 // long-pointer target. On these systems, the pointer that we are interested
1228 // in is in the upper part of the eight byte memory image of the pointer. It
1229 // also happens to be byte-swapped, but this will be handled later.
1230 //
1231 if (!isLittleEndian && hasLongPointers && isa<PointerType>(I.getType())) {
1232 unsigned R = makeAnotherReg(Type::UIntTy);
1233 BuildMI(BB, X86::ADDri32, 2, R).addReg(SrcAddrReg).addZImm(4);
1234 SrcAddrReg = R;
1235 }
Chris Lattner94af4142002-12-25 05:13:53 +00001236
Chris Lattnere8f0d922002-12-24 00:03:11 +00001237 unsigned IReg = DestReg;
Chris Lattner3e130a22003-01-13 00:32:26 +00001238 if (!isLittleEndian) // If big endian we need an intermediate stage
1239 DestReg = makeAnotherReg(Class != cLong ? I.getType() : Type::UIntTy);
Chris Lattner94af4142002-12-25 05:13:53 +00001240
Chris Lattner3e130a22003-01-13 00:32:26 +00001241 static const unsigned Opcode[] = {
1242 X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, 0, X86::MOVmr32
1243 };
Chris Lattnere8f0d922002-12-24 00:03:11 +00001244 addDirectMem(BuildMI(BB, Opcode[Class], 4, DestReg), SrcAddrReg);
1245
Chris Lattner3e130a22003-01-13 00:32:26 +00001246 // Handle long values now...
1247 if (Class == cLong) {
1248 if (isLittleEndian) {
1249 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), SrcAddrReg, 4);
1250 } else {
1251 EmitByteSwap(IReg+1, DestReg, cInt);
1252 unsigned TempReg = makeAnotherReg(Type::IntTy);
1253 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TempReg), SrcAddrReg, 4);
1254 EmitByteSwap(IReg, TempReg, cInt);
Chris Lattner94af4142002-12-25 05:13:53 +00001255 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001256 return;
1257 }
1258
1259 if (!isLittleEndian)
1260 EmitByteSwap(IReg, DestReg, Class);
1261}
1262
1263
1264/// doFPStore - This method is used to store an FP value to memory using the
1265/// current endianness.
1266///
1267void ISel::doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg) {
1268 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1269 unsigned StoreOpcode = Ty == Type::FloatTy ? X86::FSTr32 : X86::FSTr64;
1270
1271 if (TM.getTargetData().isLittleEndian()) { // fast path...
1272 addDirectMem(BuildMI(BB, StoreOpcode,5), DestAddrReg).addReg(SrcReg);
1273 return;
1274 }
1275
1276 // Allocate a temporary stack slot to transform the value into...
1277 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1278 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1279 addFrameReference(BuildMI(BB, X86::LEAr32, 5, SrcAddrReg), FrameIdx);
1280
1281 // Store the value into a temporary stack slot...
1282 addDirectMem(BuildMI(BB, StoreOpcode, 5), SrcAddrReg).addReg(SrcReg);
1283
1284 // Perform the bswaps 32 bits at a time...
1285 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1286 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1287 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1288 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1289 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1290 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
1291 DestAddrReg, Offset).addReg(TmpReg2);
1292
1293 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1294 TmpReg1 = makeAnotherReg(Type::UIntTy);
1295 TmpReg2 = makeAnotherReg(Type::UIntTy);
1296
1297 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1298 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1299 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1300 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), DestAddrReg).addReg(TmpReg2);
Chris Lattnere8f0d922002-12-24 00:03:11 +00001301 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00001302}
1303
Chris Lattner06925362002-11-17 21:56:38 +00001304
Chris Lattner6fc3c522002-11-17 21:11:55 +00001305/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1306/// instruction.
1307///
1308void ISel::visitStoreInst(StoreInst &I) {
Chris Lattnere8f0d922002-12-24 00:03:11 +00001309 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1310 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
Chris Lattner3e130a22003-01-13 00:32:26 +00001311 unsigned ValReg = getReg(I.getOperand(0));
1312 unsigned AddressReg = getReg(I.getOperand(1));
Chris Lattnere8f0d922002-12-24 00:03:11 +00001313
Chris Lattner94af4142002-12-25 05:13:53 +00001314 unsigned Class = getClass(I.getOperand(0)->getType());
1315 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001316 case cLong:
1317 if (isLittleEndian) {
1318 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(ValReg);
1319 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4),
1320 AddressReg, 4).addReg(ValReg+1);
1321 } else {
1322 unsigned T1 = makeAnotherReg(Type::IntTy);
1323 unsigned T2 = makeAnotherReg(Type::IntTy);
1324 EmitByteSwap(T1, ValReg , cInt);
1325 EmitByteSwap(T2, ValReg+1, cInt);
1326 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(T2);
1327 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg, 4).addReg(T1);
1328 }
Chris Lattner94af4142002-12-25 05:13:53 +00001329 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00001330 case cFP:
1331 doFPStore(I.getOperand(0)->getType(), AddressReg, ValReg);
1332 return;
1333 case cInt: case cShort: case cByte:
1334 break; // Integers of various sizes handled below
1335 default: assert(0 && "Unknown memory class!");
Chris Lattner94af4142002-12-25 05:13:53 +00001336 }
1337
1338 if (!isLittleEndian && hasLongPointers &&
1339 isa<PointerType>(I.getOperand(0)->getType())) {
Chris Lattnere8f0d922002-12-24 00:03:11 +00001340 unsigned R = makeAnotherReg(Type::UIntTy);
1341 BuildMI(BB, X86::ADDri32, 2, R).addReg(AddressReg).addZImm(4);
1342 AddressReg = R;
1343 }
1344
Chris Lattner94af4142002-12-25 05:13:53 +00001345 if (!isLittleEndian && Class != cByte) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001346 unsigned R = makeAnotherReg(I.getOperand(0)->getType());
1347 EmitByteSwap(R, ValReg, Class);
1348 ValReg = R;
Chris Lattnere8f0d922002-12-24 00:03:11 +00001349 }
1350
Chris Lattner94af4142002-12-25 05:13:53 +00001351 static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
Chris Lattner6fc3c522002-11-17 21:11:55 +00001352 addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
1353}
1354
1355
Brian Gaekec11232a2002-11-26 10:43:30 +00001356/// visitCastInst - Here we have various kinds of copying with or without
1357/// sign extension going on.
Chris Lattner3e130a22003-01-13 00:32:26 +00001358void ISel::visitCastInst(CastInst &CI) {
1359 const Type *DestTy = CI.getType();
1360 Value *Src = CI.getOperand(0);
1361 unsigned SrcReg = getReg(Src);
1362 const Type *SrcTy = Src->getType();
1363 unsigned SrcClass = getClassB(SrcTy);
1364 unsigned DestReg = getReg(CI);
1365 unsigned DestClass = getClassB(DestTy);
Chris Lattner7d255892002-12-13 11:31:59 +00001366
Chris Lattner3e130a22003-01-13 00:32:26 +00001367 // Implement casts to bool by using compare on the operand followed by set if
1368 // not zero on the result.
1369 if (DestTy == Type::BoolTy) {
1370 if (SrcClass == cFP || SrcClass == cLong)
1371 visitInstruction(CI);
1372
1373 BuildMI(BB, X86::CMPri8, 2).addReg(SrcReg).addZImm(0);
1374 BuildMI(BB, X86::SETNEr, 1, DestReg);
Chris Lattner94af4142002-12-25 05:13:53 +00001375 return;
1376 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001377
1378 static const unsigned RegRegMove[] = {
1379 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
1380 };
1381
1382 // Implement casts between values of the same type class (as determined by
1383 // getClass) by using a register-to-register move.
1384 if (SrcClass == DestClass) {
1385 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
1386 BuildMI(BB, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
1387 } else if (SrcClass == cFP) {
1388 if (SrcTy == Type::FloatTy) { // double -> float
1389 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
1390 BuildMI(BB, X86::FpMOV, 1, DestReg).addReg(SrcReg);
1391 } else { // float -> double
1392 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
1393 "Unknown cFP member!");
1394 // Truncate from double to float by storing to memory as short, then
1395 // reading it back.
1396 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
1397 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
1398 addFrameReference(BuildMI(BB, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
1399 addFrameReference(BuildMI(BB, X86::FLDr32, 5, DestReg), FrameIdx);
1400 }
1401 } else if (SrcClass == cLong) {
1402 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1403 BuildMI(BB, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
1404 } else {
1405 visitInstruction(CI);
Brian Gaeked474e9c2002-12-06 10:49:33 +00001406 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001407 return;
1408 }
1409
1410 // Handle cast of SMALLER int to LARGER int using a move with sign extension
1411 // or zero extension, depending on whether the source type was signed.
1412 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
1413 SrcClass < DestClass) {
1414 bool isLong = DestClass == cLong;
1415 if (isLong) DestClass = cInt;
1416
1417 static const unsigned Opc[][4] = {
1418 { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
1419 { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 } // u
1420 };
1421
1422 bool isUnsigned = SrcTy->isUnsigned();
1423 BuildMI(BB, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
1424 DestReg).addReg(SrcReg);
1425
1426 if (isLong) { // Handle upper 32 bits as appropriate...
1427 if (isUnsigned) // Zero out top bits...
1428 BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1429 else // Sign extend bottom half...
1430 BuildMI(BB, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
Brian Gaeked474e9c2002-12-06 10:49:33 +00001431 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001432 return;
1433 }
1434
1435 // Special case long -> int ...
1436 if (SrcClass == cLong && DestClass == cInt) {
1437 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1438 return;
1439 }
1440
1441 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
1442 // move out of AX or AL.
1443 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
1444 && SrcClass > DestClass) {
1445 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
1446 BuildMI(BB, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
1447 BuildMI(BB, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
1448 return;
1449 }
1450
1451 // Handle casts from integer to floating point now...
1452 if (DestClass == cFP) {
1453 // unsigned int -> load as 64 bit int.
1454 // unsigned long long -> more complex
1455 if (SrcTy->isUnsigned() && SrcTy != Type::UByteTy)
1456 visitInstruction(CI); // don't handle unsigned src yet!
1457
1458 // We don't have the facilities for directly loading byte sized data from
1459 // memory. Promote it to 16 bits.
1460 if (SrcClass == cByte) {
1461 unsigned TmpReg = makeAnotherReg(Type::ShortTy);
1462 BuildMI(BB, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
1463 1, TmpReg).addReg(SrcReg);
1464 SrcTy = Type::ShortTy; // Pretend the short is our input now!
1465 SrcClass = cShort;
1466 SrcReg = TmpReg;
1467 }
1468
1469 // Spill the integer to memory and reload it from there...
1470 int FrameIdx =
1471 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
1472
1473 if (SrcClass == cLong) {
1474 if (SrcTy == Type::ULongTy) visitInstruction(CI);
1475 addFrameReference(BuildMI(BB, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
1476 addFrameReference(BuildMI(BB, X86::MOVrm32, 5),
1477 FrameIdx, 4).addReg(SrcReg+1);
1478 } else {
1479 static const unsigned Op1[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1480 addFrameReference(BuildMI(BB, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
1481 }
1482
1483 static const unsigned Op2[] =
1484 { 0, X86::FILDr16, X86::FILDr32, 0, X86::FILDr64 };
1485 addFrameReference(BuildMI(BB, Op2[SrcClass], 5, DestReg), FrameIdx);
1486 return;
1487 }
1488
1489 // Handle casts from floating point to integer now...
1490 if (SrcClass == cFP) {
1491 // Change the floating point control register to use "round towards zero"
1492 // mode when truncating to an integer value.
1493 //
1494 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
1495 addFrameReference(BuildMI(BB, X86::FNSTCWm16, 4), CWFrameIdx);
1496
1497 // Load the old value of the high byte of the control word...
1498 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
1499 addFrameReference(BuildMI(BB, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
1500
1501 // Set the high part to be round to zero...
1502 addFrameReference(BuildMI(BB, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
1503
1504 // Reload the modified control word now...
1505 addFrameReference(BuildMI(BB, X86::FLDCWm16, 4), CWFrameIdx);
1506
1507 // Restore the memory image of control word to original value
1508 addFrameReference(BuildMI(BB, X86::MOVrm8, 5),
1509 CWFrameIdx, 1).addReg(HighPartOfCW);
1510
1511 // We don't have the facilities for directly storing byte sized data to
1512 // memory. Promote it to 16 bits. We also must promote unsigned values to
1513 // larger classes because we only have signed FP stores.
1514 unsigned StoreClass = DestClass;
1515 const Type *StoreTy = DestTy;
1516 if (StoreClass == cByte || DestTy->isUnsigned())
1517 switch (StoreClass) {
1518 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
1519 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
1520 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
1521 case cLong: visitInstruction(CI); // unsigned long long -> more complex
1522 default: assert(0 && "Unknown store class!");
1523 }
1524
1525 // Spill the integer to memory and reload it from there...
1526 int FrameIdx =
1527 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
1528
1529 static const unsigned Op1[] =
1530 { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
1531 addFrameReference(BuildMI(BB, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
1532
1533 if (DestClass == cLong) {
1534 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, DestReg), FrameIdx);
1535 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
1536 } else {
1537 static const unsigned Op2[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
1538 addFrameReference(BuildMI(BB, Op2[DestClass], 4, DestReg), FrameIdx);
1539 }
1540
1541 // Reload the original control word now...
1542 addFrameReference(BuildMI(BB, X86::FLDCWm16, 4), CWFrameIdx);
1543 return;
1544 }
1545
Brian Gaeked474e9c2002-12-06 10:49:33 +00001546 // Anything we haven't handled already, we can't (yet) handle at all.
Brian Gaekefa8d5712002-11-22 11:07:01 +00001547 visitInstruction (CI);
1548}
Brian Gaekea1719c92002-10-31 23:03:59 +00001549
Chris Lattner8a307e82002-12-16 19:32:50 +00001550// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1551// returns zero when the input is not exactly a power of two.
1552static unsigned ExactLog2(unsigned Val) {
1553 if (Val == 0) return 0;
1554 unsigned Count = 0;
1555 while (Val != 1) {
1556 if (Val & 1) return 0;
1557 Val >>= 1;
1558 ++Count;
1559 }
1560 return Count+1;
1561}
1562
Chris Lattner3e130a22003-01-13 00:32:26 +00001563void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
1564 unsigned outputReg = getReg(I);
Chris Lattnerf08ad9f2002-12-13 10:50:40 +00001565 MachineBasicBlock::iterator MI = BB->end();
1566 emitGEPOperation(BB, MI, I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +00001567 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +00001568}
1569
Brian Gaeke71794c02002-12-13 11:22:48 +00001570void ISel::emitGEPOperation(MachineBasicBlock *MBB,
Chris Lattnerf08ad9f2002-12-13 10:50:40 +00001571 MachineBasicBlock::iterator &IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +00001572 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +00001573 User::op_iterator IdxEnd, unsigned TargetReg) {
1574 const TargetData &TD = TM.getTargetData();
1575 const Type *Ty = Src->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +00001576 unsigned BaseReg = getReg(Src, MBB, IP);
Chris Lattnerc0812d82002-12-13 06:56:29 +00001577
Brian Gaeke20244b72002-12-12 15:33:40 +00001578 // GEPs have zero or more indices; we must perform a struct access
1579 // or array access for each one.
Chris Lattnerc0812d82002-12-13 06:56:29 +00001580 for (GetElementPtrInst::op_iterator oi = IdxBegin,
1581 oe = IdxEnd; oi != oe; ++oi) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001582 Value *idx = *oi;
Chris Lattner3e130a22003-01-13 00:32:26 +00001583 unsigned NextReg = BaseReg;
Chris Lattner065faeb2002-12-28 20:24:02 +00001584 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001585 // It's a struct access. idx is the index into the structure,
1586 // which names the field. This index must have ubyte type.
Chris Lattner065faeb2002-12-28 20:24:02 +00001587 const ConstantUInt *CUI = cast<ConstantUInt>(idx);
1588 assert(CUI->getType() == Type::UByteTy
Brian Gaeke20244b72002-12-12 15:33:40 +00001589 && "Funny-looking structure index in GEP");
1590 // Use the TargetData structure to pick out what the layout of
1591 // the structure is in memory. Since the structure index must
1592 // be constant, we can get its value and use it to find the
1593 // right byte offset from the StructLayout class's list of
1594 // structure member offsets.
Chris Lattnere8f0d922002-12-24 00:03:11 +00001595 unsigned idxValue = CUI->getValue();
Chris Lattner3e130a22003-01-13 00:32:26 +00001596 unsigned FieldOff = TD.getStructLayout(StTy)->MemberOffsets[idxValue];
1597 if (FieldOff) {
1598 NextReg = makeAnotherReg(Type::UIntTy);
1599 // Emit an ADD to add FieldOff to the basePtr.
1600 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(FieldOff);
1601 }
Brian Gaeke20244b72002-12-12 15:33:40 +00001602 // The next type is the member of the structure selected by the
1603 // index.
Chris Lattner065faeb2002-12-28 20:24:02 +00001604 Ty = StTy->getElementTypes()[idxValue];
1605 } else if (const SequentialType *SqTy = cast<SequentialType>(Ty)) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001606 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner8a307e82002-12-16 19:32:50 +00001607
Brian Gaeke20244b72002-12-12 15:33:40 +00001608 // idx is the index into the array. Unlike with structure
1609 // indices, we may not know its actual value at code-generation
1610 // time.
Chris Lattner8a307e82002-12-16 19:32:50 +00001611 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1612
Chris Lattner3e130a22003-01-13 00:32:26 +00001613 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
Chris Lattner8a307e82002-12-16 19:32:50 +00001614 // must find the size of the pointed-to type (Not coincidentally, the next
1615 // type is the type of the elements in the array).
1616 Ty = SqTy->getElementType();
1617 unsigned elementSize = TD.getTypeSize(Ty);
1618
1619 // If idxReg is a constant, we don't need to perform the multiply!
1620 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001621 if (!CSI->isNullValue()) {
Chris Lattner8a307e82002-12-16 19:32:50 +00001622 unsigned Offset = elementSize*CSI->getValue();
Chris Lattner3e130a22003-01-13 00:32:26 +00001623 NextReg = makeAnotherReg(Type::UIntTy);
1624 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(Offset);
Chris Lattner8a307e82002-12-16 19:32:50 +00001625 }
1626 } else if (elementSize == 1) {
1627 // If the element size is 1, we don't have to multiply, just add
1628 unsigned idxReg = getReg(idx, MBB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001629 NextReg = makeAnotherReg(Type::UIntTy);
1630 BMI(MBB, IP, X86::ADDrr32, 2, NextReg).addReg(BaseReg).addReg(idxReg);
Chris Lattner8a307e82002-12-16 19:32:50 +00001631 } else {
1632 unsigned idxReg = getReg(idx, MBB, IP);
1633 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1634 if (unsigned Shift = ExactLog2(elementSize)) {
1635 // If the element size is exactly a power of 2, use a shift to get it.
Chris Lattner8a307e82002-12-16 19:32:50 +00001636 BMI(MBB, IP, X86::SHLir32, 2,
1637 OffsetReg).addReg(idxReg).addZImm(Shift-1);
1638 } else {
1639 // Most general case, emit a multiply...
1640 unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1641 BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1642
1643 // Emit a MUL to multiply the register holding the index by
1644 // elementSize, putting the result in OffsetReg.
Chris Lattner3e130a22003-01-13 00:32:26 +00001645 doMultiply(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSizeReg);
Chris Lattner8a307e82002-12-16 19:32:50 +00001646 }
1647 // Emit an ADD to add OffsetReg to the basePtr.
Chris Lattner3e130a22003-01-13 00:32:26 +00001648 NextReg = makeAnotherReg(Type::UIntTy);
1649 BMI(MBB, IP, X86::ADDrr32, 2,NextReg).addReg(BaseReg).addReg(OffsetReg);
Chris Lattner8a307e82002-12-16 19:32:50 +00001650 }
Brian Gaeke20244b72002-12-12 15:33:40 +00001651 }
1652 // Now that we are here, further indices refer to subtypes of this
Chris Lattner3e130a22003-01-13 00:32:26 +00001653 // one, so we don't need to worry about BaseReg itself, anymore.
1654 BaseReg = NextReg;
Brian Gaeke20244b72002-12-12 15:33:40 +00001655 }
1656 // After we have processed all the indices, the result is left in
Chris Lattner3e130a22003-01-13 00:32:26 +00001657 // BaseReg. Move it to the register where we were expected to
Brian Gaeke20244b72002-12-12 15:33:40 +00001658 // put the answer. A 32-bit move should do it, because we are in
1659 // ILP32 land.
Chris Lattner3e130a22003-01-13 00:32:26 +00001660 BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001661}
1662
1663
Chris Lattner065faeb2002-12-28 20:24:02 +00001664/// visitAllocaInst - If this is a fixed size alloca, allocate space from the
1665/// frame manager, otherwise do it the hard way.
1666///
1667void ISel::visitAllocaInst(AllocaInst &I) {
Brian Gaekee48ec012002-12-13 06:46:31 +00001668 // Find the data size of the alloca inst's getAllocatedType.
Chris Lattner065faeb2002-12-28 20:24:02 +00001669 const Type *Ty = I.getAllocatedType();
1670 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1671
1672 // If this is a fixed size alloca in the entry block for the function,
1673 // statically stack allocate the space.
1674 //
1675 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
1676 if (I.getParent() == I.getParent()->getParent()->begin()) {
1677 TySize *= CUI->getValue(); // Get total allocated size...
1678 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
1679
1680 // Create a new stack object using the frame manager...
1681 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
1682 addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
1683 return;
1684 }
1685 }
1686
1687 // Create a register to hold the temporary result of multiplying the type size
1688 // constant by the variable amount.
1689 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
1690 unsigned SrcReg1 = getReg(I.getArraySize());
1691 unsigned SizeReg = makeAnotherReg(Type::UIntTy);
1692 BuildMI(BB, X86::MOVir32, 1, SizeReg).addZImm(TySize);
1693
1694 // TotalSizeReg = mul <numelements>, <TypeSize>
1695 MachineBasicBlock::iterator MBBI = BB->end();
1696 doMultiply(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, SizeReg);
1697
1698 // AddedSize = add <TotalSizeReg>, 15
1699 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
1700 BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
1701
1702 // AlignedSize = and <AddedSize>, ~15
1703 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
1704 BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
1705
Brian Gaekee48ec012002-12-13 06:46:31 +00001706 // Subtract size from stack pointer, thereby allocating some space.
Chris Lattner3e130a22003-01-13 00:32:26 +00001707 BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
Chris Lattner065faeb2002-12-28 20:24:02 +00001708
Brian Gaekee48ec012002-12-13 06:46:31 +00001709 // Put a pointer to the space into the result register, by copying
1710 // the stack pointer.
Chris Lattner065faeb2002-12-28 20:24:02 +00001711 BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
1712
1713 // Inform the Frame Information that we have just allocated a variable sized
1714 // object.
1715 F->getFrameInfo()->CreateVariableSizedObject();
Brian Gaeke20244b72002-12-12 15:33:40 +00001716}
Chris Lattner3e130a22003-01-13 00:32:26 +00001717
1718/// visitMallocInst - Malloc instructions are code generated into direct calls
1719/// to the library malloc.
1720///
1721void ISel::visitMallocInst(MallocInst &I) {
1722 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
1723 unsigned Arg;
1724
1725 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
1726 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
1727 } else {
1728 Arg = makeAnotherReg(Type::UIntTy);
1729 unsigned Op0Reg = getReg(ConstantUInt::get(Type::UIntTy, AllocSize));
1730 unsigned Op1Reg = getReg(I.getOperand(0));
1731 MachineBasicBlock::iterator MBBI = BB->end();
1732 doMultiply(BB, MBBI, Arg, Type::UIntTy, Op0Reg, Op1Reg);
1733
1734
1735 }
1736
1737 std::vector<ValueRecord> Args;
1738 Args.push_back(ValueRecord(Arg, Type::UIntTy));
1739 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1740 1).addExternalSymbol("malloc", true);
1741 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
1742}
1743
1744
1745/// visitFreeInst - Free instructions are code gen'd to call the free libc
1746/// function.
1747///
1748void ISel::visitFreeInst(FreeInst &I) {
1749 std::vector<ValueRecord> Args;
1750 Args.push_back(ValueRecord(getReg(I.getOperand(0)),
1751 I.getOperand(0)->getType()));
1752 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1753 1).addExternalSymbol("free", true);
1754 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
1755}
1756
Brian Gaeke20244b72002-12-12 15:33:40 +00001757
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00001758/// createSimpleX86InstructionSelector - This pass converts an LLVM function
1759/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00001760/// generated code sucks but the implementation is nice and simple.
1761///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00001762Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1763 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00001764}