blob: 369b203e61462f9ded65991c6dba81810a1b87f2 [file] [log] [blame]
Chris Lattner72614082002-10-25 22:55:53 +00001//===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner72614082002-10-25 22:55:53 +00009//
Chris Lattner3e130a22003-01-13 00:32:26 +000010// This file defines a simple peephole instruction selector for the x86 target
Chris Lattner72614082002-10-25 22:55:53 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "X86.h"
Chris Lattner6fc3c522002-11-17 21:11:55 +000015#include "X86InstrBuilder.h"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000016#include "X86InstrInfo.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
Chris Lattner72614082002-10-25 22:55:53 +000019#include "llvm/Function.h"
Chris Lattner67580ed2003-05-13 20:21:19 +000020#include "llvm/Instructions.h"
Chris Lattner44827152003-12-28 09:47:19 +000021#include "llvm/IntrinsicLowering.h"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000022#include "llvm/Pass.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner341a9372002-10-29 17:43:55 +000025#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner94af4142002-12-25 05:13:53 +000026#include "llvm/CodeGen/SSARegMap.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000027#include "llvm/Target/MRegisterInfo.h"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000028#include "llvm/Target/TargetMachine.h"
Chris Lattner3f1e8e72004-02-22 07:04:00 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner67580ed2003-05-13 20:21:19 +000030#include "llvm/Support/InstVisitor.h"
Chris Lattnercf93cdd2004-01-30 22:13:44 +000031#include "llvm/Support/CFG.h"
Chris Lattner986618e2004-02-22 19:47:26 +000032#include "Support/Statistic.h"
Chris Lattner44827152003-12-28 09:47:19 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Chris Lattner986618e2004-02-22 19:47:26 +000035namespace {
36 Statistic<>
37 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
38}
Chris Lattnercf93cdd2004-01-30 22:13:44 +000039
Chris Lattner72614082002-10-25 22:55:53 +000040namespace {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000041 struct ISel : public FunctionPass, InstVisitor<ISel> {
42 TargetMachine &TM;
Chris Lattnereca195e2003-05-08 19:44:13 +000043 MachineFunction *F; // The function we are compiling into
44 MachineBasicBlock *BB; // The current MBB we are compiling
45 int VarArgsFrameIndex; // FrameIndex for start of varargs area
Chris Lattner0e5b79c2004-02-15 01:04:03 +000046 int ReturnAddressIndex; // FrameIndex for the return address
Chris Lattner72614082002-10-25 22:55:53 +000047
Chris Lattner72614082002-10-25 22:55:53 +000048 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
49
Chris Lattner333b2fa2002-12-13 10:09:43 +000050 // MBBMap - Mapping between LLVM BB -> Machine BB
51 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
52
Chris Lattnerf70e0c22003-12-28 21:23:38 +000053 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
Chris Lattner72614082002-10-25 22:55:53 +000054
55 /// runOnFunction - Top level implementation of instruction selection for
56 /// the entire function.
57 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000058 bool runOnFunction(Function &Fn) {
Chris Lattner44827152003-12-28 09:47:19 +000059 // First pass over the function, lower any unknown intrinsic functions
60 // with the IntrinsicLowering class.
61 LowerUnknownIntrinsicFunctionCalls(Fn);
62
Chris Lattner36b36032002-10-29 23:40:58 +000063 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +000064
Chris Lattner065faeb2002-12-28 20:24:02 +000065 // Create all of the machine basic blocks for the function...
Chris Lattner333b2fa2002-12-13 10:09:43 +000066 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
67 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
68
Chris Lattner14aa7fe2002-12-16 22:54:46 +000069 BB = &F->front();
Chris Lattnerdbd73722003-05-06 21:32:22 +000070
Chris Lattner0e5b79c2004-02-15 01:04:03 +000071 // Set up a frame object for the return address. This is used by the
72 // llvm.returnaddress & llvm.frameaddress intrinisics.
73 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
74
Chris Lattnerdbd73722003-05-06 21:32:22 +000075 // Copy incoming arguments off of the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +000076 LoadArgumentsToVirtualRegs(Fn);
Chris Lattner14aa7fe2002-12-16 22:54:46 +000077
Chris Lattner333b2fa2002-12-13 10:09:43 +000078 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000079 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +000080
81 // Select the PHI nodes
82 SelectPHINodes();
83
Chris Lattner986618e2004-02-22 19:47:26 +000084 // Insert the FP_REG_KILL instructions into blocks that need them.
85 InsertFPRegKills();
86
Chris Lattner72614082002-10-25 22:55:53 +000087 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +000088 MBBMap.clear();
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000089 F = 0;
Chris Lattner2a865b02003-07-26 23:05:37 +000090 // We always build a machine code representation for the function
91 return true;
Chris Lattner72614082002-10-25 22:55:53 +000092 }
93
Chris Lattnerf0eb7be2002-12-15 21:13:40 +000094 virtual const char *getPassName() const {
95 return "X86 Simple Instruction Selection";
96 }
97
Chris Lattner72614082002-10-25 22:55:53 +000098 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +000099 /// block. This simply creates a new MachineBasicBlock to emit code into
100 /// and adds it to the current MachineFunction. Subsequent visit* for
101 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +0000102 ///
103 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000104 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +0000105 }
106
Chris Lattner44827152003-12-28 09:47:19 +0000107 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
108 /// function, lowering any calls to unknown intrinsic functions into the
109 /// equivalent LLVM code.
110 void LowerUnknownIntrinsicFunctionCalls(Function &F);
111
Chris Lattner065faeb2002-12-28 20:24:02 +0000112 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
113 /// from the stack into virtual registers.
114 ///
115 void LoadArgumentsToVirtualRegs(Function &F);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000116
117 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
118 /// because we have to generate our sources into the source basic blocks,
119 /// not the current one.
120 ///
121 void SelectPHINodes();
122
Chris Lattner986618e2004-02-22 19:47:26 +0000123 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
124 /// that need them. This only occurs due to the floating point stackifier
125 /// not being aggressive enough to handle arbitrary global stackification.
126 ///
127 void InsertFPRegKills();
128
Chris Lattner72614082002-10-25 22:55:53 +0000129 // Visitation methods for various instructions. These methods simply emit
130 // fixed X86 code for each instruction.
131 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000132
133 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000134 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000135 void visitBranchInst(BranchInst &BI);
Chris Lattner3e130a22003-01-13 00:32:26 +0000136
137 struct ValueRecord {
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000138 Value *Val;
Chris Lattner3e130a22003-01-13 00:32:26 +0000139 unsigned Reg;
140 const Type *Ty;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000141 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
142 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
Chris Lattner3e130a22003-01-13 00:32:26 +0000143 };
144 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000145 const std::vector<ValueRecord> &Args);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000146 void visitCallInst(CallInst &I);
Brian Gaeked0fde302003-11-11 22:41:34 +0000147 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000148
149 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000150 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000151 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
152 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000153 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +0000154 unsigned DestReg, const Type *DestTy,
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000155 unsigned Op0Reg, unsigned Op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000156 void doMultiplyConst(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000157 MachineBasicBlock::iterator MBBI,
Chris Lattnerb2acc512003-10-19 21:09:10 +0000158 unsigned DestReg, const Type *DestTy,
159 unsigned Op0Reg, unsigned Op1Val);
Chris Lattnerca9671d2002-11-02 20:28:58 +0000160 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000161
Chris Lattnerf01729e2002-11-02 20:54:46 +0000162 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
163 void visitRem(BinaryOperator &B) { visitDivRem(B); }
164 void visitDivRem(BinaryOperator &B);
165
Chris Lattnere2954c82002-11-02 20:04:26 +0000166 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000167 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
168 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
169 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000170
Chris Lattner6d40c192003-01-16 16:43:00 +0000171 // Comparison operators...
172 void visitSetCondInst(SetCondInst &I);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000173 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
174 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000175 MachineBasicBlock::iterator MBBI);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000176
Chris Lattner6fc3c522002-11-17 21:11:55 +0000177 // Memory Instructions
178 void visitLoadInst(LoadInst &I);
179 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000180 void visitGetElementPtrInst(GetElementPtrInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000181 void visitAllocaInst(AllocaInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000182 void visitMallocInst(MallocInst &I);
183 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000184
Chris Lattnere2954c82002-11-02 20:04:26 +0000185 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000186 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000187 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000188 void visitCastInst(CastInst &I);
Chris Lattner73815062003-10-18 05:56:40 +0000189 void visitVANextInst(VANextInst &I);
190 void visitVAArgInst(VAArgInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000191
192 void visitInstruction(Instruction &I) {
193 std::cerr << "Cannot instruction select: " << I;
194 abort();
195 }
196
Brian Gaeke95780cc2002-12-13 07:56:18 +0000197 /// promote32 - Make a value 32-bits wide, and put it somewhere.
Chris Lattner3e130a22003-01-13 00:32:26 +0000198 ///
199 void promote32(unsigned targetReg, const ValueRecord &VR);
200
Chris Lattnerb6bac512004-02-25 06:13:04 +0000201 // getGEPIndex - This is used to fold GEP instructions into X86 addressing
202 // expressions.
203 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
204 std::vector<Value*> &GEPOps,
205 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
206 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
207
208 /// isGEPFoldable - Return true if the specified GEP can be completely
209 /// folded into the addressing mode of a load/store or lea instruction.
210 bool isGEPFoldable(MachineBasicBlock *MBB,
211 Value *Src, User::op_iterator IdxBegin,
212 User::op_iterator IdxEnd, unsigned &BaseReg,
213 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
214
Chris Lattner3e130a22003-01-13 00:32:26 +0000215 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
216 /// constant expression GEP support.
217 ///
Chris Lattner827832c2004-02-22 17:05:38 +0000218 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000219 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000220 User::op_iterator IdxEnd, unsigned TargetReg);
221
Chris Lattner548f61d2003-04-23 17:22:12 +0000222 /// emitCastOperation - Common code shared between visitCastInst and
223 /// constant expression cast support.
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000224 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +0000225 Value *Src, const Type *DestTy, unsigned TargetReg);
226
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000227 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
228 /// and constant expression support.
229 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000230 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000231 Value *Op0, Value *Op1,
232 unsigned OperatorClass, unsigned TargetReg);
233
Chris Lattnercadff442003-10-23 17:21:43 +0000234 void emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000235 MachineBasicBlock::iterator IP,
Chris Lattnercadff442003-10-23 17:21:43 +0000236 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
237 const Type *Ty, unsigned TargetReg);
238
Chris Lattner58c41fe2003-08-24 19:19:47 +0000239 /// emitSetCCOperation - Common code shared between visitSetCondInst and
240 /// constant expression support.
241 void emitSetCCOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000242 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +0000243 Value *Op0, Value *Op1, unsigned Opcode,
244 unsigned TargetReg);
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000245
246 /// emitShiftOperation - Common code shared between visitShiftInst and
247 /// constant expression support.
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000248 void emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000249 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000250 Value *Op, Value *ShiftAmount, bool isLeftShift,
251 const Type *ResultTy, unsigned DestReg);
252
Chris Lattner58c41fe2003-08-24 19:19:47 +0000253
Chris Lattnerc5291f52002-10-27 21:16:59 +0000254 /// copyConstantToRegister - Output the instructions required to put the
255 /// specified constant into the specified register.
256 ///
Chris Lattner8a307e82002-12-16 19:32:50 +0000257 void copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000258 MachineBasicBlock::iterator MBBI,
Chris Lattner8a307e82002-12-16 19:32:50 +0000259 Constant *C, unsigned Reg);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000260
Chris Lattner3e130a22003-01-13 00:32:26 +0000261 /// makeAnotherReg - This method returns the next register number we haven't
262 /// yet used.
263 ///
264 /// Long values are handled somewhat specially. They are always allocated
265 /// as pairs of 32 bit integer values. The register number returned is the
266 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
267 /// of the long value.
268 ///
Chris Lattnerc0812d82002-12-13 06:56:29 +0000269 unsigned makeAnotherReg(const Type *Ty) {
Chris Lattner7db1fa92003-07-30 05:33:48 +0000270 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
271 "Current target doesn't have X86 reg info??");
272 const X86RegisterInfo *MRI =
273 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
Chris Lattner3e130a22003-01-13 00:32:26 +0000274 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000275 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
276 // Create the lower part
277 F->getSSARegMap()->createVirtualRegister(RC);
278 // Create the upper part.
279 return F->getSSARegMap()->createVirtualRegister(RC)-1;
Chris Lattner3e130a22003-01-13 00:32:26 +0000280 }
281
Chris Lattnerc0812d82002-12-13 06:56:29 +0000282 // Add the mapping of regnumber => reg class to MachineFunction
Chris Lattner7db1fa92003-07-30 05:33:48 +0000283 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
Chris Lattner3e130a22003-01-13 00:32:26 +0000284 return F->getSSARegMap()->createVirtualRegister(RC);
Brian Gaeke20244b72002-12-12 15:33:40 +0000285 }
286
Chris Lattner72614082002-10-25 22:55:53 +0000287 /// getReg - This method turns an LLVM value into a register number. This
288 /// is guaranteed to produce the same register number for a particular value
289 /// every time it is queried.
290 ///
291 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000292 unsigned getReg(Value *V) {
293 // Just append to the end of the current bb.
294 MachineBasicBlock::iterator It = BB->end();
295 return getReg(V, BB, It);
296 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000297 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000298 MachineBasicBlock::iterator IPt) {
Chris Lattner72614082002-10-25 22:55:53 +0000299 unsigned &Reg = RegMap[V];
Misha Brukmand2cc0172002-11-20 00:58:23 +0000300 if (Reg == 0) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000301 Reg = makeAnotherReg(V->getType());
Misha Brukmand2cc0172002-11-20 00:58:23 +0000302 RegMap[V] = Reg;
Misha Brukmand2cc0172002-11-20 00:58:23 +0000303 }
Chris Lattner72614082002-10-25 22:55:53 +0000304
Chris Lattner6f8fd252002-10-27 21:23:43 +0000305 // If this operand is a constant, emit the code to copy the constant into
306 // the register here...
307 //
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000308 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner8a307e82002-12-16 19:32:50 +0000309 copyConstantToRegister(MBB, IPt, C, Reg);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000310 RegMap.erase(V); // Assign a new name to this constant if ref'd again
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000311 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
312 // Move the address of the global into the register
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000313 BuildMI(*MBB, IPt, X86::MOV32ri, 1, Reg).addGlobalAddress(GV);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000314 RegMap.erase(V); // Assign a new name to this address if ref'd again
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000315 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000316
Chris Lattner72614082002-10-25 22:55:53 +0000317 return Reg;
318 }
Chris Lattner72614082002-10-25 22:55:53 +0000319 };
320}
321
Chris Lattner43189d12002-11-17 20:07:45 +0000322/// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
323/// Representation.
324///
325enum TypeClass {
Chris Lattner94af4142002-12-25 05:13:53 +0000326 cByte, cShort, cInt, cFP, cLong
Chris Lattner43189d12002-11-17 20:07:45 +0000327};
328
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000329/// getClass - Turn a primitive type into a "class" number which is based on the
330/// size of the type, and whether or not it is floating point.
331///
Chris Lattner43189d12002-11-17 20:07:45 +0000332static inline TypeClass getClass(const Type *Ty) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000333 switch (Ty->getPrimitiveID()) {
334 case Type::SByteTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000335 case Type::UByteTyID: return cByte; // Byte operands are class #0
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000336 case Type::ShortTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000337 case Type::UShortTyID: return cShort; // Short operands are class #1
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000338 case Type::IntTyID:
339 case Type::UIntTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000340 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000341
Chris Lattner94af4142002-12-25 05:13:53 +0000342 case Type::FloatTyID:
343 case Type::DoubleTyID: return cFP; // Floating Point is #3
Chris Lattner3e130a22003-01-13 00:32:26 +0000344
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000345 case Type::LongTyID:
Chris Lattner3e130a22003-01-13 00:32:26 +0000346 case Type::ULongTyID: return cLong; // Longs are class #4
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000347 default:
348 assert(0 && "Invalid type to getClass!");
Chris Lattner43189d12002-11-17 20:07:45 +0000349 return cByte; // not reached
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000350 }
351}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000352
Chris Lattner6b993cc2002-12-15 08:02:15 +0000353// getClassB - Just like getClass, but treat boolean values as bytes.
354static inline TypeClass getClassB(const Type *Ty) {
355 if (Ty == Type::BoolTy) return cByte;
356 return getClass(Ty);
357}
358
Chris Lattner06925362002-11-17 21:56:38 +0000359
Chris Lattnerc5291f52002-10-27 21:16:59 +0000360/// copyConstantToRegister - Output the instructions required to put the
361/// specified constant into the specified register.
362///
Chris Lattner8a307e82002-12-16 19:32:50 +0000363void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000364 MachineBasicBlock::iterator IP,
Chris Lattner8a307e82002-12-16 19:32:50 +0000365 Constant *C, unsigned R) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000366 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000367 unsigned Class = 0;
368 switch (CE->getOpcode()) {
369 case Instruction::GetElementPtr:
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000370 emitGEPOperation(MBB, IP, CE->getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000371 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000372 return;
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000373 case Instruction::Cast:
Chris Lattner548f61d2003-04-23 17:22:12 +0000374 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
Chris Lattner4b12cde2003-04-21 21:33:44 +0000375 return;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000376
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000377 case Instruction::Xor: ++Class; // FALL THROUGH
378 case Instruction::Or: ++Class; // FALL THROUGH
379 case Instruction::And: ++Class; // FALL THROUGH
380 case Instruction::Sub: ++Class; // FALL THROUGH
381 case Instruction::Add:
382 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
383 Class, R);
384 return;
385
Chris Lattnercadff442003-10-23 17:21:43 +0000386 case Instruction::Mul: {
387 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
388 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
389 doMultiply(MBB, IP, R, CE->getType(), Op0Reg, Op1Reg);
390 return;
391 }
392 case Instruction::Div:
393 case Instruction::Rem: {
394 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
395 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
396 emitDivRemOperation(MBB, IP, Op0Reg, Op1Reg,
397 CE->getOpcode() == Instruction::Div,
398 CE->getType(), R);
399 return;
400 }
401
Chris Lattner58c41fe2003-08-24 19:19:47 +0000402 case Instruction::SetNE:
403 case Instruction::SetEQ:
404 case Instruction::SetLT:
405 case Instruction::SetGT:
406 case Instruction::SetLE:
407 case Instruction::SetGE:
408 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
409 CE->getOpcode(), R);
410 return;
411
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000412 case Instruction::Shl:
413 case Instruction::Shr:
414 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000415 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
416 return;
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000417
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000418 default:
419 std::cerr << "Offending expr: " << C << "\n";
Chris Lattnerb2acc512003-10-19 21:09:10 +0000420 assert(0 && "Constant expression not yet handled!\n");
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000421 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000422 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000423
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000424 if (C->getType()->isIntegral()) {
Chris Lattner6b993cc2002-12-15 08:02:15 +0000425 unsigned Class = getClassB(C->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +0000426
427 if (Class == cLong) {
428 // Copy the value into the register pair.
Chris Lattnerc07736a2003-07-23 15:22:26 +0000429 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000430 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
431 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
Chris Lattner3e130a22003-01-13 00:32:26 +0000432 return;
433 }
434
Chris Lattner94af4142002-12-25 05:13:53 +0000435 assert(Class <= cInt && "Type not handled yet!");
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000436
437 static const unsigned IntegralOpcodeTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000438 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000439 };
440
Chris Lattner6b993cc2002-12-15 08:02:15 +0000441 if (C->getType() == Type::BoolTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000442 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000443 } else {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000444 ConstantInt *CI = cast<ConstantInt>(C);
Chris Lattneree352852004-02-29 07:22:16 +0000445 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000446 }
Chris Lattner94af4142002-12-25 05:13:53 +0000447 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattneraf703622004-02-02 18:56:30 +0000448 if (CFP->isExactlyValue(+0.0))
Chris Lattneree352852004-02-29 07:22:16 +0000449 BuildMI(*MBB, IP, X86::FLD0, 0, R);
Chris Lattneraf703622004-02-02 18:56:30 +0000450 else if (CFP->isExactlyValue(+1.0))
Chris Lattneree352852004-02-29 07:22:16 +0000451 BuildMI(*MBB, IP, X86::FLD1, 0, R);
Chris Lattner94af4142002-12-25 05:13:53 +0000452 else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000453 // Otherwise we need to spill the constant to memory...
454 MachineConstantPool *CP = F->getConstantPool();
455 unsigned CPI = CP->getConstantPoolIndex(CFP);
Chris Lattner6c09db22003-10-20 04:11:23 +0000456 const Type *Ty = CFP->getType();
457
458 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000459 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
Chris Lattneree352852004-02-29 07:22:16 +0000460 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
Chris Lattner94af4142002-12-25 05:13:53 +0000461 }
462
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000463 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000464 // Copy zero (null pointer) to the register.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000465 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000466 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000467 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(CPR->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000468 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000469 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000470 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000471 }
472}
473
Chris Lattner065faeb2002-12-28 20:24:02 +0000474/// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
475/// the stack into virtual registers.
476///
477void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
478 // Emit instructions to load the arguments... On entry to a function on the
479 // X86, the stack frame looks like this:
480 //
481 // [ESP] -- return address
Chris Lattner3e130a22003-01-13 00:32:26 +0000482 // [ESP + 4] -- first argument (leftmost lexically)
483 // [ESP + 8] -- second argument, if first argument is four bytes in size
Chris Lattner065faeb2002-12-28 20:24:02 +0000484 // ...
485 //
Chris Lattnerf158da22003-01-16 02:20:12 +0000486 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
Chris Lattneraa09b752002-12-28 21:08:28 +0000487 MachineFrameInfo *MFI = F->getFrameInfo();
Chris Lattner065faeb2002-12-28 20:24:02 +0000488
489 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
490 unsigned Reg = getReg(*I);
491
Chris Lattner065faeb2002-12-28 20:24:02 +0000492 int FI; // Frame object index
Chris Lattner065faeb2002-12-28 20:24:02 +0000493 switch (getClassB(I->getType())) {
494 case cByte:
Chris Lattneraa09b752002-12-28 21:08:28 +0000495 FI = MFI->CreateFixedObject(1, ArgOffset);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000496 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000497 break;
498 case cShort:
Chris Lattneraa09b752002-12-28 21:08:28 +0000499 FI = MFI->CreateFixedObject(2, ArgOffset);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000500 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000501 break;
502 case cInt:
Chris Lattneraa09b752002-12-28 21:08:28 +0000503 FI = MFI->CreateFixedObject(4, ArgOffset);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000504 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000505 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000506 case cLong:
507 FI = MFI->CreateFixedObject(8, ArgOffset);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000508 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
509 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +0000510 ArgOffset += 4; // longs require 4 additional bytes
511 break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000512 case cFP:
513 unsigned Opcode;
514 if (I->getType() == Type::FloatTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000515 Opcode = X86::FLD32m;
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000516 FI = MFI->CreateFixedObject(4, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000517 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000518 Opcode = X86::FLD64m;
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000519 FI = MFI->CreateFixedObject(8, ArgOffset);
520 ArgOffset += 4; // doubles require 4 additional bytes
Chris Lattner065faeb2002-12-28 20:24:02 +0000521 }
522 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
523 break;
524 default:
525 assert(0 && "Unhandled argument type!");
526 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000527 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000528 }
Chris Lattnereca195e2003-05-08 19:44:13 +0000529
530 // If the function takes variable number of arguments, add a frame offset for
531 // the start of the first vararg value... this is used to expand
532 // llvm.va_start.
533 if (Fn.getFunctionType()->isVarArg())
534 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000535}
536
537
Chris Lattner333b2fa2002-12-13 10:09:43 +0000538/// SelectPHINodes - Insert machine code to generate phis. This is tricky
539/// because we have to generate our sources into the source basic blocks, not
540/// the current one.
541///
542void ISel::SelectPHINodes() {
Chris Lattner3501fea2003-01-14 22:00:31 +0000543 const TargetInstrInfo &TII = TM.getInstrInfo();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000544 const Function &LF = *F->getFunction(); // The LLVM function...
545 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
546 const BasicBlock *BB = I;
Chris Lattner168aa902004-02-29 07:10:16 +0000547 MachineBasicBlock &MBB = *MBBMap[I];
Chris Lattner333b2fa2002-12-13 10:09:43 +0000548
549 // Loop over all of the PHI nodes in the LLVM basic block...
Chris Lattner168aa902004-02-29 07:10:16 +0000550 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000551 for (BasicBlock::const_iterator I = BB->begin();
Chris Lattnera81fc682003-10-19 00:26:11 +0000552 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000553
Chris Lattner333b2fa2002-12-13 10:09:43 +0000554 // Create a new machine instr PHI node, and insert it.
Chris Lattner3e130a22003-01-13 00:32:26 +0000555 unsigned PHIReg = getReg(*PN);
Chris Lattner168aa902004-02-29 07:10:16 +0000556 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
557 X86::PHI, PN->getNumOperands(), PHIReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000558
559 MachineInstr *LongPhiMI = 0;
Chris Lattner168aa902004-02-29 07:10:16 +0000560 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
561 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
562 X86::PHI, PN->getNumOperands(), PHIReg+1);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000563
Chris Lattnera6e73f12003-05-12 14:22:21 +0000564 // PHIValues - Map of blocks to incoming virtual registers. We use this
565 // so that we only initialize one incoming value for a particular block,
566 // even if the block has multiple entries in the PHI node.
567 //
568 std::map<MachineBasicBlock*, unsigned> PHIValues;
569
Chris Lattner333b2fa2002-12-13 10:09:43 +0000570 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
571 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
Chris Lattnera6e73f12003-05-12 14:22:21 +0000572 unsigned ValReg;
573 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
574 PHIValues.lower_bound(PredMBB);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000575
Chris Lattnera6e73f12003-05-12 14:22:21 +0000576 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
577 // We already inserted an initialization of the register for this
578 // predecessor. Recycle it.
579 ValReg = EntryIt->second;
580
581 } else {
Chris Lattnera81fc682003-10-19 00:26:11 +0000582 // Get the incoming value into a virtual register.
Chris Lattnera6e73f12003-05-12 14:22:21 +0000583 //
Chris Lattnera81fc682003-10-19 00:26:11 +0000584 Value *Val = PN->getIncomingValue(i);
585
586 // If this is a constant or GlobalValue, we may have to insert code
587 // into the basic block to compute it into a virtual register.
588 if (isa<Constant>(Val) || isa<GlobalValue>(Val)) {
589 // Because we don't want to clobber any values which might be in
590 // physical registers with the computation of this constant (which
591 // might be arbitrarily complex if it is a constant expression),
592 // just insert the computation at the top of the basic block.
593 MachineBasicBlock::iterator PI = PredMBB->begin();
594
595 // Skip over any PHI nodes though!
Alkis Evlogimenosc0b9dc52004-02-12 02:27:10 +0000596 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
Chris Lattnera81fc682003-10-19 00:26:11 +0000597 ++PI;
598
599 ValReg = getReg(Val, PredMBB, PI);
600 } else {
601 ValReg = getReg(Val);
602 }
Chris Lattnera6e73f12003-05-12 14:22:21 +0000603
604 // Remember that we inserted a value for this PHI for this predecessor
605 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
606 }
607
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000608 PhiMI->addRegOperand(ValReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000609 PhiMI->addMachineBasicBlockOperand(PredMBB);
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000610 if (LongPhiMI) {
611 LongPhiMI->addRegOperand(ValReg+1);
612 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
613 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000614 }
Chris Lattner168aa902004-02-29 07:10:16 +0000615
616 // Now that we emitted all of the incoming values for the PHI node, make
617 // sure to reposition the InsertPoint after the PHI that we just added.
618 // This is needed because we might have inserted a constant into this
619 // block, right after the PHI's which is before the old insert point!
620 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
621 ++PHIInsertPoint;
Chris Lattner333b2fa2002-12-13 10:09:43 +0000622 }
623 }
624}
625
Chris Lattner986618e2004-02-22 19:47:26 +0000626/// RequiresFPRegKill - The floating point stackifier pass cannot insert
627/// compensation code on critical edges. As such, it requires that we kill all
628/// FP registers on the exit from any blocks that either ARE critical edges, or
629/// branch to a block that has incoming critical edges.
630///
631/// Note that this kill instruction will eventually be eliminated when
632/// restrictions in the stackifier are relaxed.
633///
634static bool RequiresFPRegKill(const BasicBlock *BB) {
635#if 0
636 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
637 const BasicBlock *Succ = *SI;
638 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
639 ++PI; // Block have at least one predecessory
640 if (PI != PE) { // If it has exactly one, this isn't crit edge
641 // If this block has more than one predecessor, check all of the
642 // predecessors to see if they have multiple successors. If so, then the
643 // block we are analyzing needs an FPRegKill.
644 for (PI = pred_begin(Succ); PI != PE; ++PI) {
645 const BasicBlock *Pred = *PI;
646 succ_const_iterator SI2 = succ_begin(Pred);
647 ++SI2; // There must be at least one successor of this block.
648 if (SI2 != succ_end(Pred))
649 return true; // Yes, we must insert the kill on this edge.
650 }
651 }
652 }
653 // If we got this far, there is no need to insert the kill instruction.
654 return false;
655#else
656 return true;
657#endif
658}
659
660// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
661// need them. This only occurs due to the floating point stackifier not being
662// aggressive enough to handle arbitrary global stackification.
663//
664// Currently we insert an FP_REG_KILL instruction into each block that uses or
665// defines a floating point virtual register.
666//
667// When the global register allocators (like linear scan) finally update live
668// variable analysis, we can keep floating point values in registers across
669// portions of the CFG that do not involve critical edges. This will be a big
670// win, but we are waiting on the global allocators before we can do this.
671//
672// With a bit of work, the floating point stackifier pass can be enhanced to
673// break critical edges as needed (to make a place to put compensation code),
674// but this will require some infrastructure improvements as well.
675//
676void ISel::InsertFPRegKills() {
677 SSARegMap &RegMap = *F->getSSARegMap();
Chris Lattner986618e2004-02-22 19:47:26 +0000678
679 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000680 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000681 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
682 MachineOperand& MO = I->getOperand(i);
683 if (MO.isRegister() && MO.getReg()) {
684 unsigned Reg = MO.getReg();
Chris Lattner986618e2004-02-22 19:47:26 +0000685 if (MRegisterInfo::isVirtualRegister(Reg))
Chris Lattner65cf42d2004-02-23 07:29:45 +0000686 if (RegMap.getRegClass(Reg)->getSize() == 10)
687 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000688 }
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000689 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000690 // If we haven't found an FP register use or def in this basic block, check
691 // to see if any of our successors has an FP PHI node, which will cause a
692 // copy to be inserted into this block.
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000693 for (succ_const_iterator SI = succ_begin(BB->getBasicBlock()),
694 E = succ_end(BB->getBasicBlock()); SI != E; ++SI) {
695 MachineBasicBlock *SBB = MBBMap[*SI];
696 for (MachineBasicBlock::iterator I = SBB->begin();
697 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
698 if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
699 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000700 }
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000701 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000702 continue;
703 UsesFPReg:
704 // Okay, this block uses an FP register. If the block has successors (ie,
705 // it's not an unwind/return), insert the FP_REG_KILL instruction.
706 if (BB->getBasicBlock()->getTerminator()->getNumSuccessors() &&
707 RequiresFPRegKill(BB->getBasicBlock())) {
Chris Lattneree352852004-02-29 07:22:16 +0000708 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
Chris Lattner65cf42d2004-02-23 07:29:45 +0000709 ++NumFPKill;
Chris Lattner986618e2004-02-22 19:47:26 +0000710 }
711 }
712}
713
714
Chris Lattner6d40c192003-01-16 16:43:00 +0000715// canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
716// the conditional branch instruction which is the only user of the cc
717// instruction. This is the case if the conditional branch is the only user of
718// the setcc, and if the setcc is in the same basic block as the conditional
719// branch. We also don't handle long arguments below, so we reject them here as
720// well.
721//
722static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
723 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
Chris Lattnerfd059242003-10-15 16:48:29 +0000724 if (SCI->hasOneUse() && isa<BranchInst>(SCI->use_back()) &&
Chris Lattner6d40c192003-01-16 16:43:00 +0000725 SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
726 const Type *Ty = SCI->getOperand(0)->getType();
727 if (Ty != Type::LongTy && Ty != Type::ULongTy)
728 return SCI;
729 }
730 return 0;
731}
Chris Lattner333b2fa2002-12-13 10:09:43 +0000732
Chris Lattner6d40c192003-01-16 16:43:00 +0000733// Return a fixed numbering for setcc instructions which does not depend on the
734// order of the opcodes.
735//
736static unsigned getSetCCNumber(unsigned Opcode) {
737 switch(Opcode) {
738 default: assert(0 && "Unknown setcc instruction!");
739 case Instruction::SetEQ: return 0;
740 case Instruction::SetNE: return 1;
741 case Instruction::SetLT: return 2;
Chris Lattner55f6fab2003-01-16 18:07:23 +0000742 case Instruction::SetGE: return 3;
743 case Instruction::SetGT: return 4;
744 case Instruction::SetLE: return 5;
Chris Lattner6d40c192003-01-16 16:43:00 +0000745 }
746}
Chris Lattner06925362002-11-17 21:56:38 +0000747
Chris Lattner6d40c192003-01-16 16:43:00 +0000748// LLVM -> X86 signed X86 unsigned
749// ----- ---------- ------------
750// seteq -> sete sete
751// setne -> setne setne
752// setlt -> setl setb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000753// setge -> setge setae
Chris Lattner6d40c192003-01-16 16:43:00 +0000754// setgt -> setg seta
755// setle -> setle setbe
Chris Lattnerb2acc512003-10-19 21:09:10 +0000756// ----
757// sets // Used by comparison with 0 optimization
758// setns
759static const unsigned SetCCOpcodeTab[2][8] = {
760 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
761 0, 0 },
762 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
763 X86::SETSr, X86::SETNSr },
Chris Lattner6d40c192003-01-16 16:43:00 +0000764};
765
Chris Lattnerb2acc512003-10-19 21:09:10 +0000766// EmitComparison - This function emits a comparison of the two operands,
767// returning the extended setcc code to use.
768unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
769 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000770 MachineBasicBlock::iterator IP) {
Brian Gaeke1749d632002-11-07 17:59:21 +0000771 // The arguments are already supposed to be of the same type.
Chris Lattner6d40c192003-01-16 16:43:00 +0000772 const Type *CompTy = Op0->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +0000773 unsigned Class = getClassB(CompTy);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000774 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattner333864d2003-06-05 19:30:30 +0000775
776 // Special case handling of: cmp R, i
777 if (Class == cByte || Class == cShort || Class == cInt)
778 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000779 uint64_t Op1v = cast<ConstantInt>(CI)->getRawValue();
780
Chris Lattner333864d2003-06-05 19:30:30 +0000781 // Mask off any upper bits of the constant, if there are any...
782 Op1v &= (1ULL << (8 << Class)) - 1;
783
Chris Lattnerb2acc512003-10-19 21:09:10 +0000784 // If this is a comparison against zero, emit more efficient code. We
785 // can't handle unsigned comparisons against zero unless they are == or
786 // !=. These should have been strength reduced already anyway.
787 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
788 static const unsigned TESTTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000789 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
Chris Lattnerb2acc512003-10-19 21:09:10 +0000790 };
Chris Lattneree352852004-02-29 07:22:16 +0000791 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000792
793 if (OpNum == 2) return 6; // Map jl -> js
794 if (OpNum == 3) return 7; // Map jg -> jns
795 return OpNum;
Chris Lattner333864d2003-06-05 19:30:30 +0000796 }
Chris Lattnerb2acc512003-10-19 21:09:10 +0000797
798 static const unsigned CMPTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000799 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
Chris Lattnerb2acc512003-10-19 21:09:10 +0000800 };
801
Chris Lattneree352852004-02-29 07:22:16 +0000802 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000803 return OpNum;
Chris Lattner333864d2003-06-05 19:30:30 +0000804 }
805
Chris Lattner9f08a922004-02-03 18:54:04 +0000806 // Special case handling of comparison against +/- 0.0
807 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
808 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
Chris Lattneree352852004-02-29 07:22:16 +0000809 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000810 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +0000811 BuildMI(*MBB, IP, X86::SAHF, 1);
Chris Lattner9f08a922004-02-03 18:54:04 +0000812 return OpNum;
813 }
814
Chris Lattner58c41fe2003-08-24 19:19:47 +0000815 unsigned Op1r = getReg(Op1, MBB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +0000816 switch (Class) {
817 default: assert(0 && "Unknown type class!");
818 // Emit: cmp <var1>, <var2> (do the comparison). We can
819 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
820 // 32-bit.
821 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000822 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000823 break;
824 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000825 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000826 break;
827 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000828 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000829 break;
830 case cFP:
Chris Lattneree352852004-02-29 07:22:16 +0000831 BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000832 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +0000833 BuildMI(*MBB, IP, X86::SAHF, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +0000834 break;
835
836 case cLong:
837 if (OpNum < 2) { // seteq, setne
838 unsigned LoTmp = makeAnotherReg(Type::IntTy);
839 unsigned HiTmp = makeAnotherReg(Type::IntTy);
840 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000841 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
842 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
843 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
Chris Lattner3e130a22003-01-13 00:32:26 +0000844 break; // Allow the sete or setne to be generated from flags set by OR
845 } else {
846 // Emit a sequence of code which compares the high and low parts once
847 // each, then uses a conditional move to handle the overflow case. For
848 // example, a setlt for long would generate code like this:
849 //
850 // AL = lo(op1) < lo(op2) // Signedness depends on operands
851 // BL = hi(op1) < hi(op2) // Always unsigned comparison
852 // dest = hi(op1) == hi(op2) ? AL : BL;
853 //
854
Chris Lattner6d40c192003-01-16 16:43:00 +0000855 // FIXME: This would be much better if we had hierarchical register
Chris Lattner3e130a22003-01-13 00:32:26 +0000856 // classes! Until then, hardcode registers so that we can deal with their
857 // aliases (because we don't have conditional byte moves).
858 //
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000859 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattneree352852004-02-29 07:22:16 +0000860 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000861 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
Chris Lattneree352852004-02-29 07:22:16 +0000862 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
863 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
864 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000865 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
Chris Lattneree352852004-02-29 07:22:16 +0000866 .addReg(X86::AX);
Chris Lattner6d40c192003-01-16 16:43:00 +0000867 // NOTE: visitSetCondInst knows that the value is dumped into the BL
868 // register at this point for long values...
Chris Lattnerb2acc512003-10-19 21:09:10 +0000869 return OpNum;
Chris Lattner3e130a22003-01-13 00:32:26 +0000870 }
871 }
Chris Lattnerb2acc512003-10-19 21:09:10 +0000872 return OpNum;
Chris Lattner6d40c192003-01-16 16:43:00 +0000873}
Chris Lattner3e130a22003-01-13 00:32:26 +0000874
Chris Lattner6d40c192003-01-16 16:43:00 +0000875
876/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
877/// register, then move it to wherever the result should be.
878///
879void ISel::visitSetCondInst(SetCondInst &I) {
880 if (canFoldSetCCIntoBranch(&I)) return; // Fold this into a branch...
881
Chris Lattner6d40c192003-01-16 16:43:00 +0000882 unsigned DestReg = getReg(I);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000883 MachineBasicBlock::iterator MII = BB->end();
884 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
885 DestReg);
886}
Chris Lattner6d40c192003-01-16 16:43:00 +0000887
Chris Lattner58c41fe2003-08-24 19:19:47 +0000888/// emitSetCCOperation - Common code shared between visitSetCondInst and
889/// constant expression support.
890void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000891 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +0000892 Value *Op0, Value *Op1, unsigned Opcode,
893 unsigned TargetReg) {
894 unsigned OpNum = getSetCCNumber(Opcode);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000895 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000896
Chris Lattnerb2acc512003-10-19 21:09:10 +0000897 const Type *CompTy = Op0->getType();
898 unsigned CompClass = getClassB(CompTy);
899 bool isSigned = CompTy->isSigned() && CompClass != cFP;
900
901 if (CompClass != cLong || OpNum < 2) {
Chris Lattner6d40c192003-01-16 16:43:00 +0000902 // Handle normal comparisons with a setcc instruction...
Chris Lattneree352852004-02-29 07:22:16 +0000903 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
Chris Lattner6d40c192003-01-16 16:43:00 +0000904 } else {
905 // Handle long comparisons by copying the value which is already in BL into
906 // the register we want...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000907 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
Chris Lattner6d40c192003-01-16 16:43:00 +0000908 }
Brian Gaeke1749d632002-11-07 17:59:21 +0000909}
Chris Lattner51b49a92002-11-02 19:45:49 +0000910
Chris Lattner58c41fe2003-08-24 19:19:47 +0000911
912
913
Brian Gaekec2505982002-11-30 11:57:28 +0000914/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
915/// operand, in the specified target register.
Chris Lattner3e130a22003-01-13 00:32:26 +0000916void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
917 bool isUnsigned = VR.Ty->isUnsigned();
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000918
919 // Make sure we have the register number for this value...
920 unsigned Reg = VR.Val ? getReg(VR.Val) : VR.Reg;
921
Chris Lattner3e130a22003-01-13 00:32:26 +0000922 switch (getClassB(VR.Ty)) {
Chris Lattner94af4142002-12-25 05:13:53 +0000923 case cByte:
924 // Extend value into target register (8->32)
925 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000926 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000927 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000928 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000929 break;
930 case cShort:
931 // Extend value into target register (16->32)
932 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000933 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000934 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000935 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000936 break;
937 case cInt:
938 // Move value into target register (32->32)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000939 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +0000940 break;
941 default:
942 assert(0 && "Unpromotable operand class in promote32");
943 }
Brian Gaekec2505982002-11-30 11:57:28 +0000944}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000945
Chris Lattner72614082002-10-25 22:55:53 +0000946/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
947/// we have the following possibilities:
948///
949/// ret void: No return value, simply emit a 'ret' instruction
950/// ret sbyte, ubyte : Extend value into EAX and return
951/// ret short, ushort: Extend value into EAX and return
952/// ret int, uint : Move value into EAX and return
953/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +0000954/// ret long, ulong : Move value into EAX/EDX and return
955/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +0000956///
Chris Lattner3e130a22003-01-13 00:32:26 +0000957void ISel::visitReturnInst(ReturnInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +0000958 if (I.getNumOperands() == 0) {
959 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
960 return;
961 }
962
963 Value *RetVal = I.getOperand(0);
Chris Lattner3e130a22003-01-13 00:32:26 +0000964 unsigned RetReg = getReg(RetVal);
965 switch (getClassB(RetVal->getType())) {
Chris Lattner94af4142002-12-25 05:13:53 +0000966 case cByte: // integral return values: extend or move into EAX and return
967 case cShort:
968 case cInt:
Chris Lattner3e130a22003-01-13 00:32:26 +0000969 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
Chris Lattnerdbd73722003-05-06 21:32:22 +0000970 // Declare that EAX is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +0000971 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +0000972 break;
973 case cFP: // Floats & Doubles: Return in ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +0000974 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
Chris Lattnerdbd73722003-05-06 21:32:22 +0000975 // Declare that top-of-stack is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +0000976 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +0000977 break;
978 case cLong:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000979 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
980 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
Chris Lattnerdbd73722003-05-06 21:32:22 +0000981 // Declare that EAX & EDX are live on exit
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000982 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
983 .addReg(X86::ESP);
Chris Lattner3e130a22003-01-13 00:32:26 +0000984 break;
Chris Lattner94af4142002-12-25 05:13:53 +0000985 default:
Chris Lattner3e130a22003-01-13 00:32:26 +0000986 visitInstruction(I);
Chris Lattner94af4142002-12-25 05:13:53 +0000987 }
Chris Lattner43189d12002-11-17 20:07:45 +0000988 // Emit a 'ret' instruction
Chris Lattner94af4142002-12-25 05:13:53 +0000989 BuildMI(BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +0000990}
991
Chris Lattner55f6fab2003-01-16 18:07:23 +0000992// getBlockAfter - Return the basic block which occurs lexically after the
993// specified one.
994static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
995 Function::iterator I = BB; ++I; // Get iterator to next block
996 return I != BB->getParent()->end() ? &*I : 0;
997}
998
Chris Lattner51b49a92002-11-02 19:45:49 +0000999/// visitBranchInst - Handle conditional and unconditional branches here. Note
1000/// that since code layout is frozen at this point, that if we are trying to
1001/// jump to a block that is the immediate successor of the current block, we can
Chris Lattner6d40c192003-01-16 16:43:00 +00001002/// just make a fall-through (but we don't currently).
Chris Lattner51b49a92002-11-02 19:45:49 +00001003///
Chris Lattner94af4142002-12-25 05:13:53 +00001004void ISel::visitBranchInst(BranchInst &BI) {
Chris Lattner55f6fab2003-01-16 18:07:23 +00001005 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1006
1007 if (!BI.isConditional()) { // Unconditional branch?
Chris Lattnercf93cdd2004-01-30 22:13:44 +00001008 if (BI.getSuccessor(0) != NextBB)
Chris Lattner55f6fab2003-01-16 18:07:23 +00001009 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
Chris Lattner6d40c192003-01-16 16:43:00 +00001010 return;
1011 }
1012
1013 // See if we can fold the setcc into the branch itself...
1014 SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
1015 if (SCI == 0) {
1016 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1017 // computed some other way...
Chris Lattner065faeb2002-12-28 20:24:02 +00001018 unsigned condReg = getReg(BI.getCondition());
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001019 BuildMI(BB, X86::CMP8ri, 2).addReg(condReg).addImm(0);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001020 if (BI.getSuccessor(1) == NextBB) {
1021 if (BI.getSuccessor(0) != NextBB)
1022 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1023 } else {
1024 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1025
1026 if (BI.getSuccessor(0) != NextBB)
1027 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1028 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001029 return;
Chris Lattner94af4142002-12-25 05:13:53 +00001030 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001031
1032 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
Chris Lattner58c41fe2003-08-24 19:19:47 +00001033 MachineBasicBlock::iterator MII = BB->end();
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001034 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001035
1036 const Type *CompTy = SCI->getOperand(0)->getType();
1037 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
Chris Lattner6d40c192003-01-16 16:43:00 +00001038
Chris Lattnerb2acc512003-10-19 21:09:10 +00001039
Chris Lattner6d40c192003-01-16 16:43:00 +00001040 // LLVM -> X86 signed X86 unsigned
1041 // ----- ---------- ------------
1042 // seteq -> je je
1043 // setne -> jne jne
1044 // setlt -> jl jb
Chris Lattner55f6fab2003-01-16 18:07:23 +00001045 // setge -> jge jae
Chris Lattner6d40c192003-01-16 16:43:00 +00001046 // setgt -> jg ja
1047 // setle -> jle jbe
Chris Lattnerb2acc512003-10-19 21:09:10 +00001048 // ----
1049 // js // Used by comparison with 0 optimization
1050 // jns
1051
1052 static const unsigned OpcodeTab[2][8] = {
1053 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1054 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1055 X86::JS, X86::JNS },
Chris Lattner6d40c192003-01-16 16:43:00 +00001056 };
1057
Chris Lattner55f6fab2003-01-16 18:07:23 +00001058 if (BI.getSuccessor(0) != NextBB) {
1059 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1060 if (BI.getSuccessor(1) != NextBB)
1061 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1062 } else {
1063 // Change to the inverse condition...
1064 if (BI.getSuccessor(1) != NextBB) {
1065 OpNum ^= 1;
1066 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1067 }
1068 }
Chris Lattner2df035b2002-11-02 19:27:56 +00001069}
1070
Chris Lattner3e130a22003-01-13 00:32:26 +00001071
1072/// doCall - This emits an abstract call instruction, setting up the arguments
1073/// and the return value as appropriate. For the actual function call itself,
1074/// it inserts the specified CallMI instruction into the stream.
1075///
1076void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001077 const std::vector<ValueRecord> &Args) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001078
Chris Lattner065faeb2002-12-28 20:24:02 +00001079 // Count how many bytes are to be pushed on the stack...
1080 unsigned NumBytes = 0;
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001081
Chris Lattner3e130a22003-01-13 00:32:26 +00001082 if (!Args.empty()) {
1083 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1084 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001085 case cByte: case cShort: case cInt:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001086 NumBytes += 4; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001087 case cLong:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001088 NumBytes += 8; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001089 case cFP:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001090 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1091 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001092 default: assert(0 && "Unknown class!");
1093 }
1094
1095 // Adjust the stack pointer for the new arguments...
Chris Lattneree352852004-02-29 07:22:16 +00001096 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
Chris Lattner065faeb2002-12-28 20:24:02 +00001097
1098 // Arguments go on the stack in reverse order, as specified by the ABI.
1099 unsigned ArgOffset = 0;
Chris Lattner3e130a22003-01-13 00:32:26 +00001100 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Chris Lattnerce6096f2004-03-01 02:34:08 +00001101 unsigned ArgReg;
Chris Lattner3e130a22003-01-13 00:32:26 +00001102 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001103 case cByte:
Chris Lattner21585222004-03-01 02:42:43 +00001104 case cShort:
1105 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1106 // Zero/Sign extend constant, then stuff into memory.
1107 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1108 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1109 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1110 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1111 } else {
1112 // Promote arg to 32 bits wide into a temporary register...
1113 ArgReg = makeAnotherReg(Type::UIntTy);
1114 promote32(ArgReg, Args[i]);
1115 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1116 X86::ESP, ArgOffset).addReg(ArgReg);
1117 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001118 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001119 case cInt:
Chris Lattner21585222004-03-01 02:42:43 +00001120 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1121 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1122 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1123 X86::ESP, ArgOffset).addImm(Val);
1124 } else {
1125 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1126 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1127 X86::ESP, ArgOffset).addReg(ArgReg);
1128 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001129 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001130 case cLong:
Chris Lattnerce6096f2004-03-01 02:34:08 +00001131 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001132 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001133 X86::ESP, ArgOffset).addReg(ArgReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001134 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001135 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1136 ArgOffset += 4; // 8 byte entry, not 4.
1137 break;
1138
Chris Lattner065faeb2002-12-28 20:24:02 +00001139 case cFP:
Chris Lattnerce6096f2004-03-01 02:34:08 +00001140 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001141 if (Args[i].Ty == Type::FloatTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001142 addRegOffset(BuildMI(BB, X86::FST32m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001143 X86::ESP, ArgOffset).addReg(ArgReg);
1144 } else {
1145 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001146 addRegOffset(BuildMI(BB, X86::FST64m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001147 X86::ESP, ArgOffset).addReg(ArgReg);
1148 ArgOffset += 4; // 8 byte entry, not 4.
1149 }
1150 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001151
Chris Lattner3e130a22003-01-13 00:32:26 +00001152 default: assert(0 && "Unknown class!");
Chris Lattner065faeb2002-12-28 20:24:02 +00001153 }
1154 ArgOffset += 4;
Chris Lattner94af4142002-12-25 05:13:53 +00001155 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001156 } else {
Chris Lattneree352852004-02-29 07:22:16 +00001157 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +00001158 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +00001159
Chris Lattner3e130a22003-01-13 00:32:26 +00001160 BB->push_back(CallMI);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001161
Chris Lattneree352852004-02-29 07:22:16 +00001162 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
Chris Lattnera3243642002-12-04 23:45:28 +00001163
1164 // If there is a return value, scavenge the result from the location the call
1165 // leaves it in...
1166 //
Chris Lattner3e130a22003-01-13 00:32:26 +00001167 if (Ret.Ty != Type::VoidTy) {
1168 unsigned DestClass = getClassB(Ret.Ty);
1169 switch (DestClass) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001170 case cByte:
1171 case cShort:
1172 case cInt: {
1173 // Integral results are in %eax, or the appropriate portion
1174 // thereof.
1175 static const unsigned regRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001176 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
Brian Gaeke20244b72002-12-12 15:33:40 +00001177 };
1178 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +00001179 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001180 break;
Brian Gaeke20244b72002-12-12 15:33:40 +00001181 }
Chris Lattner94af4142002-12-25 05:13:53 +00001182 case cFP: // Floating-point return values live in %ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +00001183 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001184 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001185 case cLong: // Long values are left in EDX:EAX
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001186 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1187 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
Chris Lattner3e130a22003-01-13 00:32:26 +00001188 break;
1189 default: assert(0 && "Unknown class!");
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001190 }
Chris Lattnera3243642002-12-04 23:45:28 +00001191 }
Brian Gaekefa8d5712002-11-22 11:07:01 +00001192}
Chris Lattner2df035b2002-11-02 19:27:56 +00001193
Chris Lattner3e130a22003-01-13 00:32:26 +00001194
1195/// visitCallInst - Push args on stack and do a procedure call instruction.
1196void ISel::visitCallInst(CallInst &CI) {
1197 MachineInstr *TheCall;
1198 if (Function *F = CI.getCalledFunction()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001199 // Is it an intrinsic function call?
Brian Gaeked0fde302003-11-11 22:41:34 +00001200 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001201 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1202 return;
1203 }
1204
Chris Lattner3e130a22003-01-13 00:32:26 +00001205 // Emit a CALL instruction with PC-relative displacement.
1206 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1207 } else { // Emit an indirect call...
1208 unsigned Reg = getReg(CI.getCalledValue());
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001209 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001210 }
1211
1212 std::vector<ValueRecord> Args;
1213 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001214 Args.push_back(ValueRecord(CI.getOperand(i)));
Chris Lattner3e130a22003-01-13 00:32:26 +00001215
1216 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1217 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001218}
Chris Lattner3e130a22003-01-13 00:32:26 +00001219
Chris Lattneraeb54b82003-08-28 21:23:43 +00001220
Chris Lattner44827152003-12-28 09:47:19 +00001221/// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1222/// function, lowering any calls to unknown intrinsic functions into the
1223/// equivalent LLVM code.
1224void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1225 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1226 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1227 if (CallInst *CI = dyn_cast<CallInst>(I++))
1228 if (Function *F = CI->getCalledFunction())
1229 switch (F->getIntrinsicID()) {
Chris Lattneraed386e2003-12-28 09:53:23 +00001230 case Intrinsic::not_intrinsic:
Chris Lattner44827152003-12-28 09:47:19 +00001231 case Intrinsic::va_start:
1232 case Intrinsic::va_copy:
1233 case Intrinsic::va_end:
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001234 case Intrinsic::returnaddress:
1235 case Intrinsic::frameaddress:
Chris Lattner915e5e52004-02-12 17:53:22 +00001236 case Intrinsic::memcpy:
Chris Lattner2a0f2242004-02-14 04:46:05 +00001237 case Intrinsic::memset:
Chris Lattner44827152003-12-28 09:47:19 +00001238 // We directly implement these intrinsics
1239 break;
1240 default:
1241 // All other intrinsic calls we must lower.
1242 Instruction *Before = CI->getPrev();
Chris Lattnerf70e0c22003-12-28 21:23:38 +00001243 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
Chris Lattner44827152003-12-28 09:47:19 +00001244 if (Before) { // Move iterator to instruction after call
1245 I = Before; ++I;
1246 } else {
1247 I = BB->begin();
1248 }
1249 }
1250
1251}
1252
Brian Gaeked0fde302003-11-11 22:41:34 +00001253void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001254 unsigned TmpReg1, TmpReg2;
1255 switch (ID) {
Brian Gaeked0fde302003-11-11 22:41:34 +00001256 case Intrinsic::va_start:
Chris Lattnereca195e2003-05-08 19:44:13 +00001257 // Get the address of the first vararg value...
Chris Lattner73815062003-10-18 05:56:40 +00001258 TmpReg1 = getReg(CI);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001259 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
Chris Lattnereca195e2003-05-08 19:44:13 +00001260 return;
1261
Brian Gaeked0fde302003-11-11 22:41:34 +00001262 case Intrinsic::va_copy:
Chris Lattner73815062003-10-18 05:56:40 +00001263 TmpReg1 = getReg(CI);
1264 TmpReg2 = getReg(CI.getOperand(1));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001265 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
Chris Lattnereca195e2003-05-08 19:44:13 +00001266 return;
Brian Gaeked0fde302003-11-11 22:41:34 +00001267 case Intrinsic::va_end: return; // Noop on X86
Chris Lattnereca195e2003-05-08 19:44:13 +00001268
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001269 case Intrinsic::returnaddress:
1270 case Intrinsic::frameaddress:
1271 TmpReg1 = getReg(CI);
1272 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1273 if (ID == Intrinsic::returnaddress) {
1274 // Just load the return address
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001275 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001276 ReturnAddressIndex);
1277 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001278 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001279 ReturnAddressIndex, -4);
1280 }
1281 } else {
1282 // Values other than zero are not implemented yet.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001283 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001284 }
1285 return;
1286
Chris Lattner915e5e52004-02-12 17:53:22 +00001287 case Intrinsic::memcpy: {
1288 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1289 unsigned Align = 1;
1290 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1291 Align = AlignC->getRawValue();
1292 if (Align == 0) Align = 1;
1293 }
1294
1295 // Turn the byte code into # iterations
Chris Lattner915e5e52004-02-12 17:53:22 +00001296 unsigned CountReg;
Chris Lattner2a0f2242004-02-14 04:46:05 +00001297 unsigned Opcode;
Chris Lattner915e5e52004-02-12 17:53:22 +00001298 switch (Align & 3) {
1299 case 2: // WORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001300 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1301 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1302 } else {
1303 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001304 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001305 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner07122832004-02-13 23:36:47 +00001306 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001307 Opcode = X86::REP_MOVSW;
Chris Lattner915e5e52004-02-12 17:53:22 +00001308 break;
1309 case 0: // DWORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001310 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1311 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1312 } else {
1313 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001314 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001315 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner07122832004-02-13 23:36:47 +00001316 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001317 Opcode = X86::REP_MOVSD;
Chris Lattner915e5e52004-02-12 17:53:22 +00001318 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001319 default: // BYTE aligned
Chris Lattner07122832004-02-13 23:36:47 +00001320 CountReg = getReg(CI.getOperand(3));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001321 Opcode = X86::REP_MOVSB;
Chris Lattner915e5e52004-02-12 17:53:22 +00001322 break;
1323 }
1324
1325 // No matter what the alignment is, we put the source in ESI, the
1326 // destination in EDI, and the count in ECX.
1327 TmpReg1 = getReg(CI.getOperand(1));
1328 TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001329 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1330 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1331 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001332 BuildMI(BB, Opcode, 0);
1333 return;
1334 }
1335 case Intrinsic::memset: {
1336 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1337 unsigned Align = 1;
1338 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1339 Align = AlignC->getRawValue();
1340 if (Align == 0) Align = 1;
Chris Lattner915e5e52004-02-12 17:53:22 +00001341 }
1342
Chris Lattner2a0f2242004-02-14 04:46:05 +00001343 // Turn the byte code into # iterations
Chris Lattner2a0f2242004-02-14 04:46:05 +00001344 unsigned CountReg;
1345 unsigned Opcode;
1346 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1347 unsigned Val = ValC->getRawValue() & 255;
1348
1349 // If the value is a constant, then we can potentially use larger copies.
1350 switch (Align & 3) {
1351 case 2: // WORD aligned
1352 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001353 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001354 } else {
1355 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001356 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001357 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001358 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001359 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001360 Opcode = X86::REP_STOSW;
1361 break;
1362 case 0: // DWORD aligned
1363 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001364 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001365 } else {
1366 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001367 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001368 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001369 }
1370 Val = (Val << 8) | Val;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001371 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001372 Opcode = X86::REP_STOSD;
1373 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001374 default: // BYTE aligned
Chris Lattner2a0f2242004-02-14 04:46:05 +00001375 CountReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001376 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001377 Opcode = X86::REP_STOSB;
1378 break;
1379 }
1380 } else {
1381 // If it's not a constant value we are storing, just fall back. We could
1382 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1383 unsigned ValReg = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001384 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001385 CountReg = getReg(CI.getOperand(3));
1386 Opcode = X86::REP_STOSB;
1387 }
1388
1389 // No matter what the alignment is, we put the source in ESI, the
1390 // destination in EDI, and the count in ECX.
1391 TmpReg1 = getReg(CI.getOperand(1));
1392 //TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001393 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1394 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001395 BuildMI(BB, Opcode, 0);
Chris Lattner915e5e52004-02-12 17:53:22 +00001396 return;
1397 }
1398
Chris Lattner44827152003-12-28 09:47:19 +00001399 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
Chris Lattnereca195e2003-05-08 19:44:13 +00001400 }
1401}
1402
1403
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001404/// visitSimpleBinary - Implement simple binary operators for integral types...
1405/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1406/// Xor.
1407void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1408 unsigned DestReg = getReg(B);
1409 MachineBasicBlock::iterator MI = BB->end();
1410 emitSimpleBinaryOperation(BB, MI, B.getOperand(0), B.getOperand(1),
1411 OperatorClass, DestReg);
1412}
Chris Lattner3e130a22003-01-13 00:32:26 +00001413
Chris Lattnerb2acc512003-10-19 21:09:10 +00001414/// emitSimpleBinaryOperation - Implement simple binary operators for integral
1415/// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1416/// Or, 4 for Xor.
Chris Lattner68aad932002-11-02 20:13:22 +00001417///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001418/// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1419/// and constant expression support.
Chris Lattnerb2acc512003-10-19 21:09:10 +00001420///
1421void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001422 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001423 Value *Op0, Value *Op1,
Chris Lattnerb2acc512003-10-19 21:09:10 +00001424 unsigned OperatorClass, unsigned DestReg) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001425 unsigned Class = getClassB(Op0->getType());
Chris Lattnerb2acc512003-10-19 21:09:10 +00001426
1427 // sub 0, X -> neg X
1428 if (OperatorClass == 1 && Class != cLong)
Chris Lattneraf703622004-02-02 18:56:30 +00001429 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
Chris Lattnerb2acc512003-10-19 21:09:10 +00001430 if (CI->isNullValue()) {
1431 unsigned op1Reg = getReg(Op1, MBB, IP);
1432 switch (Class) {
1433 default: assert(0 && "Unknown class for this function!");
1434 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001435 BuildMI(*MBB, IP, X86::NEG8r, 1, DestReg).addReg(op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001436 return;
1437 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001438 BuildMI(*MBB, IP, X86::NEG16r, 1, DestReg).addReg(op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001439 return;
1440 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001441 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg).addReg(op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001442 return;
1443 }
1444 }
Chris Lattner9f8fd6d2004-02-02 19:31:38 +00001445 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1446 if (CFP->isExactlyValue(-0.0)) {
1447 // -0.0 - X === -X
1448 unsigned op1Reg = getReg(Op1, MBB, IP);
Chris Lattneree352852004-02-29 07:22:16 +00001449 BuildMI(*MBB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
Chris Lattner9f8fd6d2004-02-02 19:31:38 +00001450 return;
1451 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001452
Chris Lattner35333e12003-06-05 18:28:55 +00001453 if (!isa<ConstantInt>(Op1) || Class == cLong) {
1454 static const unsigned OpcodeTab[][4] = {
1455 // Arithmetic operators
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001456 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, X86::FpADD }, // ADD
1457 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::FpSUB }, // SUB
Chris Lattner35333e12003-06-05 18:28:55 +00001458
1459 // Bitwise operators
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001460 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0 }, // AND
1461 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0 }, // OR
1462 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0 }, // XOR
Chris Lattner3e130a22003-01-13 00:32:26 +00001463 };
Chris Lattner35333e12003-06-05 18:28:55 +00001464
1465 bool isLong = false;
1466 if (Class == cLong) {
1467 isLong = true;
1468 Class = cInt; // Bottom 32 bits are handled just like ints
1469 }
1470
1471 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1472 assert(Opcode && "Floating point arguments to logical inst?");
Chris Lattnerb2acc512003-10-19 21:09:10 +00001473 unsigned Op0r = getReg(Op0, MBB, IP);
1474 unsigned Op1r = getReg(Op1, MBB, IP);
Chris Lattneree352852004-02-29 07:22:16 +00001475 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
Chris Lattner35333e12003-06-05 18:28:55 +00001476
1477 if (isLong) { // Handle the upper 32 bits of long values...
1478 static const unsigned TopTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001479 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
Chris Lattner35333e12003-06-05 18:28:55 +00001480 };
Chris Lattneree352852004-02-29 07:22:16 +00001481 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
Chris Lattnerb2acc512003-10-19 21:09:10 +00001482 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
Chris Lattner35333e12003-06-05 18:28:55 +00001483 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001484 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00001485 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001486
1487 // Special case: op Reg, <const>
1488 ConstantInt *Op1C = cast<ConstantInt>(Op1);
1489 unsigned Op0r = getReg(Op0, MBB, IP);
1490
1491 // xor X, -1 -> not X
1492 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001493 static unsigned const NOTTab[] = { X86::NOT8r, X86::NOT16r, X86::NOT32r };
Chris Lattneree352852004-02-29 07:22:16 +00001494 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001495 return;
1496 }
1497
1498 // add X, -1 -> dec X
1499 if (OperatorClass == 0 && Op1C->isAllOnesValue()) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001500 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
Chris Lattneree352852004-02-29 07:22:16 +00001501 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001502 return;
1503 }
1504
1505 // add X, 1 -> inc X
1506 if (OperatorClass == 0 && Op1C->equalsInt(1)) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001507 static unsigned const DECTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
Chris Lattneree352852004-02-29 07:22:16 +00001508 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001509 return;
1510 }
1511
1512 static const unsigned OpcodeTab[][3] = {
1513 // Arithmetic operators
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001514 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri }, // ADD
1515 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri }, // SUB
Chris Lattnerb2acc512003-10-19 21:09:10 +00001516
1517 // Bitwise operators
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001518 { X86::AND8ri, X86::AND16ri, X86::AND32ri }, // AND
1519 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri }, // OR
1520 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri }, // XOR
Chris Lattnerb2acc512003-10-19 21:09:10 +00001521 };
1522
1523 assert(Class < 3 && "General code handles 64-bit integer types!");
1524 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1525 uint64_t Op1v = cast<ConstantInt>(Op1C)->getRawValue();
1526
1527 // Mask off any upper bits of the constant, if there are any...
1528 Op1v &= (1ULL << (8 << Class)) - 1;
Chris Lattneree352852004-02-29 07:22:16 +00001529 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1v);
Chris Lattnere2954c82002-11-02 20:04:26 +00001530}
1531
Chris Lattner3e130a22003-01-13 00:32:26 +00001532/// doMultiply - Emit appropriate instructions to multiply together the
1533/// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1534/// result should be given as DestTy.
1535///
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001536void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +00001537 unsigned DestReg, const Type *DestTy,
Chris Lattner8a307e82002-12-16 19:32:50 +00001538 unsigned op0Reg, unsigned op1Reg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001539 unsigned Class = getClass(DestTy);
Chris Lattner94af4142002-12-25 05:13:53 +00001540 switch (Class) {
1541 case cFP: // Floating point multiply
Chris Lattneree352852004-02-29 07:22:16 +00001542 BuildMI(*MBB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001543 return;
Chris Lattner0f1c4612003-06-21 17:16:58 +00001544 case cInt:
1545 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001546 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
Chris Lattner0f1c4612003-06-21 17:16:58 +00001547 .addReg(op0Reg).addReg(op1Reg);
1548 return;
1549 case cByte:
1550 // Must use the MUL instruction, which forces use of AL...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001551 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
1552 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
1553 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
Chris Lattner0f1c4612003-06-21 17:16:58 +00001554 return;
Chris Lattner94af4142002-12-25 05:13:53 +00001555 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00001556 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
Chris Lattner94af4142002-12-25 05:13:53 +00001557 }
Brian Gaeke20244b72002-12-12 15:33:40 +00001558}
1559
Chris Lattnerb2acc512003-10-19 21:09:10 +00001560// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1561// returns zero when the input is not exactly a power of two.
1562static unsigned ExactLog2(unsigned Val) {
1563 if (Val == 0) return 0;
1564 unsigned Count = 0;
1565 while (Val != 1) {
1566 if (Val & 1) return 0;
1567 Val >>= 1;
1568 ++Count;
1569 }
1570 return Count+1;
1571}
1572
1573void ISel::doMultiplyConst(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001574 MachineBasicBlock::iterator IP,
Chris Lattnerb2acc512003-10-19 21:09:10 +00001575 unsigned DestReg, const Type *DestTy,
1576 unsigned op0Reg, unsigned ConstRHS) {
1577 unsigned Class = getClass(DestTy);
1578
1579 // If the element size is exactly a power of 2, use a shift to get it.
1580 if (unsigned Shift = ExactLog2(ConstRHS)) {
1581 switch (Class) {
1582 default: assert(0 && "Unknown class for this function!");
1583 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001584 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001585 return;
1586 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001587 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001588 return;
1589 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001590 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001591 return;
1592 }
1593 }
Chris Lattnerc01d1232003-10-20 03:42:58 +00001594
1595 if (Class == cShort) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001596 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00001597 return;
1598 } else if (Class == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001599 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00001600 return;
1601 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001602
1603 // Most general case, emit a normal multiply...
Chris Lattner6e173a02004-02-17 06:16:44 +00001604 static const unsigned MOVriTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001605 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
Chris Lattnerb2acc512003-10-19 21:09:10 +00001606 };
1607
1608 unsigned TmpReg = makeAnotherReg(DestTy);
Chris Lattneree352852004-02-29 07:22:16 +00001609 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001610
1611 // Emit a MUL to multiply the register holding the index by
1612 // elementSize, putting the result in OffsetReg.
1613 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
1614}
1615
Chris Lattnerca9671d2002-11-02 20:28:58 +00001616/// visitMul - Multiplies are not simple binary operators because they must deal
1617/// with the EAX register explicitly.
1618///
1619void ISel::visitMul(BinaryOperator &I) {
Chris Lattner202a2d02002-12-13 13:07:42 +00001620 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattner3e130a22003-01-13 00:32:26 +00001621 unsigned DestReg = getReg(I);
1622
1623 // Simple scalar multiply?
1624 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
Chris Lattnerb2acc512003-10-19 21:09:10 +00001625 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1626 unsigned Val = (unsigned)CI->getRawValue(); // Cannot be 64-bit constant
1627 MachineBasicBlock::iterator MBBI = BB->end();
1628 doMultiplyConst(BB, MBBI, DestReg, I.getType(), Op0Reg, Val);
1629 } else {
1630 unsigned Op1Reg = getReg(I.getOperand(1));
1631 MachineBasicBlock::iterator MBBI = BB->end();
1632 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1633 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001634 } else {
Chris Lattnerb2acc512003-10-19 21:09:10 +00001635 unsigned Op1Reg = getReg(I.getOperand(1));
1636
Chris Lattner3e130a22003-01-13 00:32:26 +00001637 // Long value. We have to do things the hard way...
1638 // Multiply the two low parts... capturing carry into EDX
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001639 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
1640 BuildMI(BB, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
Chris Lattner3e130a22003-01-13 00:32:26 +00001641
1642 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001643 BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
1644 BuildMI(BB, X86::MOV32rr, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
Chris Lattner3e130a22003-01-13 00:32:26 +00001645
1646 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattner034acf02003-06-21 18:15:27 +00001647 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001648 BuildMI(*BB, MBBI, X86::IMUL32rr,2,AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001649
1650 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001651 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001652 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001653
1654 MBBI = BB->end();
Chris Lattner034acf02003-06-21 18:15:27 +00001655 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001656 BuildMI(*BB, MBBI, X86::IMUL32rr,2,ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00001657
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001658 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001659 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001660 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00001661}
Chris Lattnerca9671d2002-11-02 20:28:58 +00001662
Chris Lattner06925362002-11-17 21:56:38 +00001663
Chris Lattnerf01729e2002-11-02 20:54:46 +00001664/// visitDivRem - Handle division and remainder instructions... these
1665/// instruction both require the same instructions to be generated, they just
1666/// select the result from a different register. Note that both of these
1667/// instructions work differently for signed and unsigned operands.
1668///
1669void ISel::visitDivRem(BinaryOperator &I) {
Chris Lattnercadff442003-10-23 17:21:43 +00001670 unsigned Op0Reg = getReg(I.getOperand(0));
1671 unsigned Op1Reg = getReg(I.getOperand(1));
1672 unsigned ResultReg = getReg(I);
Chris Lattner94af4142002-12-25 05:13:53 +00001673
Chris Lattnercadff442003-10-23 17:21:43 +00001674 MachineBasicBlock::iterator IP = BB->end();
1675 emitDivRemOperation(BB, IP, Op0Reg, Op1Reg, I.getOpcode() == Instruction::Div,
1676 I.getType(), ResultReg);
1677}
1678
1679void ISel::emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001680 MachineBasicBlock::iterator IP,
Chris Lattnercadff442003-10-23 17:21:43 +00001681 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
1682 const Type *Ty, unsigned ResultReg) {
1683 unsigned Class = getClass(Ty);
Chris Lattner94af4142002-12-25 05:13:53 +00001684 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001685 case cFP: // Floating point divide
Chris Lattnercadff442003-10-23 17:21:43 +00001686 if (isDiv) {
Chris Lattneree352852004-02-29 07:22:16 +00001687 BuildMI(*BB, IP, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001688 } else { // Floating point remainder...
Chris Lattner3e130a22003-01-13 00:32:26 +00001689 MachineInstr *TheCall =
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001690 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00001691 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00001692 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1693 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00001694 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1695 }
Chris Lattner94af4142002-12-25 05:13:53 +00001696 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00001697 case cLong: {
1698 static const char *FnName[] =
1699 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1700
Chris Lattnercadff442003-10-23 17:21:43 +00001701 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
Chris Lattner3e130a22003-01-13 00:32:26 +00001702 MachineInstr *TheCall =
1703 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1704
1705 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00001706 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1707 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00001708 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1709 return;
1710 }
1711 case cByte: case cShort: case cInt:
Misha Brukmancf00c4a2003-10-10 17:57:28 +00001712 break; // Small integrals, handled below...
Chris Lattner3e130a22003-01-13 00:32:26 +00001713 default: assert(0 && "Unknown class!");
Chris Lattner94af4142002-12-25 05:13:53 +00001714 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00001715
1716 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001717 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
1718 static const unsigned SarOpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
1719 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
Chris Lattnerf01729e2002-11-02 20:54:46 +00001720 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1721
1722 static const unsigned DivOpcode[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001723 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
1724 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
Chris Lattnerf01729e2002-11-02 20:54:46 +00001725 };
1726
Chris Lattnercadff442003-10-23 17:21:43 +00001727 bool isSigned = Ty->isSigned();
Chris Lattnerf01729e2002-11-02 20:54:46 +00001728 unsigned Reg = Regs[Class];
1729 unsigned ExtReg = ExtRegs[Class];
Chris Lattnerf01729e2002-11-02 20:54:46 +00001730
1731 // Put the first operand into one of the A registers...
Chris Lattneree352852004-02-29 07:22:16 +00001732 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00001733
1734 if (isSigned) {
1735 // Emit a sign extension instruction...
Chris Lattnercadff442003-10-23 17:21:43 +00001736 unsigned ShiftResult = makeAnotherReg(Ty);
Chris Lattneree352852004-02-29 07:22:16 +00001737 BuildMI(*BB, IP, SarOpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
1738 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
Chris Lattnerf01729e2002-11-02 20:54:46 +00001739 } else {
Alkis Evlogimenosf998a7e2004-01-12 07:22:45 +00001740 // If unsigned, emit a zeroing instruction... (reg = 0)
Chris Lattneree352852004-02-29 07:22:16 +00001741 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
Chris Lattnerf01729e2002-11-02 20:54:46 +00001742 }
1743
Chris Lattner06925362002-11-17 21:56:38 +00001744 // Emit the appropriate divide or remainder instruction...
Chris Lattneree352852004-02-29 07:22:16 +00001745 BuildMI(*BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
Chris Lattner06925362002-11-17 21:56:38 +00001746
Chris Lattnerf01729e2002-11-02 20:54:46 +00001747 // Figure out which register we want to pick the result out of...
Chris Lattnercadff442003-10-23 17:21:43 +00001748 unsigned DestReg = isDiv ? Reg : ExtReg;
Chris Lattnerf01729e2002-11-02 20:54:46 +00001749
Chris Lattnerf01729e2002-11-02 20:54:46 +00001750 // Put the result into the destination register...
Chris Lattneree352852004-02-29 07:22:16 +00001751 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +00001752}
Chris Lattnere2954c82002-11-02 20:04:26 +00001753
Chris Lattner06925362002-11-17 21:56:38 +00001754
Brian Gaekea1719c92002-10-31 23:03:59 +00001755/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1756/// for constant immediate shift values, and for constant immediate
1757/// shift values equal to 1. Even the general case is sort of special,
1758/// because the shift amount has to be in CL, not just any old register.
1759///
Chris Lattner3e130a22003-01-13 00:32:26 +00001760void ISel::visitShiftInst(ShiftInst &I) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00001761 MachineBasicBlock::iterator IP = BB->end ();
1762 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
1763 I.getOpcode () == Instruction::Shl, I.getType (),
1764 getReg (I));
1765}
1766
1767/// emitShiftOperation - Common code shared between visitShiftInst and
1768/// constant expression support.
1769void ISel::emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001770 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00001771 Value *Op, Value *ShiftAmount, bool isLeftShift,
1772 const Type *ResultTy, unsigned DestReg) {
1773 unsigned SrcReg = getReg (Op, MBB, IP);
1774 bool isSigned = ResultTy->isSigned ();
1775 unsigned Class = getClass (ResultTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00001776
1777 static const unsigned ConstantOperand[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001778 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 }, // SHR
1779 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 }, // SAR
1780 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SHL
1781 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00001782 };
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001783
Chris Lattner3e130a22003-01-13 00:32:26 +00001784 static const unsigned NonConstantOperand[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001785 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
1786 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
1787 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
1788 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00001789 };
Chris Lattner796df732002-11-02 00:44:25 +00001790
Chris Lattner3e130a22003-01-13 00:32:26 +00001791 // Longs, as usual, are handled specially...
1792 if (Class == cLong) {
1793 // If we have a constant shift, we can generate much more efficient code
1794 // than otherwise...
1795 //
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00001796 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001797 unsigned Amount = CUI->getValue();
1798 if (Amount < 32) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001799 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1800 if (isLeftShift) {
Chris Lattneree352852004-02-29 07:22:16 +00001801 BuildMI(*MBB, IP, Opc[3], 3,
1802 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
1803 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001804 } else {
Chris Lattneree352852004-02-29 07:22:16 +00001805 BuildMI(*MBB, IP, Opc[3], 3,
1806 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
1807 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001808 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001809 } else { // Shifting more than 32 bits
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001810 Amount -= 32;
1811 if (isLeftShift) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001812 BuildMI(*MBB, IP, X86::SHL32ri, 2,
Chris Lattneree352852004-02-29 07:22:16 +00001813 DestReg + 1).addReg(SrcReg).addImm(Amount);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001814 BuildMI(*MBB, IP, X86::MOV32ri, 1,
Chris Lattneree352852004-02-29 07:22:16 +00001815 DestReg).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001816 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001817 unsigned Opcode = isSigned ? X86::SAR32ri : X86::SHR32ri;
Chris Lattneree352852004-02-29 07:22:16 +00001818 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(SrcReg+1).addImm(Amount);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001819 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001820 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001821 }
1822 } else {
Chris Lattner9171ef52003-06-01 01:56:54 +00001823 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1824
1825 if (!isLeftShift && isSigned) {
1826 // If this is a SHR of a Long, then we need to do funny sign extension
1827 // stuff. TmpReg gets the value to use as the high-part if we are
1828 // shifting more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001829 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
Chris Lattner9171ef52003-06-01 01:56:54 +00001830 } else {
1831 // Other shifts use a fixed zero value if the shift is more than 32
1832 // bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001833 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
Chris Lattner9171ef52003-06-01 01:56:54 +00001834 }
1835
1836 // Initialize CL with the shift amount...
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00001837 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001838 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00001839
1840 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1841 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
1842 if (isLeftShift) {
1843 // TmpReg2 = shld inHi, inLo
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001844 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
Chris Lattneree352852004-02-29 07:22:16 +00001845 .addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00001846 // TmpReg3 = shl inLo, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001847 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00001848
1849 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001850 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00001851
1852 // DestHi = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001853 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00001854 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
1855 // DestLo = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001856 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00001857 DestReg).addReg(TmpReg3).addReg(TmpReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00001858 } else {
1859 // TmpReg2 = shrd inLo, inHi
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001860 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
Chris Lattneree352852004-02-29 07:22:16 +00001861 .addReg(SrcReg+1);
Chris Lattner9171ef52003-06-01 01:56:54 +00001862 // TmpReg3 = s[ah]r inHi, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001863 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
Chris Lattner9171ef52003-06-01 01:56:54 +00001864 .addReg(SrcReg+1);
1865
1866 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001867 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00001868
1869 // DestLo = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001870 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00001871 DestReg).addReg(TmpReg2).addReg(TmpReg3);
1872
1873 // DestHi = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001874 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00001875 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
1876 }
Brian Gaekea1719c92002-10-31 23:03:59 +00001877 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001878 return;
1879 }
Chris Lattnere9913f22002-11-02 01:41:55 +00001880
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00001881 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001882 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1883 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001884
Chris Lattner3e130a22003-01-13 00:32:26 +00001885 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00001886 BuildMI(*MBB, IP, Opc[Class], 2,
1887 DestReg).addReg(SrcReg).addImm(CUI->getValue());
Chris Lattner3e130a22003-01-13 00:32:26 +00001888 } else { // The shift amount is non-constant.
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00001889 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001890 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001891
Chris Lattner3e130a22003-01-13 00:32:26 +00001892 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00001893 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001894 }
1895}
Chris Lattnerb1761fc2002-11-02 01:15:18 +00001896
Chris Lattner3e130a22003-01-13 00:32:26 +00001897
Chris Lattner6fc3c522002-11-17 21:11:55 +00001898/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
Chris Lattnere8f0d922002-12-24 00:03:11 +00001899/// instruction. The load and store instructions are the only place where we
1900/// need to worry about the memory layout of the target machine.
Chris Lattner6fc3c522002-11-17 21:11:55 +00001901///
1902void ISel::visitLoadInst(LoadInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +00001903 unsigned DestReg = getReg(I);
Chris Lattnerb6bac512004-02-25 06:13:04 +00001904 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
1905 Value *Addr = I.getOperand(0);
1906 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
1907 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
1908 BaseReg, Scale, IndexReg, Disp))
1909 Addr = 0; // Address is consumed!
1910 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
1911 if (CE->getOpcode() == Instruction::GetElementPtr)
1912 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
1913 BaseReg, Scale, IndexReg, Disp))
1914 Addr = 0;
1915 }
1916
1917 if (Addr) {
1918 // If it's not foldable, reset addr mode.
1919 BaseReg = getReg(Addr);
1920 Scale = 1; IndexReg = 0; Disp = 0;
1921 }
Chris Lattnere8f0d922002-12-24 00:03:11 +00001922
Brian Gaekebfedb912003-07-17 21:30:06 +00001923 unsigned Class = getClassB(I.getType());
Chris Lattner6ac1d712003-10-20 04:48:06 +00001924 if (Class == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001925 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
Chris Lattnerb6bac512004-02-25 06:13:04 +00001926 BaseReg, Scale, IndexReg, Disp);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001927 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
Chris Lattnerb6bac512004-02-25 06:13:04 +00001928 BaseReg, Scale, IndexReg, Disp+4);
Chris Lattner94af4142002-12-25 05:13:53 +00001929 return;
1930 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00001931
Chris Lattner6ac1d712003-10-20 04:48:06 +00001932 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001933 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m
Chris Lattner3e130a22003-01-13 00:32:26 +00001934 };
Chris Lattner6ac1d712003-10-20 04:48:06 +00001935 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001936 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
Chris Lattnerb6bac512004-02-25 06:13:04 +00001937 addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
1938 BaseReg, Scale, IndexReg, Disp);
Chris Lattner3e130a22003-01-13 00:32:26 +00001939}
1940
Chris Lattner6fc3c522002-11-17 21:11:55 +00001941/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1942/// instruction.
1943///
1944void ISel::visitStoreInst(StoreInst &I) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00001945 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
1946 Value *Addr = I.getOperand(1);
1947 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
1948 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
1949 BaseReg, Scale, IndexReg, Disp))
1950 Addr = 0; // Address is consumed!
1951 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
1952 if (CE->getOpcode() == Instruction::GetElementPtr)
1953 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
1954 BaseReg, Scale, IndexReg, Disp))
1955 Addr = 0;
1956 }
1957
1958 if (Addr) {
1959 // If it's not foldable, reset addr mode.
1960 BaseReg = getReg(Addr);
1961 Scale = 1; IndexReg = 0; Disp = 0;
1962 }
1963
Chris Lattner6c09db22003-10-20 04:11:23 +00001964 const Type *ValTy = I.getOperand(0)->getType();
1965 unsigned Class = getClassB(ValTy);
Chris Lattner6ac1d712003-10-20 04:48:06 +00001966
Chris Lattner5a830962004-02-25 02:56:58 +00001967 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
1968 uint64_t Val = CI->getRawValue();
1969 if (Class == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001970 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00001971 BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001972 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00001973 BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
Chris Lattner5a830962004-02-25 02:56:58 +00001974 } else {
1975 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001976 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
Chris Lattner5a830962004-02-25 02:56:58 +00001977 };
1978 unsigned Opcode = Opcodes[Class];
Chris Lattnerb6bac512004-02-25 06:13:04 +00001979 addFullAddress(BuildMI(BB, Opcode, 5),
Chris Lattneree352852004-02-29 07:22:16 +00001980 BaseReg, Scale, IndexReg, Disp).addImm(Val);
Chris Lattner5a830962004-02-25 02:56:58 +00001981 }
1982 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001983 addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00001984 BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
Chris Lattner5a830962004-02-25 02:56:58 +00001985 } else {
1986 if (Class == cLong) {
1987 unsigned ValReg = getReg(I.getOperand(0));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001988 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
Chris Lattnerb6bac512004-02-25 06:13:04 +00001989 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001990 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
Chris Lattnerb6bac512004-02-25 06:13:04 +00001991 BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
Chris Lattner5a830962004-02-25 02:56:58 +00001992 } else {
1993 unsigned ValReg = getReg(I.getOperand(0));
1994 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001995 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
Chris Lattner5a830962004-02-25 02:56:58 +00001996 };
1997 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001998 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
Chris Lattnerb6bac512004-02-25 06:13:04 +00001999 addFullAddress(BuildMI(BB, Opcode, 1+4),
2000 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
Chris Lattner5a830962004-02-25 02:56:58 +00002001 }
Chris Lattner94af4142002-12-25 05:13:53 +00002002 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00002003}
2004
2005
Brian Gaekec11232a2002-11-26 10:43:30 +00002006/// visitCastInst - Here we have various kinds of copying with or without
2007/// sign extension going on.
Chris Lattner3e130a22003-01-13 00:32:26 +00002008void ISel::visitCastInst(CastInst &CI) {
Chris Lattnerf5854472003-06-21 16:01:24 +00002009 Value *Op = CI.getOperand(0);
2010 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2011 // of the case are GEP instructions, then the cast does not need to be
2012 // generated explicitly, it will be folded into the GEP.
2013 if (CI.getType() == Type::LongTy &&
2014 (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
2015 bool AllUsesAreGEPs = true;
2016 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2017 if (!isa<GetElementPtrInst>(*I)) {
2018 AllUsesAreGEPs = false;
2019 break;
2020 }
2021
2022 // No need to codegen this cast if all users are getelementptr instrs...
2023 if (AllUsesAreGEPs) return;
2024 }
2025
Chris Lattner548f61d2003-04-23 17:22:12 +00002026 unsigned DestReg = getReg(CI);
2027 MachineBasicBlock::iterator MI = BB->end();
Chris Lattnerf5854472003-06-21 16:01:24 +00002028 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
Chris Lattner548f61d2003-04-23 17:22:12 +00002029}
2030
2031/// emitCastOperation - Common code shared between visitCastInst and
2032/// constant expression cast support.
2033void ISel::emitCastOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002034 MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +00002035 Value *Src, const Type *DestTy,
2036 unsigned DestReg) {
Chris Lattner3907d112003-04-23 17:57:48 +00002037 unsigned SrcReg = getReg(Src, BB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00002038 const Type *SrcTy = Src->getType();
2039 unsigned SrcClass = getClassB(SrcTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00002040 unsigned DestClass = getClassB(DestTy);
Chris Lattner7d255892002-12-13 11:31:59 +00002041
Chris Lattner3e130a22003-01-13 00:32:26 +00002042 // Implement casts to bool by using compare on the operand followed by set if
2043 // not zero on the result.
2044 if (DestTy == Type::BoolTy) {
Chris Lattner20772542003-06-01 03:38:24 +00002045 switch (SrcClass) {
2046 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002047 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002048 break;
2049 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002050 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002051 break;
2052 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002053 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002054 break;
2055 case cLong: {
2056 unsigned TmpReg = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002057 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
Chris Lattner20772542003-06-01 03:38:24 +00002058 break;
2059 }
2060 case cFP:
Chris Lattneree352852004-02-29 07:22:16 +00002061 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002062 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +00002063 BuildMI(*BB, IP, X86::SAHF, 1);
Chris Lattner311ca2e2004-02-23 03:21:41 +00002064 break;
Chris Lattner20772542003-06-01 03:38:24 +00002065 }
2066
2067 // If the zero flag is not set, then the value is true, set the byte to
2068 // true.
Chris Lattneree352852004-02-29 07:22:16 +00002069 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
Chris Lattner94af4142002-12-25 05:13:53 +00002070 return;
2071 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002072
2073 static const unsigned RegRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002074 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
Chris Lattner3e130a22003-01-13 00:32:26 +00002075 };
2076
2077 // Implement casts between values of the same type class (as determined by
2078 // getClass) by using a register-to-register move.
2079 if (SrcClass == DestClass) {
2080 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
Chris Lattneree352852004-02-29 07:22:16 +00002081 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002082 } else if (SrcClass == cFP) {
2083 if (SrcTy == Type::FloatTy) { // double -> float
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002084 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
Chris Lattneree352852004-02-29 07:22:16 +00002085 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002086 } else { // float -> double
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002087 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2088 "Unknown cFP member!");
2089 // Truncate from double to float by storing to memory as short, then
2090 // reading it back.
2091 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
Chris Lattner3e130a22003-01-13 00:32:26 +00002092 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002093 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
2094 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002095 }
2096 } else if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002097 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2098 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00002099 } else {
Chris Lattnerc53544a2003-05-12 20:16:58 +00002100 assert(0 && "Cannot handle this type of cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00002101 abort();
Brian Gaeked474e9c2002-12-06 10:49:33 +00002102 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002103 return;
2104 }
2105
2106 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2107 // or zero extension, depending on whether the source type was signed.
2108 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2109 SrcClass < DestClass) {
2110 bool isLong = DestClass == cLong;
2111 if (isLong) DestClass = cInt;
2112
2113 static const unsigned Opc[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002114 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
2115 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
Chris Lattner3e130a22003-01-13 00:32:26 +00002116 };
2117
2118 bool isUnsigned = SrcTy->isUnsigned();
Chris Lattneree352852004-02-29 07:22:16 +00002119 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
Chris Lattner548f61d2003-04-23 17:22:12 +00002120 DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002121
2122 if (isLong) { // Handle upper 32 bits as appropriate...
2123 if (isUnsigned) // Zero out top bits...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002124 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00002125 else // Sign extend bottom half...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002126 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
Brian Gaeked474e9c2002-12-06 10:49:33 +00002127 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002128 return;
2129 }
2130
2131 // Special case long -> int ...
2132 if (SrcClass == cLong && DestClass == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002133 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002134 return;
2135 }
2136
2137 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
2138 // move out of AX or AL.
2139 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2140 && SrcClass > DestClass) {
2141 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
Chris Lattneree352852004-02-29 07:22:16 +00002142 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
2143 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
Chris Lattner3e130a22003-01-13 00:32:26 +00002144 return;
2145 }
2146
2147 // Handle casts from integer to floating point now...
2148 if (DestClass == cFP) {
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002149 // Promote the integer to a type supported by FLD. We do this because there
2150 // are no unsigned FLD instructions, so we must promote an unsigned value to
2151 // a larger signed value, then use FLD on the larger value.
2152 //
2153 const Type *PromoteType = 0;
2154 unsigned PromoteOpcode;
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002155 unsigned RealDestReg = DestReg;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002156 switch (SrcTy->getPrimitiveID()) {
2157 case Type::BoolTyID:
2158 case Type::SByteTyID:
2159 // We don't have the facilities for directly loading byte sized data from
2160 // memory (even signed). Promote it to 16 bits.
2161 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002162 PromoteOpcode = X86::MOVSX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002163 break;
2164 case Type::UByteTyID:
2165 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002166 PromoteOpcode = X86::MOVZX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002167 break;
2168 case Type::UShortTyID:
2169 PromoteType = Type::IntTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002170 PromoteOpcode = X86::MOVZX32rr16;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002171 break;
2172 case Type::UIntTyID: {
2173 // Make a 64 bit temporary... and zero out the top of it...
2174 unsigned TmpReg = makeAnotherReg(Type::LongTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002175 BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
2176 BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002177 SrcTy = Type::LongTy;
2178 SrcClass = cLong;
2179 SrcReg = TmpReg;
2180 break;
2181 }
2182 case Type::ULongTyID:
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002183 // Don't fild into the read destination.
2184 DestReg = makeAnotherReg(Type::DoubleTy);
2185 break;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002186 default: // No promotion needed...
2187 break;
2188 }
2189
2190 if (PromoteType) {
2191 unsigned TmpReg = makeAnotherReg(PromoteType);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002192 unsigned Opc = SrcTy->isSigned() ? X86::MOVSX16rr8 : X86::MOVZX16rr8;
Chris Lattneree352852004-02-29 07:22:16 +00002193 BuildMI(*BB, IP, Opc, 1, TmpReg).addReg(SrcReg);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002194 SrcTy = PromoteType;
2195 SrcClass = getClass(PromoteType);
Chris Lattner3e130a22003-01-13 00:32:26 +00002196 SrcReg = TmpReg;
2197 }
2198
2199 // Spill the integer to memory and reload it from there...
Chris Lattnerb6bac512004-02-25 06:13:04 +00002200 int FrameIdx =
2201 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
Chris Lattner3e130a22003-01-13 00:32:26 +00002202
2203 if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002204 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002205 FrameIdx).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002206 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002207 FrameIdx, 4).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00002208 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002209 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
Chris Lattneree352852004-02-29 07:22:16 +00002210 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
2211 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002212 }
2213
2214 static const unsigned Op2[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002215 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
Chris Lattneree352852004-02-29 07:22:16 +00002216 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002217
2218 // We need special handling for unsigned 64-bit integer sources. If the
2219 // input number has the "sign bit" set, then we loaded it incorrectly as a
2220 // negative 64-bit number. In this case, add an offset value.
2221 if (SrcTy == Type::ULongTy) {
2222 // Emit a test instruction to see if the dynamic input value was signed.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002223 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002224
Chris Lattnerb6bac512004-02-25 06:13:04 +00002225 // If the sign bit is set, get a pointer to an offset, otherwise get a
2226 // pointer to a zero.
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002227 MachineConstantPool *CP = F->getConstantPool();
2228 unsigned Zero = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002229 Constant *Null = Constant::getNullValue(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002230 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002231 CP->getConstantPoolIndex(Null));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002232 unsigned Offset = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002233 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
2234
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002235 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002236 CP->getConstantPoolIndex(OffsetCst));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002237 unsigned Addr = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002238 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002239
2240 // Load the constant for an add. FIXME: this could make an 'fadd' that
2241 // reads directly from memory, but we don't support these yet.
2242 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002243 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002244
Chris Lattneree352852004-02-29 07:22:16 +00002245 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
2246 .addReg(ConstReg).addReg(DestReg);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002247 }
2248
Chris Lattner3e130a22003-01-13 00:32:26 +00002249 return;
2250 }
2251
2252 // Handle casts from floating point to integer now...
2253 if (SrcClass == cFP) {
2254 // Change the floating point control register to use "round towards zero"
2255 // mode when truncating to an integer value.
2256 //
2257 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002258 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002259
2260 // Load the old value of the high byte of the control word...
2261 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002262 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
Chris Lattneree352852004-02-29 07:22:16 +00002263 CWFrameIdx, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +00002264
2265 // Set the high part to be round to zero...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002266 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002267 CWFrameIdx, 1).addImm(12);
Chris Lattner3e130a22003-01-13 00:32:26 +00002268
2269 // Reload the modified control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002270 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002271
2272 // Restore the memory image of control word to original value
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002273 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002274 CWFrameIdx, 1).addReg(HighPartOfCW);
Chris Lattner3e130a22003-01-13 00:32:26 +00002275
2276 // We don't have the facilities for directly storing byte sized data to
2277 // memory. Promote it to 16 bits. We also must promote unsigned values to
2278 // larger classes because we only have signed FP stores.
2279 unsigned StoreClass = DestClass;
2280 const Type *StoreTy = DestTy;
2281 if (StoreClass == cByte || DestTy->isUnsigned())
2282 switch (StoreClass) {
2283 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
2284 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
2285 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
Brian Gaeked4615052003-07-18 20:23:43 +00002286 // The following treatment of cLong may not be perfectly right,
2287 // but it survives chains of casts of the form
2288 // double->ulong->double.
2289 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
Chris Lattner3e130a22003-01-13 00:32:26 +00002290 default: assert(0 && "Unknown store class!");
2291 }
2292
2293 // Spill the integer to memory and reload it from there...
2294 int FrameIdx =
2295 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
2296
2297 static const unsigned Op1[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002298 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
Chris Lattneree352852004-02-29 07:22:16 +00002299 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
2300 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002301
2302 if (DestClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002303 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
2304 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
Chris Lattneree352852004-02-29 07:22:16 +00002305 FrameIdx, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +00002306 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002307 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
Chris Lattneree352852004-02-29 07:22:16 +00002308 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002309 }
2310
2311 // Reload the original control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002312 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002313 return;
2314 }
2315
Brian Gaeked474e9c2002-12-06 10:49:33 +00002316 // Anything we haven't handled already, we can't (yet) handle at all.
Chris Lattnerc53544a2003-05-12 20:16:58 +00002317 assert(0 && "Unhandled cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00002318 abort();
Brian Gaekefa8d5712002-11-22 11:07:01 +00002319}
Brian Gaekea1719c92002-10-31 23:03:59 +00002320
Chris Lattner73815062003-10-18 05:56:40 +00002321/// visitVANextInst - Implement the va_next instruction...
Chris Lattnereca195e2003-05-08 19:44:13 +00002322///
Chris Lattner73815062003-10-18 05:56:40 +00002323void ISel::visitVANextInst(VANextInst &I) {
2324 unsigned VAList = getReg(I.getOperand(0));
Chris Lattnereca195e2003-05-08 19:44:13 +00002325 unsigned DestReg = getReg(I);
2326
Chris Lattnereca195e2003-05-08 19:44:13 +00002327 unsigned Size;
Chris Lattner73815062003-10-18 05:56:40 +00002328 switch (I.getArgType()->getPrimitiveID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00002329 default:
2330 std::cerr << I;
Chris Lattner73815062003-10-18 05:56:40 +00002331 assert(0 && "Error: bad type for va_next instruction!");
Chris Lattnereca195e2003-05-08 19:44:13 +00002332 return;
2333 case Type::PointerTyID:
2334 case Type::UIntTyID:
2335 case Type::IntTyID:
2336 Size = 4;
Chris Lattnereca195e2003-05-08 19:44:13 +00002337 break;
2338 case Type::ULongTyID:
2339 case Type::LongTyID:
Chris Lattnereca195e2003-05-08 19:44:13 +00002340 case Type::DoubleTyID:
2341 Size = 8;
Chris Lattnereca195e2003-05-08 19:44:13 +00002342 break;
2343 }
2344
2345 // Increment the VAList pointer...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002346 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
Chris Lattner73815062003-10-18 05:56:40 +00002347}
Chris Lattnereca195e2003-05-08 19:44:13 +00002348
Chris Lattner73815062003-10-18 05:56:40 +00002349void ISel::visitVAArgInst(VAArgInst &I) {
2350 unsigned VAList = getReg(I.getOperand(0));
2351 unsigned DestReg = getReg(I);
2352
2353 switch (I.getType()->getPrimitiveID()) {
2354 default:
2355 std::cerr << I;
2356 assert(0 && "Error: bad type for va_next instruction!");
2357 return;
2358 case Type::PointerTyID:
2359 case Type::UIntTyID:
2360 case Type::IntTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002361 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00002362 break;
2363 case Type::ULongTyID:
2364 case Type::LongTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002365 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2366 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
Chris Lattner73815062003-10-18 05:56:40 +00002367 break;
2368 case Type::DoubleTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002369 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00002370 break;
2371 }
Chris Lattnereca195e2003-05-08 19:44:13 +00002372}
2373
2374
Chris Lattner3e130a22003-01-13 00:32:26 +00002375void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00002376 // If this GEP instruction will be folded into all of its users, we don't need
2377 // to explicitly calculate it!
2378 unsigned A, B, C, D;
2379 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
2380 // Check all of the users of the instruction to see if they are loads and
2381 // stores.
2382 bool AllWillFold = true;
2383 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
2384 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
2385 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
2386 cast<Instruction>(*UI)->getOperand(0) == &I) {
2387 AllWillFold = false;
2388 break;
2389 }
2390
2391 // If the instruction is foldable, and will be folded into all users, don't
2392 // emit it!
2393 if (AllWillFold) return;
2394 }
2395
Chris Lattner3e130a22003-01-13 00:32:26 +00002396 unsigned outputReg = getReg(I);
Chris Lattner827832c2004-02-22 17:05:38 +00002397 emitGEPOperation(BB, BB->end(), I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +00002398 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +00002399}
2400
Chris Lattner985fe3d2004-02-25 03:45:50 +00002401/// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
2402/// GEPTypes (the derived types being stepped through at each level). On return
2403/// from this function, if some indexes of the instruction are representable as
2404/// an X86 lea instruction, the machine operands are put into the Ops
2405/// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
2406/// lists. Otherwise, GEPOps.size() is returned. If this returns a an
2407/// addressing mode that only partially consumes the input, the BaseReg input of
2408/// the addressing mode must be left free.
2409///
2410/// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
2411///
Chris Lattnerb6bac512004-02-25 06:13:04 +00002412void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2413 std::vector<Value*> &GEPOps,
2414 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
2415 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2416 const TargetData &TD = TM.getTargetData();
2417
Chris Lattner985fe3d2004-02-25 03:45:50 +00002418 // Clear out the state we are working with...
Chris Lattnerb6bac512004-02-25 06:13:04 +00002419 BaseReg = 0; // No base register
2420 Scale = 1; // Unit scale
2421 IndexReg = 0; // No index register
2422 Disp = 0; // No displacement
2423
Chris Lattner985fe3d2004-02-25 03:45:50 +00002424 // While there are GEP indexes that can be folded into the current address,
2425 // keep processing them.
2426 while (!GEPTypes.empty()) {
2427 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2428 // It's a struct access. CUI is the index into the structure,
2429 // which names the field. This index must have unsigned type.
2430 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2431
2432 // Use the TargetData structure to pick out what the layout of the
2433 // structure is in memory. Since the structure index must be constant, we
2434 // can get its value and use it to find the right byte offset from the
2435 // StructLayout class's list of structure member offsets.
Chris Lattnerb6bac512004-02-25 06:13:04 +00002436 Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
Chris Lattner985fe3d2004-02-25 03:45:50 +00002437 GEPOps.pop_back(); // Consume a GEP operand
2438 GEPTypes.pop_back();
2439 } else {
2440 // It's an array or pointer access: [ArraySize x ElementType].
2441 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2442 Value *idx = GEPOps.back();
2443
2444 // idx is the index into the array. Unlike with structure
2445 // indices, we may not know its actual value at code-generation
2446 // time.
2447 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2448
2449 // If idx is a constant, fold it into the offset.
Chris Lattner5f2c7b12004-02-25 07:00:55 +00002450 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
Chris Lattner985fe3d2004-02-25 03:45:50 +00002451 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00002452 Disp += TypeSize*CSI->getValue();
Chris Lattner985fe3d2004-02-25 03:45:50 +00002453 } else {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00002454 // If the index reg is already taken, we can't handle this index.
2455 if (IndexReg) return;
2456
2457 // If this is a size that we can handle, then add the index as
2458 switch (TypeSize) {
2459 case 1: case 2: case 4: case 8:
2460 // These are all acceptable scales on X86.
2461 Scale = TypeSize;
2462 break;
2463 default:
2464 // Otherwise, we can't handle this scale
2465 return;
2466 }
2467
2468 if (CastInst *CI = dyn_cast<CastInst>(idx))
2469 if (CI->getOperand(0)->getType() == Type::IntTy ||
2470 CI->getOperand(0)->getType() == Type::UIntTy)
2471 idx = CI->getOperand(0);
2472
2473 IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
Chris Lattner985fe3d2004-02-25 03:45:50 +00002474 }
2475
2476 GEPOps.pop_back(); // Consume a GEP operand
2477 GEPTypes.pop_back();
2478 }
2479 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00002480
2481 // GEPTypes is empty, which means we have a single operand left. See if we
2482 // can set it as the base register.
2483 //
2484 // FIXME: When addressing modes are more powerful/correct, we could load
2485 // global addresses directly as 32-bit immediates.
2486 assert(BaseReg == 0);
Chris Lattner5f2c7b12004-02-25 07:00:55 +00002487 BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
Chris Lattnerb6bac512004-02-25 06:13:04 +00002488 GEPOps.pop_back(); // Consume the last GEP operand
Chris Lattner985fe3d2004-02-25 03:45:50 +00002489}
2490
2491
Chris Lattnerb6bac512004-02-25 06:13:04 +00002492/// isGEPFoldable - Return true if the specified GEP can be completely
2493/// folded into the addressing mode of a load/store or lea instruction.
2494bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
2495 Value *Src, User::op_iterator IdxBegin,
2496 User::op_iterator IdxEnd, unsigned &BaseReg,
2497 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
Chris Lattner7ca04092004-02-22 17:35:42 +00002498 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2499 Src = CPR->getValue();
2500
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002501 std::vector<Value*> GEPOps;
2502 GEPOps.resize(IdxEnd-IdxBegin+1);
2503 GEPOps[0] = Src;
2504 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2505
2506 std::vector<const Type*> GEPTypes;
2507 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2508 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2509
Chris Lattnerb6bac512004-02-25 06:13:04 +00002510 MachineBasicBlock::iterator IP;
2511 if (MBB) IP = MBB->end();
2512 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2513
2514 // We can fold it away iff the getGEPIndex call eliminated all operands.
2515 return GEPOps.empty();
2516}
2517
2518void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2519 MachineBasicBlock::iterator IP,
2520 Value *Src, User::op_iterator IdxBegin,
2521 User::op_iterator IdxEnd, unsigned TargetReg) {
2522 const TargetData &TD = TM.getTargetData();
2523 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2524 Src = CPR->getValue();
2525
2526 std::vector<Value*> GEPOps;
2527 GEPOps.resize(IdxEnd-IdxBegin+1);
2528 GEPOps[0] = Src;
2529 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2530
2531 std::vector<const Type*> GEPTypes;
2532 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2533 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
Chris Lattner985fe3d2004-02-25 03:45:50 +00002534
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002535 // Keep emitting instructions until we consume the entire GEP instruction.
2536 while (!GEPOps.empty()) {
2537 unsigned OldSize = GEPOps.size();
Chris Lattnerb6bac512004-02-25 06:13:04 +00002538 unsigned BaseReg, Scale, IndexReg, Disp;
2539 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002540
Chris Lattner985fe3d2004-02-25 03:45:50 +00002541 if (GEPOps.size() != OldSize) {
2542 // getGEPIndex consumed some of the input. Build an LEA instruction here.
Chris Lattnerb6bac512004-02-25 06:13:04 +00002543 unsigned NextTarget = 0;
2544 if (!GEPOps.empty()) {
2545 assert(BaseReg == 0 &&
2546 "getGEPIndex should have left the base register open for chaining!");
2547 NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
Chris Lattner985fe3d2004-02-25 03:45:50 +00002548 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00002549
2550 if (IndexReg == 0 && Disp == 0)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002551 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002552 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002553 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002554 BaseReg, Scale, IndexReg, Disp);
2555 --IP;
2556 TargetReg = NextTarget;
Chris Lattner985fe3d2004-02-25 03:45:50 +00002557 } else if (GEPTypes.empty()) {
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002558 // The getGEPIndex operation didn't want to build an LEA. Check to see if
2559 // all operands are consumed but the base pointer. If so, just load it
2560 // into the register.
Chris Lattner7ca04092004-02-22 17:35:42 +00002561 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002562 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
Chris Lattner7ca04092004-02-22 17:35:42 +00002563 } else {
2564 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002565 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattner7ca04092004-02-22 17:35:42 +00002566 }
2567 break; // we are now done
Chris Lattnerb6bac512004-02-25 06:13:04 +00002568
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002569 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +00002570 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002571 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2572 Value *idx = GEPOps.back();
2573 GEPOps.pop_back(); // Consume a GEP operand
2574 GEPTypes.pop_back();
Chris Lattner8a307e82002-12-16 19:32:50 +00002575
Brian Gaeke20244b72002-12-12 15:33:40 +00002576 // idx is the index into the array. Unlike with structure
2577 // indices, we may not know its actual value at code-generation
2578 // time.
Chris Lattner8a307e82002-12-16 19:32:50 +00002579 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2580
Chris Lattnerf5854472003-06-21 16:01:24 +00002581 // Most GEP instructions use a [cast (int/uint) to LongTy] as their
2582 // operand on X86. Handle this case directly now...
2583 if (CastInst *CI = dyn_cast<CastInst>(idx))
2584 if (CI->getOperand(0)->getType() == Type::IntTy ||
2585 CI->getOperand(0)->getType() == Type::UIntTy)
2586 idx = CI->getOperand(0);
2587
Chris Lattner3e130a22003-01-13 00:32:26 +00002588 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
Chris Lattner8a307e82002-12-16 19:32:50 +00002589 // must find the size of the pointed-to type (Not coincidentally, the next
2590 // type is the type of the elements in the array).
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002591 const Type *ElTy = SqTy->getElementType();
2592 unsigned elementSize = TD.getTypeSize(ElTy);
Chris Lattner8a307e82002-12-16 19:32:50 +00002593
2594 // If idxReg is a constant, we don't need to perform the multiply!
2595 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002596 if (!CSI->isNullValue()) {
Chris Lattner8a307e82002-12-16 19:32:50 +00002597 unsigned Offset = elementSize*CSI->getValue();
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002598 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002599 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00002600 .addReg(Reg).addImm(Offset);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002601 --IP; // Insert the next instruction before this one.
2602 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00002603 }
2604 } else if (elementSize == 1) {
2605 // If the element size is 1, we don't have to multiply, just add
2606 unsigned idxReg = getReg(idx, MBB, IP);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002607 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002608 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002609 --IP; // Insert the next instruction before this one.
2610 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00002611 } else {
2612 unsigned idxReg = getReg(idx, MBB, IP);
2613 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002614
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002615 // Make sure we can back the iterator up to point to the first
2616 // instruction emitted.
2617 MachineBasicBlock::iterator BeforeIt = IP;
2618 if (IP == MBB->begin())
2619 BeforeIt = MBB->end();
2620 else
2621 --BeforeIt;
Chris Lattnerb2acc512003-10-19 21:09:10 +00002622 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2623
Chris Lattner8a307e82002-12-16 19:32:50 +00002624 // Emit an ADD to add OffsetReg to the basePtr.
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002625 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002626 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00002627 .addReg(Reg).addReg(OffsetReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00002628
2629 // Step to the first instruction of the multiply.
2630 if (BeforeIt == MBB->end())
2631 IP = MBB->begin();
2632 else
2633 IP = ++BeforeIt;
2634
2635 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00002636 }
Brian Gaeke20244b72002-12-12 15:33:40 +00002637 }
Brian Gaeke20244b72002-12-12 15:33:40 +00002638 }
Brian Gaeke20244b72002-12-12 15:33:40 +00002639}
2640
2641
Chris Lattner065faeb2002-12-28 20:24:02 +00002642/// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2643/// frame manager, otherwise do it the hard way.
2644///
2645void ISel::visitAllocaInst(AllocaInst &I) {
Brian Gaekee48ec012002-12-13 06:46:31 +00002646 // Find the data size of the alloca inst's getAllocatedType.
Chris Lattner065faeb2002-12-28 20:24:02 +00002647 const Type *Ty = I.getAllocatedType();
2648 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2649
2650 // If this is a fixed size alloca in the entry block for the function,
2651 // statically stack allocate the space.
2652 //
2653 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
2654 if (I.getParent() == I.getParent()->getParent()->begin()) {
2655 TySize *= CUI->getValue(); // Get total allocated size...
2656 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
2657
2658 // Create a new stack object using the frame manager...
2659 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002660 addFrameReference(BuildMI(BB, X86::LEA32r, 5, getReg(I)), FrameIdx);
Chris Lattner065faeb2002-12-28 20:24:02 +00002661 return;
2662 }
2663 }
2664
2665 // Create a register to hold the temporary result of multiplying the type size
2666 // constant by the variable amount.
2667 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2668 unsigned SrcReg1 = getReg(I.getArraySize());
Chris Lattner065faeb2002-12-28 20:24:02 +00002669
2670 // TotalSizeReg = mul <numelements>, <TypeSize>
2671 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00002672 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
Chris Lattner065faeb2002-12-28 20:24:02 +00002673
2674 // AddedSize = add <TotalSizeReg>, 15
2675 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002676 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
Chris Lattner065faeb2002-12-28 20:24:02 +00002677
2678 // AlignedSize = and <AddedSize>, ~15
2679 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002680 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
Chris Lattner065faeb2002-12-28 20:24:02 +00002681
Brian Gaekee48ec012002-12-13 06:46:31 +00002682 // Subtract size from stack pointer, thereby allocating some space.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002683 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
Chris Lattner065faeb2002-12-28 20:24:02 +00002684
Brian Gaekee48ec012002-12-13 06:46:31 +00002685 // Put a pointer to the space into the result register, by copying
2686 // the stack pointer.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002687 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
Chris Lattner065faeb2002-12-28 20:24:02 +00002688
Misha Brukman48196b32003-05-03 02:18:17 +00002689 // Inform the Frame Information that we have just allocated a variable-sized
Chris Lattner065faeb2002-12-28 20:24:02 +00002690 // object.
2691 F->getFrameInfo()->CreateVariableSizedObject();
Brian Gaeke20244b72002-12-12 15:33:40 +00002692}
Chris Lattner3e130a22003-01-13 00:32:26 +00002693
2694/// visitMallocInst - Malloc instructions are code generated into direct calls
2695/// to the library malloc.
2696///
2697void ISel::visitMallocInst(MallocInst &I) {
2698 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2699 unsigned Arg;
2700
2701 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2702 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2703 } else {
2704 Arg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002705 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattner3e130a22003-01-13 00:32:26 +00002706 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00002707 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
Chris Lattner3e130a22003-01-13 00:32:26 +00002708 }
2709
2710 std::vector<ValueRecord> Args;
2711 Args.push_back(ValueRecord(Arg, Type::UIntTy));
2712 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002713 1).addExternalSymbol("malloc", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00002714 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
2715}
2716
2717
2718/// visitFreeInst - Free instructions are code gen'd to call the free libc
2719/// function.
2720///
2721void ISel::visitFreeInst(FreeInst &I) {
2722 std::vector<ValueRecord> Args;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00002723 Args.push_back(ValueRecord(I.getOperand(0)));
Chris Lattner3e130a22003-01-13 00:32:26 +00002724 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002725 1).addExternalSymbol("free", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00002726 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
2727}
2728
Chris Lattnerd281de22003-07-26 23:49:58 +00002729/// createX86SimpleInstructionSelector - This pass converts an LLVM function
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00002730/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00002731/// generated code sucks but the implementation is nice and simple.
2732///
Chris Lattnerf70e0c22003-12-28 21:23:38 +00002733FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
2734 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00002735}