blob: 9f41f070cbc4f1fdd3e719eebb53540472679c40 [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 Lattner986618e2004-02-22 19:47:26 +000031#include "Support/Statistic.h"
Chris Lattner44827152003-12-28 09:47:19 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Chris Lattner986618e2004-02-22 19:47:26 +000034namespace {
35 Statistic<>
36 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
Chris Lattner427aeb42004-04-11 19:21:59 +000037
38 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
39 /// Representation.
40 ///
41 enum TypeClass {
42 cByte, cShort, cInt, cFP, cLong
43 };
44}
45
46/// getClass - Turn a primitive type into a "class" number which is based on the
47/// size of the type, and whether or not it is floating point.
48///
49static inline TypeClass getClass(const Type *Ty) {
50 switch (Ty->getPrimitiveID()) {
51 case Type::SByteTyID:
52 case Type::UByteTyID: return cByte; // Byte operands are class #0
53 case Type::ShortTyID:
54 case Type::UShortTyID: return cShort; // Short operands are class #1
55 case Type::IntTyID:
56 case Type::UIntTyID:
57 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
58
59 case Type::FloatTyID:
60 case Type::DoubleTyID: return cFP; // Floating Point is #3
61
62 case Type::LongTyID:
63 case Type::ULongTyID: return cLong; // Longs are class #4
64 default:
65 assert(0 && "Invalid type to getClass!");
66 return cByte; // not reached
67 }
68}
69
70// getClassB - Just like getClass, but treat boolean values as bytes.
71static inline TypeClass getClassB(const Type *Ty) {
72 if (Ty == Type::BoolTy) return cByte;
73 return getClass(Ty);
Chris Lattner986618e2004-02-22 19:47:26 +000074}
Chris Lattnercf93cdd2004-01-30 22:13:44 +000075
Chris Lattner72614082002-10-25 22:55:53 +000076namespace {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000077 struct ISel : public FunctionPass, InstVisitor<ISel> {
78 TargetMachine &TM;
Chris Lattnereca195e2003-05-08 19:44:13 +000079 MachineFunction *F; // The function we are compiling into
80 MachineBasicBlock *BB; // The current MBB we are compiling
81 int VarArgsFrameIndex; // FrameIndex for start of varargs area
Chris Lattner0e5b79c2004-02-15 01:04:03 +000082 int ReturnAddressIndex; // FrameIndex for the return address
Chris Lattner72614082002-10-25 22:55:53 +000083
Chris Lattner72614082002-10-25 22:55:53 +000084 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
85
Chris Lattner333b2fa2002-12-13 10:09:43 +000086 // MBBMap - Mapping between LLVM BB -> Machine BB
87 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
88
Chris Lattnercb2fd552004-05-13 07:40:27 +000089 // AllocaMap - Mapping from fixed sized alloca instructions to the
90 // FrameIndex for the alloca.
91 std::map<AllocaInst*, unsigned> AllocaMap;
92
Chris Lattnerf70e0c22003-12-28 21:23:38 +000093 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
Chris Lattner72614082002-10-25 22:55:53 +000094
95 /// runOnFunction - Top level implementation of instruction selection for
96 /// the entire function.
97 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000098 bool runOnFunction(Function &Fn) {
Chris Lattner44827152003-12-28 09:47:19 +000099 // First pass over the function, lower any unknown intrinsic functions
100 // with the IntrinsicLowering class.
101 LowerUnknownIntrinsicFunctionCalls(Fn);
102
Chris Lattner36b36032002-10-29 23:40:58 +0000103 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000104
Chris Lattner065faeb2002-12-28 20:24:02 +0000105 // Create all of the machine basic blocks for the function...
Chris Lattner333b2fa2002-12-13 10:09:43 +0000106 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
107 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
108
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000109 BB = &F->front();
Chris Lattnerdbd73722003-05-06 21:32:22 +0000110
Chris Lattner0e5b79c2004-02-15 01:04:03 +0000111 // Set up a frame object for the return address. This is used by the
112 // llvm.returnaddress & llvm.frameaddress intrinisics.
113 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
114
Chris Lattnerdbd73722003-05-06 21:32:22 +0000115 // Copy incoming arguments off of the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000116 LoadArgumentsToVirtualRegs(Fn);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000117
Chris Lattner333b2fa2002-12-13 10:09:43 +0000118 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000119 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000120
121 // Select the PHI nodes
122 SelectPHINodes();
123
Chris Lattner986618e2004-02-22 19:47:26 +0000124 // Insert the FP_REG_KILL instructions into blocks that need them.
125 InsertFPRegKills();
126
Chris Lattner72614082002-10-25 22:55:53 +0000127 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000128 MBBMap.clear();
Chris Lattnercb2fd552004-05-13 07:40:27 +0000129 AllocaMap.clear();
Chris Lattnerb4f68ed2002-10-29 22:37:54 +0000130 F = 0;
Chris Lattner2a865b02003-07-26 23:05:37 +0000131 // We always build a machine code representation for the function
132 return true;
Chris Lattner72614082002-10-25 22:55:53 +0000133 }
134
Chris Lattnerf0eb7be2002-12-15 21:13:40 +0000135 virtual const char *getPassName() const {
136 return "X86 Simple Instruction Selection";
137 }
138
Chris Lattner72614082002-10-25 22:55:53 +0000139 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +0000140 /// block. This simply creates a new MachineBasicBlock to emit code into
141 /// and adds it to the current MachineFunction. Subsequent visit* for
142 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +0000143 ///
144 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000145 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +0000146 }
147
Chris Lattner44827152003-12-28 09:47:19 +0000148 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
149 /// function, lowering any calls to unknown intrinsic functions into the
150 /// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +0000151 ///
Chris Lattner44827152003-12-28 09:47:19 +0000152 void LowerUnknownIntrinsicFunctionCalls(Function &F);
153
Chris Lattner065faeb2002-12-28 20:24:02 +0000154 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
155 /// from the stack into virtual registers.
156 ///
157 void LoadArgumentsToVirtualRegs(Function &F);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000158
159 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
160 /// because we have to generate our sources into the source basic blocks,
161 /// not the current one.
162 ///
163 void SelectPHINodes();
164
Chris Lattner986618e2004-02-22 19:47:26 +0000165 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
166 /// that need them. This only occurs due to the floating point stackifier
167 /// not being aggressive enough to handle arbitrary global stackification.
168 ///
169 void InsertFPRegKills();
170
Chris Lattner72614082002-10-25 22:55:53 +0000171 // Visitation methods for various instructions. These methods simply emit
172 // fixed X86 code for each instruction.
173 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000174
175 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000176 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000177 void visitBranchInst(BranchInst &BI);
Chris Lattner3e130a22003-01-13 00:32:26 +0000178
179 struct ValueRecord {
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000180 Value *Val;
Chris Lattner3e130a22003-01-13 00:32:26 +0000181 unsigned Reg;
182 const Type *Ty;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000183 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
184 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
Chris Lattner3e130a22003-01-13 00:32:26 +0000185 };
186 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000187 const std::vector<ValueRecord> &Args);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000188 void visitCallInst(CallInst &I);
Brian Gaeked0fde302003-11-11 22:41:34 +0000189 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000190
191 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000192 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000193 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
194 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Chris Lattnerca9671d2002-11-02 20:28:58 +0000195 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000196
Chris Lattnerf01729e2002-11-02 20:54:46 +0000197 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
198 void visitRem(BinaryOperator &B) { visitDivRem(B); }
199 void visitDivRem(BinaryOperator &B);
200
Chris Lattnere2954c82002-11-02 20:04:26 +0000201 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000202 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
203 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
204 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000205
Chris Lattner6d40c192003-01-16 16:43:00 +0000206 // Comparison operators...
207 void visitSetCondInst(SetCondInst &I);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000208 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
209 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000210 MachineBasicBlock::iterator MBBI);
Chris Lattner12d96a02004-03-30 21:22:00 +0000211 void visitSelectInst(SelectInst &SI);
212
Chris Lattnerb2acc512003-10-19 21:09:10 +0000213
Chris Lattner6fc3c522002-11-17 21:11:55 +0000214 // Memory Instructions
215 void visitLoadInst(LoadInst &I);
216 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000217 void visitGetElementPtrInst(GetElementPtrInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000218 void visitAllocaInst(AllocaInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000219 void visitMallocInst(MallocInst &I);
220 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000221
Chris Lattnere2954c82002-11-02 20:04:26 +0000222 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000223 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000224 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000225 void visitCastInst(CastInst &I);
Chris Lattner73815062003-10-18 05:56:40 +0000226 void visitVANextInst(VANextInst &I);
227 void visitVAArgInst(VAArgInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000228
229 void visitInstruction(Instruction &I) {
230 std::cerr << "Cannot instruction select: " << I;
231 abort();
232 }
233
Brian Gaeke95780cc2002-12-13 07:56:18 +0000234 /// promote32 - Make a value 32-bits wide, and put it somewhere.
Chris Lattner3e130a22003-01-13 00:32:26 +0000235 ///
236 void promote32(unsigned targetReg, const ValueRecord &VR);
237
Chris Lattner721d2d42004-03-08 01:18:36 +0000238 /// getAddressingMode - Get the addressing mode to use to address the
239 /// specified value. The returned value should be used with addFullAddress.
240 void getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
241 unsigned &IndexReg, unsigned &Disp);
242
243
244 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
245 /// expressions.
Chris Lattnerb6bac512004-02-25 06:13:04 +0000246 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
247 std::vector<Value*> &GEPOps,
248 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
249 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
250
251 /// isGEPFoldable - Return true if the specified GEP can be completely
252 /// folded into the addressing mode of a load/store or lea instruction.
253 bool isGEPFoldable(MachineBasicBlock *MBB,
254 Value *Src, User::op_iterator IdxBegin,
255 User::op_iterator IdxEnd, unsigned &BaseReg,
256 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
257
Chris Lattner3e130a22003-01-13 00:32:26 +0000258 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
259 /// constant expression GEP support.
260 ///
Chris Lattner827832c2004-02-22 17:05:38 +0000261 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000262 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000263 User::op_iterator IdxEnd, unsigned TargetReg);
264
Chris Lattner548f61d2003-04-23 17:22:12 +0000265 /// emitCastOperation - Common code shared between visitCastInst and
266 /// constant expression cast support.
Misha Brukman538607f2004-03-01 23:53:11 +0000267 ///
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000268 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +0000269 Value *Src, const Type *DestTy, unsigned TargetReg);
270
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000271 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
272 /// and constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000273 ///
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000274 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000275 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000276 Value *Op0, Value *Op1,
277 unsigned OperatorClass, unsigned TargetReg);
278
Chris Lattner6621ed92004-04-11 21:23:56 +0000279 /// emitBinaryFPOperation - This method handles emission of floating point
280 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
281 void emitBinaryFPOperation(MachineBasicBlock *BB,
282 MachineBasicBlock::iterator IP,
283 Value *Op0, Value *Op1,
284 unsigned OperatorClass, unsigned TargetReg);
285
Chris Lattner462fa822004-04-11 20:56:28 +0000286 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
287 Value *Op0, Value *Op1, unsigned TargetReg);
288
289 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
290 unsigned DestReg, const Type *DestTy,
291 unsigned Op0Reg, unsigned Op1Reg);
292 void doMultiplyConst(MachineBasicBlock *MBB,
293 MachineBasicBlock::iterator MBBI,
294 unsigned DestReg, const Type *DestTy,
295 unsigned Op0Reg, unsigned Op1Val);
296
Chris Lattnercadff442003-10-23 17:21:43 +0000297 void emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000298 MachineBasicBlock::iterator IP,
Chris Lattner462fa822004-04-11 20:56:28 +0000299 Value *Op0, Value *Op1, bool isDiv,
300 unsigned TargetReg);
Chris Lattnercadff442003-10-23 17:21:43 +0000301
Chris Lattner58c41fe2003-08-24 19:19:47 +0000302 /// emitSetCCOperation - Common code shared between visitSetCondInst and
303 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000304 ///
Chris Lattner58c41fe2003-08-24 19:19:47 +0000305 void emitSetCCOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000306 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +0000307 Value *Op0, Value *Op1, unsigned Opcode,
308 unsigned TargetReg);
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000309
310 /// emitShiftOperation - Common code shared between visitShiftInst and
311 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000312 ///
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000313 void emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000314 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000315 Value *Op, Value *ShiftAmount, bool isLeftShift,
316 const Type *ResultTy, unsigned DestReg);
317
Chris Lattner12d96a02004-03-30 21:22:00 +0000318 /// emitSelectOperation - Common code shared between visitSelectInst and the
319 /// constant expression support.
320 void emitSelectOperation(MachineBasicBlock *MBB,
321 MachineBasicBlock::iterator IP,
322 Value *Cond, Value *TrueVal, Value *FalseVal,
323 unsigned DestReg);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000324
Chris Lattnerc5291f52002-10-27 21:16:59 +0000325 /// copyConstantToRegister - Output the instructions required to put the
326 /// specified constant into the specified register.
327 ///
Chris Lattner8a307e82002-12-16 19:32:50 +0000328 void copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000329 MachineBasicBlock::iterator MBBI,
Chris Lattner8a307e82002-12-16 19:32:50 +0000330 Constant *C, unsigned Reg);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000331
Chris Lattner3e130a22003-01-13 00:32:26 +0000332 /// makeAnotherReg - This method returns the next register number we haven't
333 /// yet used.
334 ///
335 /// Long values are handled somewhat specially. They are always allocated
336 /// as pairs of 32 bit integer values. The register number returned is the
337 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
338 /// of the long value.
339 ///
Chris Lattnerc0812d82002-12-13 06:56:29 +0000340 unsigned makeAnotherReg(const Type *Ty) {
Chris Lattner7db1fa92003-07-30 05:33:48 +0000341 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
342 "Current target doesn't have X86 reg info??");
343 const X86RegisterInfo *MRI =
344 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
Chris Lattner3e130a22003-01-13 00:32:26 +0000345 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000346 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
347 // Create the lower part
348 F->getSSARegMap()->createVirtualRegister(RC);
349 // Create the upper part.
350 return F->getSSARegMap()->createVirtualRegister(RC)-1;
Chris Lattner3e130a22003-01-13 00:32:26 +0000351 }
352
Chris Lattnerc0812d82002-12-13 06:56:29 +0000353 // Add the mapping of regnumber => reg class to MachineFunction
Chris Lattner7db1fa92003-07-30 05:33:48 +0000354 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
Chris Lattner3e130a22003-01-13 00:32:26 +0000355 return F->getSSARegMap()->createVirtualRegister(RC);
Brian Gaeke20244b72002-12-12 15:33:40 +0000356 }
357
Chris Lattnercb2fd552004-05-13 07:40:27 +0000358 /// getReg - This method turns an LLVM value into a register number.
Chris Lattner72614082002-10-25 22:55:53 +0000359 ///
360 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000361 unsigned getReg(Value *V) {
362 // Just append to the end of the current bb.
363 MachineBasicBlock::iterator It = BB->end();
364 return getReg(V, BB, It);
365 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000366 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnercb2fd552004-05-13 07:40:27 +0000367 MachineBasicBlock::iterator IPt);
Chris Lattner427aeb42004-04-11 19:21:59 +0000368
Chris Lattnercb2fd552004-05-13 07:40:27 +0000369 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
370 /// that is to be statically allocated with the initial stack frame
371 /// adjustment.
372 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
Chris Lattner72614082002-10-25 22:55:53 +0000373 };
374}
375
Chris Lattnercb2fd552004-05-13 07:40:27 +0000376/// dyn_castFixedAlloca - If the specified value is a fixed size alloca
377/// instruction in the entry block, return it. Otherwise, return a null
378/// pointer.
379static AllocaInst *dyn_castFixedAlloca(Value *V) {
380 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
381 BasicBlock *BB = AI->getParent();
382 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
383 return AI;
384 }
385 return 0;
386}
387
388/// getReg - This method turns an LLVM value into a register number.
389///
390unsigned ISel::getReg(Value *V, MachineBasicBlock *MBB,
391 MachineBasicBlock::iterator IPt) {
392 // If this operand is a constant, emit the code to copy the constant into
393 // the register here...
394 //
395 if (Constant *C = dyn_cast<Constant>(V)) {
396 unsigned Reg = makeAnotherReg(V->getType());
397 copyConstantToRegister(MBB, IPt, C, Reg);
398 return Reg;
399 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
400 unsigned Reg = makeAnotherReg(V->getType());
401 // Move the address of the global into the register
402 BuildMI(*MBB, IPt, X86::MOV32ri, 1, Reg).addGlobalAddress(GV);
403 return Reg;
404 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
405 // Do not emit noop casts at all.
406 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
407 return getReg(CI->getOperand(0), MBB, IPt);
408 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
409 // If the alloca address couldn't be folded into the instruction addressing,
410 // emit an explicit LEA as appropriate.
411 unsigned Reg = makeAnotherReg(V->getType());
412 unsigned FI = getFixedSizedAllocaFI(AI);
413 addFrameReference(BuildMI(*MBB, IPt, X86::LEA32r, 4, Reg), FI);
414 return Reg;
415 }
416
417 unsigned &Reg = RegMap[V];
418 if (Reg == 0) {
419 Reg = makeAnotherReg(V->getType());
420 RegMap[V] = Reg;
421 }
422
423 return Reg;
424}
425
426/// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
427/// that is to be statically allocated with the initial stack frame
428/// adjustment.
429unsigned ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
430 // Already computed this?
431 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
432 if (I != AllocaMap.end() && I->first == AI) return I->second;
433
434 const Type *Ty = AI->getAllocatedType();
435 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
436 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
437 TySize *= CUI->getValue(); // Get total allocated size...
438 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
439
440 // Create a new stack object using the frame manager...
441 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
442 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
443 return FrameIdx;
444}
445
446
Chris Lattnerc5291f52002-10-27 21:16:59 +0000447/// copyConstantToRegister - Output the instructions required to put the
448/// specified constant into the specified register.
449///
Chris Lattner8a307e82002-12-16 19:32:50 +0000450void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000451 MachineBasicBlock::iterator IP,
Chris Lattner8a307e82002-12-16 19:32:50 +0000452 Constant *C, unsigned R) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000453 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000454 unsigned Class = 0;
455 switch (CE->getOpcode()) {
456 case Instruction::GetElementPtr:
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000457 emitGEPOperation(MBB, IP, CE->getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000458 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000459 return;
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000460 case Instruction::Cast:
Chris Lattner548f61d2003-04-23 17:22:12 +0000461 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
Chris Lattner4b12cde2003-04-21 21:33:44 +0000462 return;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000463
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000464 case Instruction::Xor: ++Class; // FALL THROUGH
465 case Instruction::Or: ++Class; // FALL THROUGH
466 case Instruction::And: ++Class; // FALL THROUGH
467 case Instruction::Sub: ++Class; // FALL THROUGH
468 case Instruction::Add:
469 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
470 Class, R);
471 return;
472
Chris Lattner462fa822004-04-11 20:56:28 +0000473 case Instruction::Mul:
474 emitMultiply(MBB, IP, CE->getOperand(0), CE->getOperand(1), R);
Chris Lattnercadff442003-10-23 17:21:43 +0000475 return;
Chris Lattner462fa822004-04-11 20:56:28 +0000476
Chris Lattnercadff442003-10-23 17:21:43 +0000477 case Instruction::Div:
Chris Lattner462fa822004-04-11 20:56:28 +0000478 case Instruction::Rem:
479 emitDivRemOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
480 CE->getOpcode() == Instruction::Div, R);
Chris Lattnercadff442003-10-23 17:21:43 +0000481 return;
Chris Lattnercadff442003-10-23 17:21:43 +0000482
Chris Lattner58c41fe2003-08-24 19:19:47 +0000483 case Instruction::SetNE:
484 case Instruction::SetEQ:
485 case Instruction::SetLT:
486 case Instruction::SetGT:
487 case Instruction::SetLE:
488 case Instruction::SetGE:
489 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
490 CE->getOpcode(), R);
491 return;
492
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000493 case Instruction::Shl:
494 case Instruction::Shr:
495 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000496 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
497 return;
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000498
Chris Lattner12d96a02004-03-30 21:22:00 +0000499 case Instruction::Select:
500 emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
501 CE->getOperand(2), R);
502 return;
503
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000504 default:
505 std::cerr << "Offending expr: " << C << "\n";
Chris Lattnerb2acc512003-10-19 21:09:10 +0000506 assert(0 && "Constant expression not yet handled!\n");
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000507 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000508 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000509
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000510 if (C->getType()->isIntegral()) {
Chris Lattner6b993cc2002-12-15 08:02:15 +0000511 unsigned Class = getClassB(C->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +0000512
513 if (Class == cLong) {
514 // Copy the value into the register pair.
Chris Lattnerc07736a2003-07-23 15:22:26 +0000515 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000516 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
517 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
Chris Lattner3e130a22003-01-13 00:32:26 +0000518 return;
519 }
520
Chris Lattner94af4142002-12-25 05:13:53 +0000521 assert(Class <= cInt && "Type not handled yet!");
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000522
523 static const unsigned IntegralOpcodeTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000524 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000525 };
526
Chris Lattner6b993cc2002-12-15 08:02:15 +0000527 if (C->getType() == Type::BoolTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000528 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000529 } else {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000530 ConstantInt *CI = cast<ConstantInt>(C);
Chris Lattneree352852004-02-29 07:22:16 +0000531 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000532 }
Chris Lattner94af4142002-12-25 05:13:53 +0000533 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattneraf703622004-02-02 18:56:30 +0000534 if (CFP->isExactlyValue(+0.0))
Chris Lattneree352852004-02-29 07:22:16 +0000535 BuildMI(*MBB, IP, X86::FLD0, 0, R);
Chris Lattneraf703622004-02-02 18:56:30 +0000536 else if (CFP->isExactlyValue(+1.0))
Chris Lattneree352852004-02-29 07:22:16 +0000537 BuildMI(*MBB, IP, X86::FLD1, 0, R);
Chris Lattner94af4142002-12-25 05:13:53 +0000538 else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000539 // Otherwise we need to spill the constant to memory...
540 MachineConstantPool *CP = F->getConstantPool();
541 unsigned CPI = CP->getConstantPoolIndex(CFP);
Chris Lattner6c09db22003-10-20 04:11:23 +0000542 const Type *Ty = CFP->getType();
543
544 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000545 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
Chris Lattneree352852004-02-29 07:22:16 +0000546 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
Chris Lattner94af4142002-12-25 05:13:53 +0000547 }
548
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000549 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000550 // Copy zero (null pointer) to the register.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000551 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000552 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000553 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(CPR->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000554 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000555 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000556 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000557 }
558}
559
Chris Lattner065faeb2002-12-28 20:24:02 +0000560/// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
561/// the stack into virtual registers.
562///
563void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
564 // Emit instructions to load the arguments... On entry to a function on the
565 // X86, the stack frame looks like this:
566 //
567 // [ESP] -- return address
Chris Lattner3e130a22003-01-13 00:32:26 +0000568 // [ESP + 4] -- first argument (leftmost lexically)
569 // [ESP + 8] -- second argument, if first argument is four bytes in size
Chris Lattner065faeb2002-12-28 20:24:02 +0000570 // ...
571 //
Chris Lattnerf158da22003-01-16 02:20:12 +0000572 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
Chris Lattneraa09b752002-12-28 21:08:28 +0000573 MachineFrameInfo *MFI = F->getFrameInfo();
Chris Lattner065faeb2002-12-28 20:24:02 +0000574
575 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
Chris Lattner427aeb42004-04-11 19:21:59 +0000576 bool ArgLive = !I->use_empty();
577 unsigned Reg = ArgLive ? getReg(*I) : 0;
Chris Lattner065faeb2002-12-28 20:24:02 +0000578 int FI; // Frame object index
Chris Lattner427aeb42004-04-11 19:21:59 +0000579
Chris Lattner065faeb2002-12-28 20:24:02 +0000580 switch (getClassB(I->getType())) {
581 case cByte:
Chris Lattner427aeb42004-04-11 19:21:59 +0000582 if (ArgLive) {
583 FI = MFI->CreateFixedObject(1, ArgOffset);
584 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
585 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000586 break;
587 case cShort:
Chris Lattner427aeb42004-04-11 19:21:59 +0000588 if (ArgLive) {
589 FI = MFI->CreateFixedObject(2, ArgOffset);
590 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
591 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000592 break;
593 case cInt:
Chris Lattner427aeb42004-04-11 19:21:59 +0000594 if (ArgLive) {
595 FI = MFI->CreateFixedObject(4, ArgOffset);
596 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
597 }
Chris Lattner065faeb2002-12-28 20:24:02 +0000598 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000599 case cLong:
Chris Lattner427aeb42004-04-11 19:21:59 +0000600 if (ArgLive) {
601 FI = MFI->CreateFixedObject(8, ArgOffset);
602 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
603 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
604 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000605 ArgOffset += 4; // longs require 4 additional bytes
606 break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000607 case cFP:
Chris Lattner427aeb42004-04-11 19:21:59 +0000608 if (ArgLive) {
609 unsigned Opcode;
610 if (I->getType() == Type::FloatTy) {
611 Opcode = X86::FLD32m;
612 FI = MFI->CreateFixedObject(4, ArgOffset);
613 } else {
614 Opcode = X86::FLD64m;
615 FI = MFI->CreateFixedObject(8, ArgOffset);
616 }
617 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000618 }
Chris Lattner427aeb42004-04-11 19:21:59 +0000619 if (I->getType() == Type::DoubleTy)
620 ArgOffset += 4; // doubles require 4 additional bytes
Chris Lattner065faeb2002-12-28 20:24:02 +0000621 break;
622 default:
623 assert(0 && "Unhandled argument type!");
624 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000625 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000626 }
Chris Lattnereca195e2003-05-08 19:44:13 +0000627
628 // If the function takes variable number of arguments, add a frame offset for
629 // the start of the first vararg value... this is used to expand
630 // llvm.va_start.
631 if (Fn.getFunctionType()->isVarArg())
632 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000633}
634
635
Chris Lattner333b2fa2002-12-13 10:09:43 +0000636/// SelectPHINodes - Insert machine code to generate phis. This is tricky
637/// because we have to generate our sources into the source basic blocks, not
638/// the current one.
639///
640void ISel::SelectPHINodes() {
Chris Lattner3501fea2003-01-14 22:00:31 +0000641 const TargetInstrInfo &TII = TM.getInstrInfo();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000642 const Function &LF = *F->getFunction(); // The LLVM function...
643 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
644 const BasicBlock *BB = I;
Chris Lattner168aa902004-02-29 07:10:16 +0000645 MachineBasicBlock &MBB = *MBBMap[I];
Chris Lattner333b2fa2002-12-13 10:09:43 +0000646
647 // Loop over all of the PHI nodes in the LLVM basic block...
Chris Lattner168aa902004-02-29 07:10:16 +0000648 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000649 for (BasicBlock::const_iterator I = BB->begin();
Chris Lattnera81fc682003-10-19 00:26:11 +0000650 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000651
Chris Lattner333b2fa2002-12-13 10:09:43 +0000652 // Create a new machine instr PHI node, and insert it.
Chris Lattner3e130a22003-01-13 00:32:26 +0000653 unsigned PHIReg = getReg(*PN);
Chris Lattner168aa902004-02-29 07:10:16 +0000654 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
655 X86::PHI, PN->getNumOperands(), PHIReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000656
657 MachineInstr *LongPhiMI = 0;
Chris Lattner168aa902004-02-29 07:10:16 +0000658 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
659 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
660 X86::PHI, PN->getNumOperands(), PHIReg+1);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000661
Chris Lattnera6e73f12003-05-12 14:22:21 +0000662 // PHIValues - Map of blocks to incoming virtual registers. We use this
663 // so that we only initialize one incoming value for a particular block,
664 // even if the block has multiple entries in the PHI node.
665 //
666 std::map<MachineBasicBlock*, unsigned> PHIValues;
667
Chris Lattner333b2fa2002-12-13 10:09:43 +0000668 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
669 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
Chris Lattnera6e73f12003-05-12 14:22:21 +0000670 unsigned ValReg;
671 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
672 PHIValues.lower_bound(PredMBB);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000673
Chris Lattnera6e73f12003-05-12 14:22:21 +0000674 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
675 // We already inserted an initialization of the register for this
676 // predecessor. Recycle it.
677 ValReg = EntryIt->second;
678
679 } else {
Chris Lattnera81fc682003-10-19 00:26:11 +0000680 // Get the incoming value into a virtual register.
Chris Lattnera6e73f12003-05-12 14:22:21 +0000681 //
Chris Lattnera81fc682003-10-19 00:26:11 +0000682 Value *Val = PN->getIncomingValue(i);
683
684 // If this is a constant or GlobalValue, we may have to insert code
685 // into the basic block to compute it into a virtual register.
Chris Lattnercb2fd552004-05-13 07:40:27 +0000686 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
687 isa<GlobalValue>(Val)) {
688 // Simple constants get emitted at the end of the basic block,
689 // before any terminator instructions. We "know" that the code to
690 // move a constant into a register will never clobber any flags.
691 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
Chris Lattnera81fc682003-10-19 00:26:11 +0000692 } else {
Chris Lattnercb2fd552004-05-13 07:40:27 +0000693 // Because we don't want to clobber any values which might be in
694 // physical registers with the computation of this constant (which
695 // might be arbitrarily complex if it is a constant expression),
696 // just insert the computation at the top of the basic block.
697 MachineBasicBlock::iterator PI = PredMBB->begin();
698
699 // Skip over any PHI nodes though!
700 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
701 ++PI;
702
703 ValReg = getReg(Val, PredMBB, PI);
Chris Lattnera81fc682003-10-19 00:26:11 +0000704 }
Chris Lattnera6e73f12003-05-12 14:22:21 +0000705
706 // Remember that we inserted a value for this PHI for this predecessor
707 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
708 }
709
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000710 PhiMI->addRegOperand(ValReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000711 PhiMI->addMachineBasicBlockOperand(PredMBB);
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000712 if (LongPhiMI) {
713 LongPhiMI->addRegOperand(ValReg+1);
714 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
715 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000716 }
Chris Lattner168aa902004-02-29 07:10:16 +0000717
718 // Now that we emitted all of the incoming values for the PHI node, make
719 // sure to reposition the InsertPoint after the PHI that we just added.
720 // This is needed because we might have inserted a constant into this
721 // block, right after the PHI's which is before the old insert point!
722 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
723 ++PHIInsertPoint;
Chris Lattner333b2fa2002-12-13 10:09:43 +0000724 }
725 }
726}
727
Chris Lattner986618e2004-02-22 19:47:26 +0000728/// RequiresFPRegKill - The floating point stackifier pass cannot insert
729/// compensation code on critical edges. As such, it requires that we kill all
730/// FP registers on the exit from any blocks that either ARE critical edges, or
731/// branch to a block that has incoming critical edges.
732///
733/// Note that this kill instruction will eventually be eliminated when
734/// restrictions in the stackifier are relaxed.
735///
Brian Gaeke1afe7732004-04-28 04:45:55 +0000736static bool RequiresFPRegKill(const MachineBasicBlock *MBB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000737#if 0
Brian Gaeke1afe7732004-04-28 04:45:55 +0000738 const BasicBlock *BB = MBB->getBasicBlock ();
Chris Lattner986618e2004-02-22 19:47:26 +0000739 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
740 const BasicBlock *Succ = *SI;
741 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
742 ++PI; // Block have at least one predecessory
743 if (PI != PE) { // If it has exactly one, this isn't crit edge
744 // If this block has more than one predecessor, check all of the
745 // predecessors to see if they have multiple successors. If so, then the
746 // block we are analyzing needs an FPRegKill.
747 for (PI = pred_begin(Succ); PI != PE; ++PI) {
748 const BasicBlock *Pred = *PI;
749 succ_const_iterator SI2 = succ_begin(Pred);
750 ++SI2; // There must be at least one successor of this block.
751 if (SI2 != succ_end(Pred))
752 return true; // Yes, we must insert the kill on this edge.
753 }
754 }
755 }
756 // If we got this far, there is no need to insert the kill instruction.
757 return false;
758#else
759 return true;
760#endif
761}
762
763// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
764// need them. This only occurs due to the floating point stackifier not being
765// aggressive enough to handle arbitrary global stackification.
766//
767// Currently we insert an FP_REG_KILL instruction into each block that uses or
768// defines a floating point virtual register.
769//
770// When the global register allocators (like linear scan) finally update live
771// variable analysis, we can keep floating point values in registers across
772// portions of the CFG that do not involve critical edges. This will be a big
773// win, but we are waiting on the global allocators before we can do this.
774//
775// With a bit of work, the floating point stackifier pass can be enhanced to
776// break critical edges as needed (to make a place to put compensation code),
777// but this will require some infrastructure improvements as well.
778//
779void ISel::InsertFPRegKills() {
780 SSARegMap &RegMap = *F->getSSARegMap();
Chris Lattner986618e2004-02-22 19:47:26 +0000781
782 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000783 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000784 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
785 MachineOperand& MO = I->getOperand(i);
786 if (MO.isRegister() && MO.getReg()) {
787 unsigned Reg = MO.getReg();
Chris Lattner986618e2004-02-22 19:47:26 +0000788 if (MRegisterInfo::isVirtualRegister(Reg))
Chris Lattner65cf42d2004-02-23 07:29:45 +0000789 if (RegMap.getRegClass(Reg)->getSize() == 10)
790 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000791 }
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000792 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000793 // If we haven't found an FP register use or def in this basic block, check
794 // to see if any of our successors has an FP PHI node, which will cause a
795 // copy to be inserted into this block.
Brian Gaeke235aa5e2004-04-28 04:34:16 +0000796 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
797 SE = BB->succ_end(); SI != SE; ++SI) {
798 MachineBasicBlock *SBB = *SI;
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000799 for (MachineBasicBlock::iterator I = SBB->begin();
800 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
801 if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
802 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000803 }
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000804 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000805 continue;
806 UsesFPReg:
807 // Okay, this block uses an FP register. If the block has successors (ie,
808 // it's not an unwind/return), insert the FP_REG_KILL instruction.
Brian Gaeke1afe7732004-04-28 04:45:55 +0000809 if (BB->succ_size () && RequiresFPRegKill(BB)) {
Chris Lattneree352852004-02-29 07:22:16 +0000810 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
Chris Lattner65cf42d2004-02-23 07:29:45 +0000811 ++NumFPKill;
Chris Lattner986618e2004-02-22 19:47:26 +0000812 }
813 }
814}
815
816
Chris Lattner307ecba2004-03-30 22:39:09 +0000817// canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
818// it into the conditional branch or select instruction which is the only user
819// of the cc instruction. This is the case if the conditional branch is the
820// only user of the setcc, and if the setcc is in the same basic block as the
821// conditional branch. We also don't handle long arguments below, so we reject
822// them here as well.
Chris Lattner6d40c192003-01-16 16:43:00 +0000823//
Chris Lattner307ecba2004-03-30 22:39:09 +0000824static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
Chris Lattner6d40c192003-01-16 16:43:00 +0000825 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
Chris Lattner307ecba2004-03-30 22:39:09 +0000826 if (SCI->hasOneUse()) {
827 Instruction *User = cast<Instruction>(SCI->use_back());
828 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
829 SCI->getParent() == User->getParent() &&
Chris Lattner48c937e2004-04-06 17:34:50 +0000830 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
831 SCI->getOpcode() == Instruction::SetEQ ||
832 SCI->getOpcode() == Instruction::SetNE))
Chris Lattner6d40c192003-01-16 16:43:00 +0000833 return SCI;
834 }
835 return 0;
836}
Chris Lattner333b2fa2002-12-13 10:09:43 +0000837
Chris Lattner6d40c192003-01-16 16:43:00 +0000838// Return a fixed numbering for setcc instructions which does not depend on the
839// order of the opcodes.
840//
841static unsigned getSetCCNumber(unsigned Opcode) {
842 switch(Opcode) {
843 default: assert(0 && "Unknown setcc instruction!");
844 case Instruction::SetEQ: return 0;
845 case Instruction::SetNE: return 1;
846 case Instruction::SetLT: return 2;
Chris Lattner55f6fab2003-01-16 18:07:23 +0000847 case Instruction::SetGE: return 3;
848 case Instruction::SetGT: return 4;
849 case Instruction::SetLE: return 5;
Chris Lattner6d40c192003-01-16 16:43:00 +0000850 }
851}
Chris Lattner06925362002-11-17 21:56:38 +0000852
Chris Lattner6d40c192003-01-16 16:43:00 +0000853// LLVM -> X86 signed X86 unsigned
854// ----- ---------- ------------
855// seteq -> sete sete
856// setne -> setne setne
857// setlt -> setl setb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000858// setge -> setge setae
Chris Lattner6d40c192003-01-16 16:43:00 +0000859// setgt -> setg seta
860// setle -> setle setbe
Chris Lattnerb2acc512003-10-19 21:09:10 +0000861// ----
862// sets // Used by comparison with 0 optimization
863// setns
864static const unsigned SetCCOpcodeTab[2][8] = {
865 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
866 0, 0 },
867 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
868 X86::SETSr, X86::SETNSr },
Chris Lattner6d40c192003-01-16 16:43:00 +0000869};
870
Chris Lattnerb2acc512003-10-19 21:09:10 +0000871// EmitComparison - This function emits a comparison of the two operands,
872// returning the extended setcc code to use.
873unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
874 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000875 MachineBasicBlock::iterator IP) {
Brian Gaeke1749d632002-11-07 17:59:21 +0000876 // The arguments are already supposed to be of the same type.
Chris Lattner6d40c192003-01-16 16:43:00 +0000877 const Type *CompTy = Op0->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +0000878 unsigned Class = getClassB(CompTy);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000879 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattner333864d2003-06-05 19:30:30 +0000880
881 // Special case handling of: cmp R, i
Chris Lattner260195d2004-05-07 19:55:55 +0000882 if (isa<ConstantPointerNull>(Op1)) {
883 if (OpNum < 2) // seteq/setne -> test
884 BuildMI(*MBB, IP, X86::TEST32rr, 2).addReg(Op0r).addReg(Op0r);
885 else
886 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(0);
887 return OpNum;
888
889 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere80e6372004-04-06 16:02:27 +0000890 if (Class == cByte || Class == cShort || Class == cInt) {
891 unsigned Op1v = CI->getRawValue();
Chris Lattnerc07736a2003-07-23 15:22:26 +0000892
Chris Lattner333864d2003-06-05 19:30:30 +0000893 // Mask off any upper bits of the constant, if there are any...
894 Op1v &= (1ULL << (8 << Class)) - 1;
895
Chris Lattnerb2acc512003-10-19 21:09:10 +0000896 // If this is a comparison against zero, emit more efficient code. We
897 // can't handle unsigned comparisons against zero unless they are == or
898 // !=. These should have been strength reduced already anyway.
899 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
900 static const unsigned TESTTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000901 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
Chris Lattnerb2acc512003-10-19 21:09:10 +0000902 };
Chris Lattneree352852004-02-29 07:22:16 +0000903 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000904
905 if (OpNum == 2) return 6; // Map jl -> js
906 if (OpNum == 3) return 7; // Map jg -> jns
907 return OpNum;
Chris Lattner333864d2003-06-05 19:30:30 +0000908 }
Chris Lattnerb2acc512003-10-19 21:09:10 +0000909
910 static const unsigned CMPTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000911 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
Chris Lattnerb2acc512003-10-19 21:09:10 +0000912 };
913
Chris Lattneree352852004-02-29 07:22:16 +0000914 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000915 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +0000916 } else {
917 assert(Class == cLong && "Unknown integer class!");
918 unsigned LowCst = CI->getRawValue();
919 unsigned HiCst = CI->getRawValue() >> 32;
920 if (OpNum < 2) { // seteq, setne
921 unsigned LoTmp = Op0r;
922 if (LowCst != 0) {
923 LoTmp = makeAnotherReg(Type::IntTy);
924 BuildMI(*MBB, IP, X86::XOR32ri, 2, LoTmp).addReg(Op0r).addImm(LowCst);
925 }
926 unsigned HiTmp = Op0r+1;
927 if (HiCst != 0) {
928 HiTmp = makeAnotherReg(Type::IntTy);
Chris Lattner48c937e2004-04-06 17:34:50 +0000929 BuildMI(*MBB, IP, X86::XOR32ri, 2,HiTmp).addReg(Op0r+1).addImm(HiCst);
Chris Lattnere80e6372004-04-06 16:02:27 +0000930 }
931 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
932 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
933 return OpNum;
Chris Lattner48c937e2004-04-06 17:34:50 +0000934 } else {
935 // Emit a sequence of code which compares the high and low parts once
936 // each, then uses a conditional move to handle the overflow case. For
937 // example, a setlt for long would generate code like this:
938 //
Chris Lattner9984fd02004-05-09 23:16:33 +0000939 // AL = lo(op1) < lo(op2) // Always unsigned comparison
940 // BL = hi(op1) < hi(op2) // Signedness depends on operands
941 // dest = hi(op1) == hi(op2) ? BL : AL;
Chris Lattner48c937e2004-04-06 17:34:50 +0000942 //
943
944 // FIXME: This would be much better if we had hierarchical register
945 // classes! Until then, hardcode registers so that we can deal with
946 // their aliases (because we don't have conditional byte moves).
947 //
948 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(LowCst);
949 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
950 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r+1).addImm(HiCst);
951 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0,X86::BL);
952 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
953 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
954 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
955 .addReg(X86::AX);
956 // NOTE: visitSetCondInst knows that the value is dumped into the BL
957 // register at this point for long values...
958 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +0000959 }
Chris Lattner333864d2003-06-05 19:30:30 +0000960 }
Chris Lattnere80e6372004-04-06 16:02:27 +0000961 }
Chris Lattner333864d2003-06-05 19:30:30 +0000962
Chris Lattner9f08a922004-02-03 18:54:04 +0000963 // Special case handling of comparison against +/- 0.0
964 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
965 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
Chris Lattneree352852004-02-29 07:22:16 +0000966 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000967 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +0000968 BuildMI(*MBB, IP, X86::SAHF, 1);
Chris Lattner9f08a922004-02-03 18:54:04 +0000969 return OpNum;
970 }
971
Chris Lattner58c41fe2003-08-24 19:19:47 +0000972 unsigned Op1r = getReg(Op1, MBB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +0000973 switch (Class) {
974 default: assert(0 && "Unknown type class!");
975 // Emit: cmp <var1>, <var2> (do the comparison). We can
976 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
977 // 32-bit.
978 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000979 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000980 break;
981 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000982 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000983 break;
984 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000985 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000986 break;
987 case cFP:
Chris Lattner8d2822e2004-04-12 01:43:36 +0000988 if (0) { // for processors prior to the P6
989 BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
990 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
991 BuildMI(*MBB, IP, X86::SAHF, 1);
992 } else {
Chris Lattner133dbb12004-04-12 03:02:48 +0000993 BuildMI(*MBB, IP, X86::FpUCOMI, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner8d2822e2004-04-12 01:43:36 +0000994 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000995 break;
996
997 case cLong:
998 if (OpNum < 2) { // seteq, setne
999 unsigned LoTmp = makeAnotherReg(Type::IntTy);
1000 unsigned HiTmp = makeAnotherReg(Type::IntTy);
1001 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001002 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
1003 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
1004 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
Chris Lattner3e130a22003-01-13 00:32:26 +00001005 break; // Allow the sete or setne to be generated from flags set by OR
1006 } else {
1007 // Emit a sequence of code which compares the high and low parts once
1008 // each, then uses a conditional move to handle the overflow case. For
1009 // example, a setlt for long would generate code like this:
1010 //
1011 // AL = lo(op1) < lo(op2) // Signedness depends on operands
1012 // BL = hi(op1) < hi(op2) // Always unsigned comparison
Chris Lattner9984fd02004-05-09 23:16:33 +00001013 // dest = hi(op1) == hi(op2) ? BL : AL;
Chris Lattner3e130a22003-01-13 00:32:26 +00001014 //
1015
Chris Lattner6d40c192003-01-16 16:43:00 +00001016 // FIXME: This would be much better if we had hierarchical register
Chris Lattner3e130a22003-01-13 00:32:26 +00001017 // classes! Until then, hardcode registers so that we can deal with their
1018 // aliases (because we don't have conditional byte moves).
1019 //
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001020 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattneree352852004-02-29 07:22:16 +00001021 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001022 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
Chris Lattneree352852004-02-29 07:22:16 +00001023 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
1024 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1025 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001026 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
Chris Lattneree352852004-02-29 07:22:16 +00001027 .addReg(X86::AX);
Chris Lattner6d40c192003-01-16 16:43:00 +00001028 // NOTE: visitSetCondInst knows that the value is dumped into the BL
1029 // register at this point for long values...
Chris Lattnerb2acc512003-10-19 21:09:10 +00001030 return OpNum;
Chris Lattner3e130a22003-01-13 00:32:26 +00001031 }
1032 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001033 return OpNum;
Chris Lattner6d40c192003-01-16 16:43:00 +00001034}
Chris Lattner3e130a22003-01-13 00:32:26 +00001035
Chris Lattner6d40c192003-01-16 16:43:00 +00001036/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
1037/// register, then move it to wherever the result should be.
1038///
1039void ISel::visitSetCondInst(SetCondInst &I) {
Chris Lattner307ecba2004-03-30 22:39:09 +00001040 if (canFoldSetCCIntoBranchOrSelect(&I))
1041 return; // Fold this into a branch or select.
Chris Lattner6d40c192003-01-16 16:43:00 +00001042
Chris Lattner6d40c192003-01-16 16:43:00 +00001043 unsigned DestReg = getReg(I);
Chris Lattner58c41fe2003-08-24 19:19:47 +00001044 MachineBasicBlock::iterator MII = BB->end();
1045 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
1046 DestReg);
1047}
Chris Lattner6d40c192003-01-16 16:43:00 +00001048
Chris Lattner58c41fe2003-08-24 19:19:47 +00001049/// emitSetCCOperation - Common code shared between visitSetCondInst and
1050/// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +00001051///
Chris Lattner58c41fe2003-08-24 19:19:47 +00001052void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001053 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +00001054 Value *Op0, Value *Op1, unsigned Opcode,
1055 unsigned TargetReg) {
1056 unsigned OpNum = getSetCCNumber(Opcode);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001057 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
Chris Lattner58c41fe2003-08-24 19:19:47 +00001058
Chris Lattnerb2acc512003-10-19 21:09:10 +00001059 const Type *CompTy = Op0->getType();
1060 unsigned CompClass = getClassB(CompTy);
1061 bool isSigned = CompTy->isSigned() && CompClass != cFP;
1062
1063 if (CompClass != cLong || OpNum < 2) {
Chris Lattner6d40c192003-01-16 16:43:00 +00001064 // Handle normal comparisons with a setcc instruction...
Chris Lattneree352852004-02-29 07:22:16 +00001065 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
Chris Lattner6d40c192003-01-16 16:43:00 +00001066 } else {
1067 // Handle long comparisons by copying the value which is already in BL into
1068 // the register we want...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001069 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
Chris Lattner6d40c192003-01-16 16:43:00 +00001070 }
Brian Gaeke1749d632002-11-07 17:59:21 +00001071}
Chris Lattner51b49a92002-11-02 19:45:49 +00001072
Chris Lattner12d96a02004-03-30 21:22:00 +00001073void ISel::visitSelectInst(SelectInst &SI) {
1074 unsigned DestReg = getReg(SI);
1075 MachineBasicBlock::iterator MII = BB->end();
1076 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1077 SI.getFalseValue(), DestReg);
1078}
1079
1080/// emitSelect - Common code shared between visitSelectInst and the constant
1081/// expression support.
1082void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1083 MachineBasicBlock::iterator IP,
1084 Value *Cond, Value *TrueVal, Value *FalseVal,
1085 unsigned DestReg) {
1086 unsigned SelectClass = getClassB(TrueVal->getType());
1087
1088 // We don't support 8-bit conditional moves. If we have incoming constants,
1089 // transform them into 16-bit constants to avoid having a run-time conversion.
1090 if (SelectClass == cByte) {
1091 if (Constant *T = dyn_cast<Constant>(TrueVal))
1092 TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
1093 if (Constant *F = dyn_cast<Constant>(FalseVal))
1094 FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
1095 }
1096
Chris Lattner82c5a992004-04-13 21:56:09 +00001097 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1098 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1099 if (TrueReg == FalseReg) {
1100 static const unsigned Opcode[] = {
1101 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
1102 };
1103 BuildMI(*MBB, IP, Opcode[SelectClass], 1, DestReg).addReg(TrueReg);
1104 if (SelectClass == cLong)
1105 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(TrueReg+1);
1106 return;
1107 }
1108
Chris Lattner307ecba2004-03-30 22:39:09 +00001109 unsigned Opcode;
1110 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1111 // We successfully folded the setcc into the select instruction.
1112
1113 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1114 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1115 IP);
1116
1117 const Type *CompTy = SCI->getOperand(0)->getType();
1118 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1119
1120 // LLVM -> X86 signed X86 unsigned
1121 // ----- ---------- ------------
1122 // seteq -> cmovNE cmovNE
1123 // setne -> cmovE cmovE
1124 // setlt -> cmovGE cmovAE
1125 // setge -> cmovL cmovB
1126 // setgt -> cmovLE cmovBE
1127 // setle -> cmovG cmovA
1128 // ----
1129 // cmovNS // Used by comparison with 0 optimization
1130 // cmovS
1131
1132 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001133 default: assert(0 && "Unknown value class!");
1134 case cFP: {
1135 // Annoyingly, we don't have a full set of floating point conditional
1136 // moves. :(
1137 static const unsigned OpcodeTab[2][8] = {
1138 { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
1139 X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1140 { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1141 };
1142 Opcode = OpcodeTab[isSigned][OpNum];
1143
1144 // If opcode == 0, we hit a case that we don't support. Output a setcc
1145 // and compare the result against zero.
1146 if (Opcode == 0) {
1147 unsigned CompClass = getClassB(CompTy);
1148 unsigned CondReg;
1149 if (CompClass != cLong || OpNum < 2) {
1150 CondReg = makeAnotherReg(Type::BoolTy);
1151 // Handle normal comparisons with a setcc instruction...
1152 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1153 } else {
1154 // Long comparisons end up in the BL register.
1155 CondReg = X86::BL;
1156 }
1157
Chris Lattner68626c22004-03-31 22:22:36 +00001158 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner352eb482004-03-31 22:03:35 +00001159 Opcode = X86::FCMOVE;
1160 }
1161 break;
1162 }
Chris Lattner307ecba2004-03-30 22:39:09 +00001163 case cByte:
1164 case cShort: {
1165 static const unsigned OpcodeTab[2][8] = {
1166 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1167 X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1168 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1169 X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1170 };
1171 Opcode = OpcodeTab[isSigned][OpNum];
1172 break;
1173 }
1174 case cInt:
1175 case cLong: {
1176 static const unsigned OpcodeTab[2][8] = {
1177 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1178 X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1179 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1180 X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1181 };
1182 Opcode = OpcodeTab[isSigned][OpNum];
1183 break;
1184 }
1185 }
1186 } else {
1187 // Get the value being branched on, and use it to set the condition codes.
1188 unsigned CondReg = getReg(Cond, MBB, IP);
Chris Lattner68626c22004-03-31 22:22:36 +00001189 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner307ecba2004-03-30 22:39:09 +00001190 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001191 default: assert(0 && "Unknown value class!");
1192 case cFP: Opcode = X86::FCMOVE; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001193 case cByte:
Chris Lattner352eb482004-03-31 22:03:35 +00001194 case cShort: Opcode = X86::CMOVE16rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001195 case cInt:
Chris Lattner352eb482004-03-31 22:03:35 +00001196 case cLong: Opcode = X86::CMOVE32rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001197 }
1198 }
Chris Lattner12d96a02004-03-30 21:22:00 +00001199
Chris Lattner12d96a02004-03-30 21:22:00 +00001200 unsigned RealDestReg = DestReg;
Chris Lattner12d96a02004-03-30 21:22:00 +00001201
Chris Lattner12d96a02004-03-30 21:22:00 +00001202
1203 // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves. Because of
1204 // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1205 // cmove, then truncate the result.
1206 if (SelectClass == cByte) {
1207 DestReg = makeAnotherReg(Type::ShortTy);
1208 if (getClassB(TrueVal->getType()) == cByte) {
1209 // Promote the true value, by storing it into AL, and reading from AX.
1210 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1211 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1212 TrueReg = makeAnotherReg(Type::ShortTy);
1213 BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1214 }
1215 if (getClassB(FalseVal->getType()) == cByte) {
1216 // Promote the true value, by storing it into CL, and reading from CX.
1217 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1218 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1219 FalseReg = makeAnotherReg(Type::ShortTy);
1220 BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1221 }
1222 }
1223
1224 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1225
1226 switch (SelectClass) {
1227 case cByte:
1228 // We did the computation with 16-bit registers. Truncate back to our
1229 // result by copying into AX then copying out AL.
1230 BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1231 BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1232 break;
1233 case cLong:
1234 // Move the upper half of the value as well.
1235 BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1236 break;
1237 }
1238}
Chris Lattner58c41fe2003-08-24 19:19:47 +00001239
1240
1241
Brian Gaekec2505982002-11-30 11:57:28 +00001242/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1243/// operand, in the specified target register.
Misha Brukman538607f2004-03-01 23:53:11 +00001244///
Chris Lattner3e130a22003-01-13 00:32:26 +00001245void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
Chris Lattner9984fd02004-05-09 23:16:33 +00001246 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001247
Chris Lattner29bf0622004-04-06 01:21:00 +00001248 Value *Val = VR.Val;
1249 const Type *Ty = VR.Ty;
Chris Lattner502e36c2004-04-06 01:25:33 +00001250 if (Val) {
Chris Lattner29bf0622004-04-06 01:21:00 +00001251 if (Constant *C = dyn_cast<Constant>(Val)) {
1252 Val = ConstantExpr::getCast(C, Type::IntTy);
1253 Ty = Type::IntTy;
1254 }
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001255
Chris Lattner502e36c2004-04-06 01:25:33 +00001256 // If this is a simple constant, just emit a MOVri directly to avoid the
1257 // copy.
1258 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1259 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
Chris Lattner2b10b082004-05-12 16:35:04 +00001260 BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
Chris Lattner502e36c2004-04-06 01:25:33 +00001261 return;
1262 }
1263 }
1264
Chris Lattner29bf0622004-04-06 01:21:00 +00001265 // Make sure we have the register number for this value...
1266 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1267
1268 switch (getClassB(Ty)) {
Chris Lattner94af4142002-12-25 05:13:53 +00001269 case cByte:
1270 // Extend value into target register (8->32)
1271 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001272 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001273 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001274 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001275 break;
1276 case cShort:
1277 // Extend value into target register (16->32)
1278 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001279 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001280 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001281 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001282 break;
1283 case cInt:
1284 // Move value into target register (32->32)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001285 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001286 break;
1287 default:
1288 assert(0 && "Unpromotable operand class in promote32");
1289 }
Brian Gaekec2505982002-11-30 11:57:28 +00001290}
Chris Lattnerc5291f52002-10-27 21:16:59 +00001291
Chris Lattner72614082002-10-25 22:55:53 +00001292/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
1293/// we have the following possibilities:
1294///
1295/// ret void: No return value, simply emit a 'ret' instruction
1296/// ret sbyte, ubyte : Extend value into EAX and return
1297/// ret short, ushort: Extend value into EAX and return
1298/// ret int, uint : Move value into EAX and return
1299/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +00001300/// ret long, ulong : Move value into EAX/EDX and return
1301/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +00001302///
Chris Lattner3e130a22003-01-13 00:32:26 +00001303void ISel::visitReturnInst(ReturnInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +00001304 if (I.getNumOperands() == 0) {
1305 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1306 return;
1307 }
1308
1309 Value *RetVal = I.getOperand(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00001310 switch (getClassB(RetVal->getType())) {
Chris Lattner94af4142002-12-25 05:13:53 +00001311 case cByte: // integral return values: extend or move into EAX and return
1312 case cShort:
1313 case cInt:
Chris Lattner29bf0622004-04-06 01:21:00 +00001314 promote32(X86::EAX, ValueRecord(RetVal));
Chris Lattnerdbd73722003-05-06 21:32:22 +00001315 // Declare that EAX is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +00001316 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +00001317 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001318 case cFP: { // Floats & Doubles: Return in ST(0)
1319 unsigned RetReg = getReg(RetVal);
Chris Lattner3e130a22003-01-13 00:32:26 +00001320 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
Chris Lattnerdbd73722003-05-06 21:32:22 +00001321 // Declare that top-of-stack is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +00001322 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +00001323 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001324 }
1325 case cLong: {
1326 unsigned RetReg = getReg(RetVal);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001327 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1328 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
Chris Lattnerdbd73722003-05-06 21:32:22 +00001329 // Declare that EAX & EDX are live on exit
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001330 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1331 .addReg(X86::ESP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001332 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001333 }
Chris Lattner94af4142002-12-25 05:13:53 +00001334 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00001335 visitInstruction(I);
Chris Lattner94af4142002-12-25 05:13:53 +00001336 }
Chris Lattner43189d12002-11-17 20:07:45 +00001337 // Emit a 'ret' instruction
Chris Lattner94af4142002-12-25 05:13:53 +00001338 BuildMI(BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +00001339}
1340
Chris Lattner55f6fab2003-01-16 18:07:23 +00001341// getBlockAfter - Return the basic block which occurs lexically after the
1342// specified one.
1343static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1344 Function::iterator I = BB; ++I; // Get iterator to next block
1345 return I != BB->getParent()->end() ? &*I : 0;
1346}
1347
Chris Lattner51b49a92002-11-02 19:45:49 +00001348/// visitBranchInst - Handle conditional and unconditional branches here. Note
1349/// that since code layout is frozen at this point, that if we are trying to
1350/// jump to a block that is the immediate successor of the current block, we can
Chris Lattner6d40c192003-01-16 16:43:00 +00001351/// just make a fall-through (but we don't currently).
Chris Lattner51b49a92002-11-02 19:45:49 +00001352///
Chris Lattner94af4142002-12-25 05:13:53 +00001353void ISel::visitBranchInst(BranchInst &BI) {
Brian Gaekeea9ca672004-04-28 04:19:37 +00001354 // Update machine-CFG edges
1355 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1356 if (BI.isConditional())
1357 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1358
Chris Lattner55f6fab2003-01-16 18:07:23 +00001359 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1360
1361 if (!BI.isConditional()) { // Unconditional branch?
Chris Lattnercf93cdd2004-01-30 22:13:44 +00001362 if (BI.getSuccessor(0) != NextBB)
Chris Lattner55f6fab2003-01-16 18:07:23 +00001363 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
Chris Lattner6d40c192003-01-16 16:43:00 +00001364 return;
1365 }
1366
1367 // See if we can fold the setcc into the branch itself...
Chris Lattner307ecba2004-03-30 22:39:09 +00001368 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
Chris Lattner6d40c192003-01-16 16:43:00 +00001369 if (SCI == 0) {
1370 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1371 // computed some other way...
Chris Lattner065faeb2002-12-28 20:24:02 +00001372 unsigned condReg = getReg(BI.getCondition());
Chris Lattner68626c22004-03-31 22:22:36 +00001373 BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001374 if (BI.getSuccessor(1) == NextBB) {
1375 if (BI.getSuccessor(0) != NextBB)
1376 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1377 } else {
1378 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1379
1380 if (BI.getSuccessor(0) != NextBB)
1381 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1382 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001383 return;
Chris Lattner94af4142002-12-25 05:13:53 +00001384 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001385
1386 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
Chris Lattner58c41fe2003-08-24 19:19:47 +00001387 MachineBasicBlock::iterator MII = BB->end();
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001388 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001389
1390 const Type *CompTy = SCI->getOperand(0)->getType();
1391 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
Chris Lattner6d40c192003-01-16 16:43:00 +00001392
Chris Lattnerb2acc512003-10-19 21:09:10 +00001393
Chris Lattner6d40c192003-01-16 16:43:00 +00001394 // LLVM -> X86 signed X86 unsigned
1395 // ----- ---------- ------------
1396 // seteq -> je je
1397 // setne -> jne jne
1398 // setlt -> jl jb
Chris Lattner55f6fab2003-01-16 18:07:23 +00001399 // setge -> jge jae
Chris Lattner6d40c192003-01-16 16:43:00 +00001400 // setgt -> jg ja
1401 // setle -> jle jbe
Chris Lattnerb2acc512003-10-19 21:09:10 +00001402 // ----
1403 // js // Used by comparison with 0 optimization
1404 // jns
1405
1406 static const unsigned OpcodeTab[2][8] = {
1407 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1408 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1409 X86::JS, X86::JNS },
Chris Lattner6d40c192003-01-16 16:43:00 +00001410 };
1411
Chris Lattner55f6fab2003-01-16 18:07:23 +00001412 if (BI.getSuccessor(0) != NextBB) {
1413 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1414 if (BI.getSuccessor(1) != NextBB)
1415 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1416 } else {
1417 // Change to the inverse condition...
1418 if (BI.getSuccessor(1) != NextBB) {
1419 OpNum ^= 1;
1420 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1421 }
1422 }
Chris Lattner2df035b2002-11-02 19:27:56 +00001423}
1424
Chris Lattner3e130a22003-01-13 00:32:26 +00001425
1426/// doCall - This emits an abstract call instruction, setting up the arguments
1427/// and the return value as appropriate. For the actual function call itself,
1428/// it inserts the specified CallMI instruction into the stream.
1429///
1430void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001431 const std::vector<ValueRecord> &Args) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001432
Chris Lattner065faeb2002-12-28 20:24:02 +00001433 // Count how many bytes are to be pushed on the stack...
1434 unsigned NumBytes = 0;
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001435
Chris Lattner3e130a22003-01-13 00:32:26 +00001436 if (!Args.empty()) {
1437 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1438 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001439 case cByte: case cShort: case cInt:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001440 NumBytes += 4; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001441 case cLong:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001442 NumBytes += 8; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001443 case cFP:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001444 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1445 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001446 default: assert(0 && "Unknown class!");
1447 }
1448
1449 // Adjust the stack pointer for the new arguments...
Chris Lattneree352852004-02-29 07:22:16 +00001450 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
Chris Lattner065faeb2002-12-28 20:24:02 +00001451
1452 // Arguments go on the stack in reverse order, as specified by the ABI.
1453 unsigned ArgOffset = 0;
Chris Lattner3e130a22003-01-13 00:32:26 +00001454 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Chris Lattnerce6096f2004-03-01 02:34:08 +00001455 unsigned ArgReg;
Chris Lattner3e130a22003-01-13 00:32:26 +00001456 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001457 case cByte:
Chris Lattner2b10b082004-05-12 16:35:04 +00001458 if (Args[i].Val && isa<ConstantBool>(Args[i].Val)) {
1459 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1460 .addImm(Args[i].Val == ConstantBool::True);
1461 break;
1462 }
1463 // FALL THROUGH
Chris Lattner21585222004-03-01 02:42:43 +00001464 case cShort:
1465 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1466 // Zero/Sign extend constant, then stuff into memory.
1467 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1468 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1469 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1470 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1471 } else {
1472 // Promote arg to 32 bits wide into a temporary register...
1473 ArgReg = makeAnotherReg(Type::UIntTy);
1474 promote32(ArgReg, Args[i]);
1475 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1476 X86::ESP, ArgOffset).addReg(ArgReg);
1477 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001478 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001479 case cInt:
Chris Lattner21585222004-03-01 02:42:43 +00001480 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1481 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1482 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1483 X86::ESP, ArgOffset).addImm(Val);
1484 } else {
1485 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1486 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1487 X86::ESP, ArgOffset).addReg(ArgReg);
1488 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001489 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001490 case cLong:
Chris Lattner92900a62004-04-06 03:23:00 +00001491 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1492 uint64_t Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1493 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1494 X86::ESP, ArgOffset).addImm(Val & ~0U);
1495 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1496 X86::ESP, ArgOffset+4).addImm(Val >> 32ULL);
1497 } else {
1498 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1499 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1500 X86::ESP, ArgOffset).addReg(ArgReg);
1501 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1502 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1503 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001504 ArgOffset += 4; // 8 byte entry, not 4.
1505 break;
1506
Chris Lattner065faeb2002-12-28 20:24:02 +00001507 case cFP:
Chris Lattnerce6096f2004-03-01 02:34:08 +00001508 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001509 if (Args[i].Ty == Type::FloatTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001510 addRegOffset(BuildMI(BB, X86::FST32m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001511 X86::ESP, ArgOffset).addReg(ArgReg);
1512 } else {
1513 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001514 addRegOffset(BuildMI(BB, X86::FST64m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001515 X86::ESP, ArgOffset).addReg(ArgReg);
1516 ArgOffset += 4; // 8 byte entry, not 4.
1517 }
1518 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001519
Chris Lattner3e130a22003-01-13 00:32:26 +00001520 default: assert(0 && "Unknown class!");
Chris Lattner065faeb2002-12-28 20:24:02 +00001521 }
1522 ArgOffset += 4;
Chris Lattner94af4142002-12-25 05:13:53 +00001523 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001524 } else {
Chris Lattneree352852004-02-29 07:22:16 +00001525 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +00001526 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +00001527
Chris Lattner3e130a22003-01-13 00:32:26 +00001528 BB->push_back(CallMI);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001529
Chris Lattneree352852004-02-29 07:22:16 +00001530 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
Chris Lattnera3243642002-12-04 23:45:28 +00001531
1532 // If there is a return value, scavenge the result from the location the call
1533 // leaves it in...
1534 //
Chris Lattner3e130a22003-01-13 00:32:26 +00001535 if (Ret.Ty != Type::VoidTy) {
1536 unsigned DestClass = getClassB(Ret.Ty);
1537 switch (DestClass) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001538 case cByte:
1539 case cShort:
1540 case cInt: {
1541 // Integral results are in %eax, or the appropriate portion
1542 // thereof.
1543 static const unsigned regRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001544 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
Brian Gaeke20244b72002-12-12 15:33:40 +00001545 };
1546 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +00001547 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001548 break;
Brian Gaeke20244b72002-12-12 15:33:40 +00001549 }
Chris Lattner94af4142002-12-25 05:13:53 +00001550 case cFP: // Floating-point return values live in %ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +00001551 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001552 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001553 case cLong: // Long values are left in EDX:EAX
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001554 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1555 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
Chris Lattner3e130a22003-01-13 00:32:26 +00001556 break;
1557 default: assert(0 && "Unknown class!");
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001558 }
Chris Lattnera3243642002-12-04 23:45:28 +00001559 }
Brian Gaekefa8d5712002-11-22 11:07:01 +00001560}
Chris Lattner2df035b2002-11-02 19:27:56 +00001561
Chris Lattner3e130a22003-01-13 00:32:26 +00001562
1563/// visitCallInst - Push args on stack and do a procedure call instruction.
1564void ISel::visitCallInst(CallInst &CI) {
1565 MachineInstr *TheCall;
1566 if (Function *F = CI.getCalledFunction()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001567 // Is it an intrinsic function call?
Brian Gaeked0fde302003-11-11 22:41:34 +00001568 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001569 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1570 return;
1571 }
1572
Chris Lattner3e130a22003-01-13 00:32:26 +00001573 // Emit a CALL instruction with PC-relative displacement.
1574 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1575 } else { // Emit an indirect call...
1576 unsigned Reg = getReg(CI.getCalledValue());
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001577 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001578 }
1579
1580 std::vector<ValueRecord> Args;
1581 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001582 Args.push_back(ValueRecord(CI.getOperand(i)));
Chris Lattner3e130a22003-01-13 00:32:26 +00001583
1584 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1585 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001586}
Chris Lattner3e130a22003-01-13 00:32:26 +00001587
Chris Lattneraeb54b82003-08-28 21:23:43 +00001588
Chris Lattner44827152003-12-28 09:47:19 +00001589/// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1590/// function, lowering any calls to unknown intrinsic functions into the
1591/// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +00001592///
Chris Lattner44827152003-12-28 09:47:19 +00001593void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1594 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1595 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1596 if (CallInst *CI = dyn_cast<CallInst>(I++))
1597 if (Function *F = CI->getCalledFunction())
1598 switch (F->getIntrinsicID()) {
Chris Lattneraed386e2003-12-28 09:53:23 +00001599 case Intrinsic::not_intrinsic:
Chris Lattner317201d2004-03-13 00:24:00 +00001600 case Intrinsic::vastart:
1601 case Intrinsic::vacopy:
1602 case Intrinsic::vaend:
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001603 case Intrinsic::returnaddress:
1604 case Intrinsic::frameaddress:
Chris Lattner915e5e52004-02-12 17:53:22 +00001605 case Intrinsic::memcpy:
Chris Lattner2a0f2242004-02-14 04:46:05 +00001606 case Intrinsic::memset:
John Criswell4ffff9e2004-04-08 20:31:47 +00001607 case Intrinsic::readport:
1608 case Intrinsic::writeport:
Chris Lattner44827152003-12-28 09:47:19 +00001609 // We directly implement these intrinsics
1610 break;
John Criswelle5a4c152004-04-13 22:13:14 +00001611 case Intrinsic::readio: {
1612 // On X86, memory operations are in-order. Lower this intrinsic
1613 // into a volatile load.
1614 Instruction *Before = CI->getPrev();
1615 LoadInst * LI = new LoadInst (CI->getOperand(1), "", true, CI);
1616 CI->replaceAllUsesWith (LI);
1617 BB->getInstList().erase (CI);
John Criswelle5a4c152004-04-13 22:13:14 +00001618 break;
1619 }
1620 case Intrinsic::writeio: {
1621 // On X86, memory operations are in-order. Lower this intrinsic
1622 // into a volatile store.
1623 Instruction *Before = CI->getPrev();
1624 StoreInst * LI = new StoreInst (CI->getOperand(1),
1625 CI->getOperand(2), true, CI);
1626 CI->replaceAllUsesWith (LI);
1627 BB->getInstList().erase (CI);
John Criswelle5a4c152004-04-13 22:13:14 +00001628 break;
1629 }
Chris Lattner44827152003-12-28 09:47:19 +00001630 default:
1631 // All other intrinsic calls we must lower.
1632 Instruction *Before = CI->getPrev();
Chris Lattnerf70e0c22003-12-28 21:23:38 +00001633 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
Chris Lattner44827152003-12-28 09:47:19 +00001634 if (Before) { // Move iterator to instruction after call
1635 I = Before; ++I;
1636 } else {
1637 I = BB->begin();
1638 }
1639 }
1640
1641}
1642
Brian Gaeked0fde302003-11-11 22:41:34 +00001643void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001644 unsigned TmpReg1, TmpReg2;
1645 switch (ID) {
Chris Lattner5634b9f2004-03-13 00:24:52 +00001646 case Intrinsic::vastart:
Chris Lattnereca195e2003-05-08 19:44:13 +00001647 // Get the address of the first vararg value...
Chris Lattner73815062003-10-18 05:56:40 +00001648 TmpReg1 = getReg(CI);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001649 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
Chris Lattnereca195e2003-05-08 19:44:13 +00001650 return;
1651
Chris Lattner5634b9f2004-03-13 00:24:52 +00001652 case Intrinsic::vacopy:
Chris Lattner73815062003-10-18 05:56:40 +00001653 TmpReg1 = getReg(CI);
1654 TmpReg2 = getReg(CI.getOperand(1));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001655 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
Chris Lattnereca195e2003-05-08 19:44:13 +00001656 return;
Chris Lattner5634b9f2004-03-13 00:24:52 +00001657 case Intrinsic::vaend: return; // Noop on X86
Chris Lattnereca195e2003-05-08 19:44:13 +00001658
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001659 case Intrinsic::returnaddress:
1660 case Intrinsic::frameaddress:
1661 TmpReg1 = getReg(CI);
1662 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1663 if (ID == Intrinsic::returnaddress) {
1664 // Just load the return address
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001665 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001666 ReturnAddressIndex);
1667 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001668 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001669 ReturnAddressIndex, -4);
1670 }
1671 } else {
1672 // Values other than zero are not implemented yet.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001673 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001674 }
1675 return;
1676
Chris Lattner915e5e52004-02-12 17:53:22 +00001677 case Intrinsic::memcpy: {
1678 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1679 unsigned Align = 1;
1680 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1681 Align = AlignC->getRawValue();
1682 if (Align == 0) Align = 1;
1683 }
1684
1685 // Turn the byte code into # iterations
Chris Lattner915e5e52004-02-12 17:53:22 +00001686 unsigned CountReg;
Chris Lattner2a0f2242004-02-14 04:46:05 +00001687 unsigned Opcode;
Chris Lattner915e5e52004-02-12 17:53:22 +00001688 switch (Align & 3) {
1689 case 2: // WORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001690 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1691 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1692 } else {
1693 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001694 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001695 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner07122832004-02-13 23:36:47 +00001696 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001697 Opcode = X86::REP_MOVSW;
Chris Lattner915e5e52004-02-12 17:53:22 +00001698 break;
1699 case 0: // DWORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001700 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1701 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1702 } else {
1703 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001704 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001705 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner07122832004-02-13 23:36:47 +00001706 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001707 Opcode = X86::REP_MOVSD;
Chris Lattner915e5e52004-02-12 17:53:22 +00001708 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001709 default: // BYTE aligned
Chris Lattner07122832004-02-13 23:36:47 +00001710 CountReg = getReg(CI.getOperand(3));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001711 Opcode = X86::REP_MOVSB;
Chris Lattner915e5e52004-02-12 17:53:22 +00001712 break;
1713 }
1714
1715 // No matter what the alignment is, we put the source in ESI, the
1716 // destination in EDI, and the count in ECX.
1717 TmpReg1 = getReg(CI.getOperand(1));
1718 TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001719 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1720 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1721 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001722 BuildMI(BB, Opcode, 0);
1723 return;
1724 }
1725 case Intrinsic::memset: {
1726 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1727 unsigned Align = 1;
1728 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1729 Align = AlignC->getRawValue();
1730 if (Align == 0) Align = 1;
Chris Lattner915e5e52004-02-12 17:53:22 +00001731 }
1732
Chris Lattner2a0f2242004-02-14 04:46:05 +00001733 // Turn the byte code into # iterations
Chris Lattner2a0f2242004-02-14 04:46:05 +00001734 unsigned CountReg;
1735 unsigned Opcode;
1736 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1737 unsigned Val = ValC->getRawValue() & 255;
1738
1739 // If the value is a constant, then we can potentially use larger copies.
1740 switch (Align & 3) {
1741 case 2: // WORD aligned
1742 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001743 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001744 } else {
1745 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001746 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001747 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001748 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001749 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001750 Opcode = X86::REP_STOSW;
1751 break;
1752 case 0: // DWORD aligned
1753 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001754 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001755 } else {
1756 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001757 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001758 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001759 }
1760 Val = (Val << 8) | Val;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001761 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001762 Opcode = X86::REP_STOSD;
1763 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001764 default: // BYTE aligned
Chris Lattner2a0f2242004-02-14 04:46:05 +00001765 CountReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001766 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001767 Opcode = X86::REP_STOSB;
1768 break;
1769 }
1770 } else {
1771 // If it's not a constant value we are storing, just fall back. We could
1772 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1773 unsigned ValReg = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001774 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001775 CountReg = getReg(CI.getOperand(3));
1776 Opcode = X86::REP_STOSB;
1777 }
1778
1779 // No matter what the alignment is, we put the source in ESI, the
1780 // destination in EDI, and the count in ECX.
1781 TmpReg1 = getReg(CI.getOperand(1));
1782 //TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001783 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1784 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001785 BuildMI(BB, Opcode, 0);
Chris Lattner915e5e52004-02-12 17:53:22 +00001786 return;
1787 }
1788
Chris Lattner87e18de2004-04-13 17:20:37 +00001789 case Intrinsic::readport: {
1790 // First, determine that the size of the operand falls within the acceptable
1791 // range for this architecture.
John Criswell4ffff9e2004-04-08 20:31:47 +00001792 //
Chris Lattner87e18de2004-04-13 17:20:37 +00001793 if (getClassB(CI.getOperand(1)->getType()) != cShort) {
John Criswellca6ea0f2004-04-08 22:39:13 +00001794 std::cerr << "llvm.readport: Address size is not 16 bits\n";
Chris Lattner87e18de2004-04-13 17:20:37 +00001795 exit(1);
John Criswellca6ea0f2004-04-08 22:39:13 +00001796 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001797
John Criswell4ffff9e2004-04-08 20:31:47 +00001798 // Now, move the I/O port address into the DX register and use the IN
1799 // instruction to get the input data.
1800 //
Chris Lattner87e18de2004-04-13 17:20:37 +00001801 unsigned Class = getClass(CI.getCalledFunction()->getReturnType());
1802 unsigned DestReg = getReg(CI);
John Criswell4ffff9e2004-04-08 20:31:47 +00001803
Chris Lattner87e18de2004-04-13 17:20:37 +00001804 // If the port is a single-byte constant, use the immediate form.
1805 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(1)))
1806 if ((C->getRawValue() & 255) == C->getRawValue()) {
1807 switch (Class) {
1808 case cByte:
1809 BuildMI(BB, X86::IN8ri, 1).addImm((unsigned char)C->getRawValue());
1810 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1811 return;
1812 case cShort:
1813 BuildMI(BB, X86::IN16ri, 1).addImm((unsigned char)C->getRawValue());
1814 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1815 return;
1816 case cInt:
1817 BuildMI(BB, X86::IN32ri, 1).addImm((unsigned char)C->getRawValue());
1818 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1819 return;
1820 }
1821 }
1822
1823 unsigned Reg = getReg(CI.getOperand(1));
1824 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1825 switch (Class) {
1826 case cByte:
1827 BuildMI(BB, X86::IN8rr, 0);
1828 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1829 break;
1830 case cShort:
1831 BuildMI(BB, X86::IN16rr, 0);
1832 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1833 break;
1834 case cInt:
1835 BuildMI(BB, X86::IN32rr, 0);
1836 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1837 break;
1838 default:
1839 std::cerr << "Cannot do input on this data type";
John Criswellca6ea0f2004-04-08 22:39:13 +00001840 exit (1);
1841 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001842 return;
Chris Lattner87e18de2004-04-13 17:20:37 +00001843 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001844
Chris Lattner87e18de2004-04-13 17:20:37 +00001845 case Intrinsic::writeport: {
1846 // First, determine that the size of the operand falls within the
1847 // acceptable range for this architecture.
1848 if (getClass(CI.getOperand(2)->getType()) != cShort) {
1849 std::cerr << "llvm.writeport: Address size is not 16 bits\n";
1850 exit(1);
1851 }
1852
1853 unsigned Class = getClassB(CI.getOperand(1)->getType());
1854 unsigned ValReg = getReg(CI.getOperand(1));
1855 switch (Class) {
1856 case cByte:
1857 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1858 break;
1859 case cShort:
1860 BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(ValReg);
1861 break;
1862 case cInt:
1863 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(ValReg);
1864 break;
1865 default:
1866 std::cerr << "llvm.writeport: invalid data type for X86 target";
1867 exit(1);
1868 }
1869
1870
1871 // If the port is a single-byte constant, use the immediate form.
1872 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(2)))
1873 if ((C->getRawValue() & 255) == C->getRawValue()) {
1874 static const unsigned O[] = { X86::OUT8ir, X86::OUT16ir, X86::OUT32ir };
1875 BuildMI(BB, O[Class], 1).addImm((unsigned char)C->getRawValue());
1876 return;
1877 }
1878
1879 // Otherwise, move the I/O port address into the DX register and the value
1880 // to write into the AL/AX/EAX register.
1881 static const unsigned Opc[] = { X86::OUT8rr, X86::OUT16rr, X86::OUT32rr };
1882 unsigned Reg = getReg(CI.getOperand(2));
1883 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1884 BuildMI(BB, Opc[Class], 0);
1885 return;
1886 }
1887
Chris Lattner44827152003-12-28 09:47:19 +00001888 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
Chris Lattnereca195e2003-05-08 19:44:13 +00001889 }
1890}
1891
Chris Lattner7dee5da2004-03-08 01:58:35 +00001892static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1893 if (LI.getParent() != User.getParent())
1894 return false;
1895 BasicBlock::iterator It = &LI;
1896 // Check all of the instructions between the load and the user. We should
1897 // really use alias analysis here, but for now we just do something simple.
1898 for (++It; It != BasicBlock::iterator(&User); ++It) {
1899 switch (It->getOpcode()) {
Chris Lattner85c84e72004-03-18 06:29:54 +00001900 case Instruction::Free:
Chris Lattner7dee5da2004-03-08 01:58:35 +00001901 case Instruction::Store:
1902 case Instruction::Call:
1903 case Instruction::Invoke:
1904 return false;
Chris Lattner133dbb12004-04-12 03:02:48 +00001905 case Instruction::Load:
1906 if (cast<LoadInst>(It)->isVolatile() && LI.isVolatile())
1907 return false;
1908 break;
Chris Lattner7dee5da2004-03-08 01:58:35 +00001909 }
1910 }
1911 return true;
1912}
1913
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001914/// visitSimpleBinary - Implement simple binary operators for integral types...
1915/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1916/// Xor.
Misha Brukman538607f2004-03-01 23:53:11 +00001917///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001918void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1919 unsigned DestReg = getReg(B);
1920 MachineBasicBlock::iterator MI = BB->end();
Chris Lattner721d2d42004-03-08 01:18:36 +00001921 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
Chris Lattnerc81e6ba2004-05-10 15:15:55 +00001922 unsigned Class = getClassB(B.getType());
Chris Lattner721d2d42004-03-08 01:18:36 +00001923
Chris Lattner7dee5da2004-03-08 01:58:35 +00001924 // Special case: op Reg, load [mem]
Chris Lattnerc81e6ba2004-05-10 15:15:55 +00001925 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1) && Class != cLong &&
1926 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B))
Chris Lattner7dee5da2004-03-08 01:58:35 +00001927 if (!B.swapOperands())
1928 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
1929
Chris Lattner95157f72004-04-11 22:05:45 +00001930 if (isa<LoadInst>(Op1) && Class != cLong &&
Chris Lattner7dee5da2004-03-08 01:58:35 +00001931 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
1932
Chris Lattner95157f72004-04-11 22:05:45 +00001933 unsigned Opcode;
1934 if (Class != cFP) {
1935 static const unsigned OpcodeTab[][3] = {
1936 // Arithmetic operators
1937 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
1938 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
1939
1940 // Bitwise operators
1941 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
1942 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
1943 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
1944 };
1945 Opcode = OpcodeTab[OperatorClass][Class];
1946 } else {
1947 static const unsigned OpcodeTab[][2] = {
1948 { X86::FADD32m, X86::FADD64m }, // ADD
1949 { X86::FSUB32m, X86::FSUB64m }, // SUB
1950 };
1951 const Type *Ty = Op0->getType();
1952 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1953 Opcode = OpcodeTab[OperatorClass][Ty == Type::DoubleTy];
1954 }
Chris Lattner7dee5da2004-03-08 01:58:35 +00001955
1956 unsigned BaseReg, Scale, IndexReg, Disp;
1957 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), BaseReg,
1958 Scale, IndexReg, Disp);
1959
1960 unsigned Op0r = getReg(Op0);
1961 addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r),
1962 BaseReg, Scale, IndexReg, Disp);
1963 return;
1964 }
1965
Chris Lattner95157f72004-04-11 22:05:45 +00001966 // If this is a floating point subtract, check to see if we can fold the first
1967 // operand in.
1968 if (Class == cFP && OperatorClass == 1 &&
1969 isa<LoadInst>(Op0) &&
1970 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B)) {
1971 const Type *Ty = Op0->getType();
1972 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1973 unsigned Opcode = Ty == Type::FloatTy ? X86::FSUBR32m : X86::FSUBR64m;
1974
1975 unsigned BaseReg, Scale, IndexReg, Disp;
1976 getAddressingMode(cast<LoadInst>(Op0)->getOperand(0), BaseReg,
1977 Scale, IndexReg, Disp);
1978
1979 unsigned Op1r = getReg(Op1);
1980 addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op1r),
1981 BaseReg, Scale, IndexReg, Disp);
1982 return;
1983 }
1984
Chris Lattner721d2d42004-03-08 01:18:36 +00001985 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001986}
Chris Lattner3e130a22003-01-13 00:32:26 +00001987
Chris Lattner6621ed92004-04-11 21:23:56 +00001988
1989/// emitBinaryFPOperation - This method handles emission of floating point
1990/// Add (0), Sub (1), Mul (2), and Div (3) operations.
1991void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1992 MachineBasicBlock::iterator IP,
1993 Value *Op0, Value *Op1,
1994 unsigned OperatorClass, unsigned DestReg) {
1995
1996 // Special case: op Reg, <const fp>
1997 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1))
1998 if (!Op1C->isExactlyValue(+0.0) && !Op1C->isExactlyValue(+1.0)) {
1999 // Create a constant pool entry for this constant.
2000 MachineConstantPool *CP = F->getConstantPool();
2001 unsigned CPI = CP->getConstantPoolIndex(Op1C);
2002 const Type *Ty = Op1->getType();
2003
2004 static const unsigned OpcodeTab[][4] = {
2005 { X86::FADD32m, X86::FSUB32m, X86::FMUL32m, X86::FDIV32m }, // Float
2006 { X86::FADD64m, X86::FSUB64m, X86::FMUL64m, X86::FDIV64m }, // Double
2007 };
2008
2009 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2010 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2011 unsigned Op0r = getReg(Op0, BB, IP);
2012 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2013 DestReg).addReg(Op0r), CPI);
2014 return;
2015 }
2016
Chris Lattner13c07fe2004-04-12 00:12:04 +00002017 // Special case: R1 = op <const fp>, R2
Chris Lattner6621ed92004-04-11 21:23:56 +00002018 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
2019 if (CFP->isExactlyValue(-0.0) && OperatorClass == 1) {
2020 // -0.0 - X === -X
2021 unsigned op1Reg = getReg(Op1, BB, IP);
2022 BuildMI(*BB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
2023 return;
2024 } else if (!CFP->isExactlyValue(+0.0) && !CFP->isExactlyValue(+1.0)) {
Chris Lattner13c07fe2004-04-12 00:12:04 +00002025 // R1 = op CST, R2 --> R1 = opr R2, CST
Chris Lattner6621ed92004-04-11 21:23:56 +00002026
2027 // Create a constant pool entry for this constant.
2028 MachineConstantPool *CP = F->getConstantPool();
2029 unsigned CPI = CP->getConstantPoolIndex(CFP);
2030 const Type *Ty = CFP->getType();
2031
2032 static const unsigned OpcodeTab[][4] = {
2033 { X86::FADD32m, X86::FSUBR32m, X86::FMUL32m, X86::FDIVR32m }, // Float
2034 { X86::FADD64m, X86::FSUBR64m, X86::FMUL64m, X86::FDIVR64m }, // Double
2035 };
2036
2037 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2038 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2039 unsigned Op1r = getReg(Op1, BB, IP);
2040 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2041 DestReg).addReg(Op1r), CPI);
2042 return;
2043 }
2044
2045 // General case.
2046 static const unsigned OpcodeTab[4] = {
2047 X86::FpADD, X86::FpSUB, X86::FpMUL, X86::FpDIV
2048 };
2049
2050 unsigned Opcode = OpcodeTab[OperatorClass];
2051 unsigned Op0r = getReg(Op0, BB, IP);
2052 unsigned Op1r = getReg(Op1, BB, IP);
2053 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2054}
2055
Chris Lattnerb2acc512003-10-19 21:09:10 +00002056/// emitSimpleBinaryOperation - Implement simple binary operators for integral
2057/// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
2058/// Or, 4 for Xor.
Chris Lattner68aad932002-11-02 20:13:22 +00002059///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002060/// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
2061/// and constant expression support.
Chris Lattnerb2acc512003-10-19 21:09:10 +00002062///
2063void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002064 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002065 Value *Op0, Value *Op1,
Chris Lattnerb2acc512003-10-19 21:09:10 +00002066 unsigned OperatorClass, unsigned DestReg) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +00002067 unsigned Class = getClassB(Op0->getType());
Chris Lattnerb2acc512003-10-19 21:09:10 +00002068
Chris Lattner6621ed92004-04-11 21:23:56 +00002069 if (Class == cFP) {
2070 assert(OperatorClass < 2 && "No logical ops for FP!");
2071 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
2072 return;
2073 }
2074
Chris Lattnerb2acc512003-10-19 21:09:10 +00002075 // sub 0, X -> neg X
Chris Lattner48b0c972004-04-11 20:26:20 +00002076 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
2077 if (OperatorClass == 1 && CI->isNullValue()) {
2078 unsigned op1Reg = getReg(Op1, MBB, IP);
2079 static unsigned const NEGTab[] = {
2080 X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
2081 };
2082 BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
2083
2084 if (Class == cLong) {
2085 // We just emitted: Dl = neg Sl
2086 // Now emit : T = addc Sh, 0
2087 // : Dh = neg T
2088 unsigned T = makeAnotherReg(Type::IntTy);
2089 BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
2090 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002091 }
Chris Lattner48b0c972004-04-11 20:26:20 +00002092 return;
2093 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002094
Chris Lattner48b0c972004-04-11 20:26:20 +00002095 // Special case: op Reg, <const int>
2096 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner721d2d42004-03-08 01:18:36 +00002097 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002098
Chris Lattner721d2d42004-03-08 01:18:36 +00002099 // xor X, -1 -> not X
2100 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002101 static unsigned const NOTTab[] = {
2102 X86::NOT8r, X86::NOT16r, X86::NOT32r, 0, X86::NOT32r
2103 };
Chris Lattner721d2d42004-03-08 01:18:36 +00002104 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002105 if (Class == cLong) // Invert the top part too
2106 BuildMI(*MBB, IP, X86::NOT32r, 1, DestReg+1).addReg(Op0r+1);
Chris Lattner721d2d42004-03-08 01:18:36 +00002107 return;
2108 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002109
Chris Lattner721d2d42004-03-08 01:18:36 +00002110 // add X, -1 -> dec X
Chris Lattner06521672004-04-06 03:36:57 +00002111 if (OperatorClass == 0 && Op1C->isAllOnesValue() && Class != cLong) {
2112 // Note that we can't use dec for 64-bit decrements, because it does not
2113 // set the carry flag!
2114 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
Chris Lattner721d2d42004-03-08 01:18:36 +00002115 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
2116 return;
2117 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002118
Chris Lattner721d2d42004-03-08 01:18:36 +00002119 // add X, 1 -> inc X
Chris Lattner06521672004-04-06 03:36:57 +00002120 if (OperatorClass == 0 && Op1C->equalsInt(1) && Class != cLong) {
2121 // Note that we can't use inc for 64-bit increments, because it does not
2122 // set the carry flag!
2123 static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
Alkis Evlogimenosbee8a092004-04-02 18:11:32 +00002124 BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattner721d2d42004-03-08 01:18:36 +00002125 return;
2126 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002127
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002128 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00002129 // Arithmetic operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002130 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri }, // ADD
2131 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri }, // SUB
Chris Lattnerb2acc512003-10-19 21:09:10 +00002132
Chris Lattner721d2d42004-03-08 01:18:36 +00002133 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002134 { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri }, // AND
2135 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri }, // OR
2136 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri }, // XOR
Chris Lattner721d2d42004-03-08 01:18:36 +00002137 };
2138
Chris Lattner721d2d42004-03-08 01:18:36 +00002139 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner33f7fa32004-04-06 03:15:53 +00002140 unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
Chris Lattner721d2d42004-03-08 01:18:36 +00002141
Chris Lattner33f7fa32004-04-06 03:15:53 +00002142 if (Class != cLong) {
2143 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2144 return;
Chris Lattner6621ed92004-04-11 21:23:56 +00002145 }
2146
2147 // If this is a long value and the high or low bits have a special
2148 // property, emit some special cases.
2149 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
2150
2151 // If the constant is zero in the low 32-bits, just copy the low part
2152 // across and apply the normal 32-bit operation to the high parts. There
2153 // will be no carry or borrow into the top.
2154 if (Op1l == 0) {
2155 if (OperatorClass != 2) // All but and...
2156 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0r);
2157 else
2158 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2159 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg+1)
2160 .addReg(Op0r+1).addImm(Op1h);
Chris Lattner33f7fa32004-04-06 03:15:53 +00002161 return;
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002162 }
Chris Lattner6621ed92004-04-11 21:23:56 +00002163
2164 // If this is a logical operation and the top 32-bits are zero, just
2165 // operate on the lower 32.
2166 if (Op1h == 0 && OperatorClass > 1) {
2167 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg)
2168 .addReg(Op0r).addImm(Op1l);
2169 if (OperatorClass != 2) // All but and
2170 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(Op0r+1);
2171 else
2172 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2173 return;
2174 }
2175
2176 // TODO: We could handle lots of other special cases here, such as AND'ing
2177 // with 0xFFFFFFFF00000000 -> noop, etc.
2178
2179 // Otherwise, code generate the full operation with a constant.
2180 static const unsigned TopTab[] = {
2181 X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
2182 };
2183
2184 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2185 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
2186 .addReg(Op0r+1).addImm(Op1h);
2187 return;
Chris Lattner721d2d42004-03-08 01:18:36 +00002188 }
2189
2190 // Finally, handle the general case now.
Chris Lattner7ba92302004-04-06 02:13:25 +00002191 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00002192 // Arithmetic operators
Chris Lattner6621ed92004-04-11 21:23:56 +00002193 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, 0, X86::ADD32rr }, // ADD
2194 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, 0, X86::SUB32rr }, // SUB
Chris Lattner721d2d42004-03-08 01:18:36 +00002195
Chris Lattnerb2acc512003-10-19 21:09:10 +00002196 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002197 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr }, // AND
2198 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr }, // OR
2199 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr }, // XOR
Chris Lattnerb2acc512003-10-19 21:09:10 +00002200 };
Chris Lattner721d2d42004-03-08 01:18:36 +00002201
Chris Lattnerb2acc512003-10-19 21:09:10 +00002202 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner721d2d42004-03-08 01:18:36 +00002203 unsigned Op0r = getReg(Op0, MBB, IP);
2204 unsigned Op1r = getReg(Op1, MBB, IP);
2205 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2206
Chris Lattnerab1d0e02004-04-06 02:11:49 +00002207 if (Class == cLong) { // Handle the upper 32 bits of long values...
Chris Lattner721d2d42004-03-08 01:18:36 +00002208 static const unsigned TopTab[] = {
2209 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
2210 };
2211 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
2212 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2213 }
Chris Lattnere2954c82002-11-02 20:04:26 +00002214}
2215
Chris Lattner3e130a22003-01-13 00:32:26 +00002216/// doMultiply - Emit appropriate instructions to multiply together the
2217/// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
2218/// result should be given as DestTy.
2219///
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002220void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +00002221 unsigned DestReg, const Type *DestTy,
Chris Lattner8a307e82002-12-16 19:32:50 +00002222 unsigned op0Reg, unsigned op1Reg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002223 unsigned Class = getClass(DestTy);
Chris Lattner94af4142002-12-25 05:13:53 +00002224 switch (Class) {
Chris Lattner0f1c4612003-06-21 17:16:58 +00002225 case cInt:
2226 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002227 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
Chris Lattner0f1c4612003-06-21 17:16:58 +00002228 .addReg(op0Reg).addReg(op1Reg);
2229 return;
2230 case cByte:
2231 // Must use the MUL instruction, which forces use of AL...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002232 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
2233 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
2234 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
Chris Lattner0f1c4612003-06-21 17:16:58 +00002235 return;
Chris Lattner94af4142002-12-25 05:13:53 +00002236 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00002237 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
Chris Lattner94af4142002-12-25 05:13:53 +00002238 }
Brian Gaeke20244b72002-12-12 15:33:40 +00002239}
2240
Chris Lattnerb2acc512003-10-19 21:09:10 +00002241// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
2242// returns zero when the input is not exactly a power of two.
2243static unsigned ExactLog2(unsigned Val) {
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002244 if (Val == 0 || (Val & (Val-1))) return 0;
Chris Lattnerb2acc512003-10-19 21:09:10 +00002245 unsigned Count = 0;
2246 while (Val != 1) {
Chris Lattnerb2acc512003-10-19 21:09:10 +00002247 Val >>= 1;
2248 ++Count;
2249 }
2250 return Count+1;
2251}
2252
Chris Lattner462fa822004-04-11 20:56:28 +00002253
2254/// doMultiplyConst - This function is specialized to efficiently codegen an 8,
2255/// 16, or 32-bit integer multiply by a constant.
Chris Lattnerb2acc512003-10-19 21:09:10 +00002256void ISel::doMultiplyConst(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002257 MachineBasicBlock::iterator IP,
Chris Lattnerb2acc512003-10-19 21:09:10 +00002258 unsigned DestReg, const Type *DestTy,
2259 unsigned op0Reg, unsigned ConstRHS) {
Chris Lattner6ab06d52004-04-06 04:55:43 +00002260 static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
2261 static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002262 static const unsigned ADDrrTab[] = {X86::ADD8rr, X86::ADD16rr, X86::ADD32rr};
Chris Lattner6ab06d52004-04-06 04:55:43 +00002263
Chris Lattnerb2acc512003-10-19 21:09:10 +00002264 unsigned Class = getClass(DestTy);
2265
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002266 // Handle special cases here.
2267 switch (ConstRHS) {
2268 case 0:
Chris Lattner6ab06d52004-04-06 04:55:43 +00002269 BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
2270 return;
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002271 case 1:
Chris Lattner6ab06d52004-04-06 04:55:43 +00002272 BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
2273 return;
Chris Lattner9eb9b8e2004-05-04 15:47:14 +00002274 case 2:
2275 BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(op0Reg).addReg(op0Reg);
2276 return;
2277 case 3:
2278 case 5:
2279 case 9:
2280 if (Class == cInt) {
2281 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, DestReg),
2282 op0Reg, ConstRHS-1, op0Reg, 0);
2283 return;
2284 }
Chris Lattner6ab06d52004-04-06 04:55:43 +00002285 }
2286
Chris Lattnerb2acc512003-10-19 21:09:10 +00002287 // If the element size is exactly a power of 2, use a shift to get it.
2288 if (unsigned Shift = ExactLog2(ConstRHS)) {
2289 switch (Class) {
2290 default: assert(0 && "Unknown class for this function!");
2291 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002292 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002293 return;
2294 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002295 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002296 return;
2297 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002298 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002299 return;
2300 }
2301 }
Chris Lattnerc01d1232003-10-20 03:42:58 +00002302
2303 if (Class == cShort) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002304 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002305 return;
2306 } else if (Class == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002307 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002308 return;
2309 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002310
2311 // Most general case, emit a normal multiply...
Chris Lattnerb2acc512003-10-19 21:09:10 +00002312 unsigned TmpReg = makeAnotherReg(DestTy);
Chris Lattneree352852004-02-29 07:22:16 +00002313 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002314
2315 // Emit a MUL to multiply the register holding the index by
2316 // elementSize, putting the result in OffsetReg.
2317 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
2318}
2319
Chris Lattnerca9671d2002-11-02 20:28:58 +00002320/// visitMul - Multiplies are not simple binary operators because they must deal
2321/// with the EAX register explicitly.
2322///
2323void ISel::visitMul(BinaryOperator &I) {
Chris Lattner462fa822004-04-11 20:56:28 +00002324 unsigned ResultReg = getReg(I);
2325
Chris Lattner95157f72004-04-11 22:05:45 +00002326 Value *Op0 = I.getOperand(0);
2327 Value *Op1 = I.getOperand(1);
2328
2329 // Fold loads into floating point multiplies.
2330 if (getClass(Op0->getType()) == cFP) {
2331 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
2332 if (!I.swapOperands())
2333 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
2334 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2335 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2336 const Type *Ty = Op0->getType();
2337 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2338 unsigned Opcode = Ty == Type::FloatTy ? X86::FMUL32m : X86::FMUL64m;
2339
2340 unsigned BaseReg, Scale, IndexReg, Disp;
2341 getAddressingMode(LI->getOperand(0), BaseReg,
2342 Scale, IndexReg, Disp);
2343
2344 unsigned Op0r = getReg(Op0);
2345 addFullAddress(BuildMI(BB, Opcode, 2, ResultReg).addReg(Op0r),
2346 BaseReg, Scale, IndexReg, Disp);
2347 return;
2348 }
2349 }
2350
Chris Lattner462fa822004-04-11 20:56:28 +00002351 MachineBasicBlock::iterator IP = BB->end();
Chris Lattner95157f72004-04-11 22:05:45 +00002352 emitMultiply(BB, IP, Op0, Op1, ResultReg);
Chris Lattner462fa822004-04-11 20:56:28 +00002353}
2354
2355void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2356 Value *Op0, Value *Op1, unsigned DestReg) {
2357 MachineBasicBlock &BB = *MBB;
2358 TypeClass Class = getClass(Op0->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +00002359
2360 // Simple scalar multiply?
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002361 unsigned Op0Reg = getReg(Op0, &BB, IP);
Chris Lattner462fa822004-04-11 20:56:28 +00002362 switch (Class) {
2363 case cByte:
2364 case cShort:
2365 case cInt:
2366 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner462fa822004-04-11 20:56:28 +00002367 unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
2368 doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002369 } else {
Chris Lattner462fa822004-04-11 20:56:28 +00002370 unsigned Op1Reg = getReg(Op1, &BB, IP);
2371 doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002372 }
Chris Lattner462fa822004-04-11 20:56:28 +00002373 return;
2374 case cFP:
Chris Lattner6621ed92004-04-11 21:23:56 +00002375 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2376 return;
Chris Lattner462fa822004-04-11 20:56:28 +00002377 case cLong:
2378 break;
2379 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002380
Chris Lattner462fa822004-04-11 20:56:28 +00002381 // Long value. We have to do things the hard way...
2382 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2383 unsigned CLow = CI->getRawValue();
2384 unsigned CHi = CI->getRawValue() >> 32;
2385
2386 if (CLow == 0) {
2387 // If the low part of the constant is all zeros, things are simple.
2388 BuildMI(BB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2389 doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
2390 return;
2391 }
2392
2393 // Multiply the two low parts... capturing carry into EDX
2394 unsigned OverflowReg = 0;
2395 if (CLow == 1) {
2396 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
Chris Lattner028adc42004-04-06 04:29:36 +00002397 } else {
Chris Lattner462fa822004-04-11 20:56:28 +00002398 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2399 OverflowReg = makeAnotherReg(Type::UIntTy);
2400 BuildMI(BB, IP, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
2401 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2402 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1RegL); // AL*BL
Chris Lattner028adc42004-04-06 04:29:36 +00002403
Chris Lattner462fa822004-04-11 20:56:28 +00002404 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2405 BuildMI(BB, IP, X86::MOV32rr, 1,
2406 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2407 }
2408
2409 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2410 doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
2411
2412 unsigned AHBLplusOverflowReg;
2413 if (OverflowReg) {
2414 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2415 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
Chris Lattner028adc42004-04-06 04:29:36 +00002416 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
Chris Lattner462fa822004-04-11 20:56:28 +00002417 } else {
2418 AHBLplusOverflowReg = AHBLReg;
2419 }
2420
2421 if (CHi == 0) {
2422 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
2423 } else {
Chris Lattner028adc42004-04-06 04:29:36 +00002424 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
Chris Lattner462fa822004-04-11 20:56:28 +00002425 doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
Chris Lattner028adc42004-04-06 04:29:36 +00002426
Chris Lattner462fa822004-04-11 20:56:28 +00002427 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
Chris Lattner028adc42004-04-06 04:29:36 +00002428 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2429 }
Chris Lattner462fa822004-04-11 20:56:28 +00002430 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00002431 }
Chris Lattner462fa822004-04-11 20:56:28 +00002432
2433 // General 64x64 multiply
2434
2435 unsigned Op1Reg = getReg(Op1, &BB, IP);
2436 // Multiply the two low parts... capturing carry into EDX
2437 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2438 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
2439
2440 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2441 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2442 BuildMI(BB, IP, X86::MOV32rr, 1,
2443 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2444
2445 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2446 BuildMI(BB, IP, X86::IMUL32rr, 2,
2447 AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2448
2449 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2450 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2451 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2452
2453 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2454 BuildMI(BB, IP, X86::IMUL32rr, 2,
2455 ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2456
2457 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2458 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002459}
Chris Lattnerca9671d2002-11-02 20:28:58 +00002460
Chris Lattner06925362002-11-17 21:56:38 +00002461
Chris Lattnerf01729e2002-11-02 20:54:46 +00002462/// visitDivRem - Handle division and remainder instructions... these
2463/// instruction both require the same instructions to be generated, they just
2464/// select the result from a different register. Note that both of these
2465/// instructions work differently for signed and unsigned operands.
2466///
2467void ISel::visitDivRem(BinaryOperator &I) {
Chris Lattnercadff442003-10-23 17:21:43 +00002468 unsigned ResultReg = getReg(I);
Chris Lattner95157f72004-04-11 22:05:45 +00002469 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2470
2471 // Fold loads into floating point divides.
2472 if (getClass(Op0->getType()) == cFP) {
2473 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2474 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2475 const Type *Ty = Op0->getType();
2476 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2477 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIV32m : X86::FDIV64m;
2478
2479 unsigned BaseReg, Scale, IndexReg, Disp;
2480 getAddressingMode(LI->getOperand(0), BaseReg,
2481 Scale, IndexReg, Disp);
2482
2483 unsigned Op0r = getReg(Op0);
2484 addFullAddress(BuildMI(BB, Opcode, 2, ResultReg).addReg(Op0r),
2485 BaseReg, Scale, IndexReg, Disp);
2486 return;
2487 }
2488
2489 if (LoadInst *LI = dyn_cast<LoadInst>(Op0))
2490 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2491 const Type *Ty = Op0->getType();
2492 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2493 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIVR32m : X86::FDIVR64m;
2494
2495 unsigned BaseReg, Scale, IndexReg, Disp;
2496 getAddressingMode(LI->getOperand(0), BaseReg,
2497 Scale, IndexReg, Disp);
2498
2499 unsigned Op1r = getReg(Op1);
2500 addFullAddress(BuildMI(BB, Opcode, 2, ResultReg).addReg(Op1r),
2501 BaseReg, Scale, IndexReg, Disp);
2502 return;
2503 }
2504 }
2505
Chris Lattner94af4142002-12-25 05:13:53 +00002506
Chris Lattnercadff442003-10-23 17:21:43 +00002507 MachineBasicBlock::iterator IP = BB->end();
Chris Lattner95157f72004-04-11 22:05:45 +00002508 emitDivRemOperation(BB, IP, Op0, Op1,
Chris Lattner462fa822004-04-11 20:56:28 +00002509 I.getOpcode() == Instruction::Div, ResultReg);
Chris Lattnercadff442003-10-23 17:21:43 +00002510}
2511
2512void ISel::emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002513 MachineBasicBlock::iterator IP,
Chris Lattner462fa822004-04-11 20:56:28 +00002514 Value *Op0, Value *Op1, bool isDiv,
2515 unsigned ResultReg) {
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002516 const Type *Ty = Op0->getType();
2517 unsigned Class = getClass(Ty);
Chris Lattner94af4142002-12-25 05:13:53 +00002518 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002519 case cFP: // Floating point divide
Chris Lattnercadff442003-10-23 17:21:43 +00002520 if (isDiv) {
Chris Lattner6621ed92004-04-11 21:23:56 +00002521 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2522 return;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00002523 } else { // Floating point remainder...
Chris Lattner462fa822004-04-11 20:56:28 +00002524 unsigned Op0Reg = getReg(Op0, BB, IP);
2525 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00002526 MachineInstr *TheCall =
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002527 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00002528 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002529 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2530 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002531 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
2532 }
Chris Lattner94af4142002-12-25 05:13:53 +00002533 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00002534 case cLong: {
2535 static const char *FnName[] =
2536 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
Chris Lattner462fa822004-04-11 20:56:28 +00002537 unsigned Op0Reg = getReg(Op0, BB, IP);
2538 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattner8ebf1c32004-04-11 21:09:14 +00002539 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
Chris Lattner3e130a22003-01-13 00:32:26 +00002540 MachineInstr *TheCall =
2541 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
2542
2543 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002544 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2545 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002546 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
2547 return;
2548 }
2549 case cByte: case cShort: case cInt:
Misha Brukmancf00c4a2003-10-10 17:57:28 +00002550 break; // Small integrals, handled below...
Chris Lattner3e130a22003-01-13 00:32:26 +00002551 default: assert(0 && "Unknown class!");
Chris Lattner94af4142002-12-25 05:13:53 +00002552 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00002553
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002554 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002555 static const unsigned NEGOpcode[] = { X86::NEG8r, X86::NEG16r, X86::NEG32r };
2556 static const unsigned SAROpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
2557 static const unsigned SHROpcode[]={ X86::SHR8ri, X86::SHR16ri, X86::SHR32ri };
2558 static const unsigned ADDOpcode[]={ X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
2559
2560 // Special case signed division by power of 2.
2561 if (isDiv)
2562 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2563 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2564 int V = CI->getValue();
2565
2566 if (V == 1) { // X /s 1 => X
2567 unsigned Op0Reg = getReg(Op0, BB, IP);
2568 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2569 return;
2570 }
2571
2572 if (V == -1) { // X /s -1 => -X
2573 unsigned Op0Reg = getReg(Op0, BB, IP);
2574 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2575 return;
2576 }
2577
2578 bool isNeg = false;
2579 if (V < 0) { // Not a positive power of 2?
2580 V = -V;
2581 isNeg = true; // Maybe it's a negative power of 2.
2582 }
2583 if (unsigned Log = ExactLog2(V)) {
2584 --Log;
2585 unsigned Op0Reg = getReg(Op0, BB, IP);
2586 unsigned TmpReg = makeAnotherReg(Op0->getType());
2587 if (Log != 1)
2588 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg)
2589 .addReg(Op0Reg).addImm(Log-1);
2590 else
2591 BuildMI(*BB, IP, MovOpcode[Class], 1, TmpReg).addReg(Op0Reg);
2592 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2593 BuildMI(*BB, IP, SHROpcode[Class], 2, TmpReg2)
2594 .addReg(TmpReg).addImm(32-Log);
2595 unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2596 BuildMI(*BB, IP, ADDOpcode[Class], 2, TmpReg3)
2597 .addReg(Op0Reg).addReg(TmpReg2);
2598
2599 unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2600 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg4)
2601 .addReg(Op0Reg).addImm(Log);
2602 if (isNeg)
2603 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg4);
2604 return;
2605 }
2606 }
2607
2608 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002609 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
Chris Lattnerf01729e2002-11-02 20:54:46 +00002610 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
2611
2612 static const unsigned DivOpcode[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002613 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
2614 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
Chris Lattnerf01729e2002-11-02 20:54:46 +00002615 };
2616
Chris Lattnerf01729e2002-11-02 20:54:46 +00002617 unsigned Reg = Regs[Class];
2618 unsigned ExtReg = ExtRegs[Class];
Chris Lattnerf01729e2002-11-02 20:54:46 +00002619
2620 // Put the first operand into one of the A registers...
Chris Lattner462fa822004-04-11 20:56:28 +00002621 unsigned Op0Reg = getReg(Op0, BB, IP);
2622 unsigned Op1Reg = getReg(Op1, BB, IP);
Chris Lattneree352852004-02-29 07:22:16 +00002623 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002624
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002625 if (Ty->isSigned()) {
Chris Lattnerf01729e2002-11-02 20:54:46 +00002626 // Emit a sign extension instruction...
Chris Lattner462fa822004-04-11 20:56:28 +00002627 unsigned ShiftResult = makeAnotherReg(Op0->getType());
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002628 BuildMI(*BB, IP, SAROpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
Chris Lattneree352852004-02-29 07:22:16 +00002629 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002630
2631 // Emit the appropriate divide or remainder instruction...
2632 BuildMI(*BB, IP, DivOpcode[1][Class], 1).addReg(Op1Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002633 } else {
Alkis Evlogimenosf998a7e2004-01-12 07:22:45 +00002634 // If unsigned, emit a zeroing instruction... (reg = 0)
Chris Lattneree352852004-02-29 07:22:16 +00002635 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002636
Chris Lattnerc8af02c2004-05-04 19:33:58 +00002637 // Emit the appropriate divide or remainder instruction...
2638 BuildMI(*BB, IP, DivOpcode[0][Class], 1).addReg(Op1Reg);
2639 }
Chris Lattner06925362002-11-17 21:56:38 +00002640
Chris Lattnerf01729e2002-11-02 20:54:46 +00002641 // Figure out which register we want to pick the result out of...
Chris Lattnercadff442003-10-23 17:21:43 +00002642 unsigned DestReg = isDiv ? Reg : ExtReg;
Chris Lattnerf01729e2002-11-02 20:54:46 +00002643
Chris Lattnerf01729e2002-11-02 20:54:46 +00002644 // Put the result into the destination register...
Chris Lattneree352852004-02-29 07:22:16 +00002645 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +00002646}
Chris Lattnere2954c82002-11-02 20:04:26 +00002647
Chris Lattner06925362002-11-17 21:56:38 +00002648
Brian Gaekea1719c92002-10-31 23:03:59 +00002649/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2650/// for constant immediate shift values, and for constant immediate
2651/// shift values equal to 1. Even the general case is sort of special,
2652/// because the shift amount has to be in CL, not just any old register.
2653///
Chris Lattner3e130a22003-01-13 00:32:26 +00002654void ISel::visitShiftInst(ShiftInst &I) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002655 MachineBasicBlock::iterator IP = BB->end ();
2656 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2657 I.getOpcode () == Instruction::Shl, I.getType (),
2658 getReg (I));
2659}
2660
2661/// emitShiftOperation - Common code shared between visitShiftInst and
2662/// constant expression support.
2663void ISel::emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002664 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002665 Value *Op, Value *ShiftAmount, bool isLeftShift,
2666 const Type *ResultTy, unsigned DestReg) {
2667 unsigned SrcReg = getReg (Op, MBB, IP);
2668 bool isSigned = ResultTy->isSigned ();
2669 unsigned Class = getClass (ResultTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00002670
2671 static const unsigned ConstantOperand[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002672 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 }, // SHR
2673 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 }, // SAR
2674 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SHL
2675 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00002676 };
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002677
Chris Lattner3e130a22003-01-13 00:32:26 +00002678 static const unsigned NonConstantOperand[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002679 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
2680 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
2681 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
2682 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00002683 };
Chris Lattner796df732002-11-02 00:44:25 +00002684
Chris Lattner3e130a22003-01-13 00:32:26 +00002685 // Longs, as usual, are handled specially...
2686 if (Class == cLong) {
2687 // If we have a constant shift, we can generate much more efficient code
2688 // than otherwise...
2689 //
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002690 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002691 unsigned Amount = CUI->getValue();
2692 if (Amount < 32) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002693 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2694 if (isLeftShift) {
Chris Lattneree352852004-02-29 07:22:16 +00002695 BuildMI(*MBB, IP, Opc[3], 3,
2696 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
2697 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002698 } else {
Chris Lattneree352852004-02-29 07:22:16 +00002699 BuildMI(*MBB, IP, Opc[3], 3,
2700 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
2701 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002702 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002703 } else { // Shifting more than 32 bits
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002704 Amount -= 32;
2705 if (isLeftShift) {
Chris Lattner722070e2004-04-06 03:42:38 +00002706 if (Amount != 0) {
2707 BuildMI(*MBB, IP, X86::SHL32ri, 2,
2708 DestReg + 1).addReg(SrcReg).addImm(Amount);
2709 } else {
2710 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
2711 }
2712 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002713 } else {
Chris Lattner722070e2004-04-06 03:42:38 +00002714 if (Amount != 0) {
2715 BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
2716 DestReg).addReg(SrcReg+1).addImm(Amount);
2717 } else {
2718 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
2719 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002720 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002721 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002722 }
2723 } else {
Chris Lattner9171ef52003-06-01 01:56:54 +00002724 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2725
2726 if (!isLeftShift && isSigned) {
2727 // If this is a SHR of a Long, then we need to do funny sign extension
2728 // stuff. TmpReg gets the value to use as the high-part if we are
2729 // shifting more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002730 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
Chris Lattner9171ef52003-06-01 01:56:54 +00002731 } else {
2732 // Other shifts use a fixed zero value if the shift is more than 32
2733 // bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002734 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
Chris Lattner9171ef52003-06-01 01:56:54 +00002735 }
2736
2737 // Initialize CL with the shift amount...
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002738 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002739 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002740
2741 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2742 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2743 if (isLeftShift) {
2744 // TmpReg2 = shld inHi, inLo
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002745 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
Chris Lattneree352852004-02-29 07:22:16 +00002746 .addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002747 // TmpReg3 = shl inLo, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002748 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002749
2750 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002751 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00002752
2753 // DestHi = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002754 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002755 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
2756 // DestLo = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002757 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002758 DestReg).addReg(TmpReg3).addReg(TmpReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002759 } else {
2760 // TmpReg2 = shrd inLo, inHi
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002761 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
Chris Lattneree352852004-02-29 07:22:16 +00002762 .addReg(SrcReg+1);
Chris Lattner9171ef52003-06-01 01:56:54 +00002763 // TmpReg3 = s[ah]r inHi, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002764 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
Chris Lattner9171ef52003-06-01 01:56:54 +00002765 .addReg(SrcReg+1);
2766
2767 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002768 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00002769
2770 // DestLo = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002771 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002772 DestReg).addReg(TmpReg2).addReg(TmpReg3);
2773
2774 // DestHi = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002775 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002776 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
2777 }
Brian Gaekea1719c92002-10-31 23:03:59 +00002778 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002779 return;
2780 }
Chris Lattnere9913f22002-11-02 01:41:55 +00002781
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002782 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002783 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2784 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002785
Chris Lattner3e130a22003-01-13 00:32:26 +00002786 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00002787 BuildMI(*MBB, IP, Opc[Class], 2,
2788 DestReg).addReg(SrcReg).addImm(CUI->getValue());
Chris Lattner3e130a22003-01-13 00:32:26 +00002789 } else { // The shift amount is non-constant.
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002790 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002791 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002792
Chris Lattner3e130a22003-01-13 00:32:26 +00002793 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00002794 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002795 }
2796}
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002797
Chris Lattner3e130a22003-01-13 00:32:26 +00002798
Chris Lattner721d2d42004-03-08 01:18:36 +00002799void ISel::getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
2800 unsigned &IndexReg, unsigned &Disp) {
2801 BaseReg = 0; Scale = 1; IndexReg = 0; Disp = 0;
2802 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
2803 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
2804 BaseReg, Scale, IndexReg, Disp))
2805 return;
2806 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2807 if (CE->getOpcode() == Instruction::GetElementPtr)
2808 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
2809 BaseReg, Scale, IndexReg, Disp))
2810 return;
2811 }
2812
2813 // If it's not foldable, reset addr mode.
2814 BaseReg = getReg(Addr);
2815 Scale = 1; IndexReg = 0; Disp = 0;
2816}
2817
2818
Chris Lattner6fc3c522002-11-17 21:11:55 +00002819/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
Chris Lattnere8f0d922002-12-24 00:03:11 +00002820/// instruction. The load and store instructions are the only place where we
2821/// need to worry about the memory layout of the target machine.
Chris Lattner6fc3c522002-11-17 21:11:55 +00002822///
2823void ISel::visitLoadInst(LoadInst &I) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00002824 // Check to see if this load instruction is going to be folded into a binary
2825 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
2826 // pattern matching instruction selector be nice?
Chris Lattner95157f72004-04-11 22:05:45 +00002827 unsigned Class = getClassB(I.getType());
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002828 if (I.hasOneUse()) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00002829 Instruction *User = cast<Instruction>(I.use_back());
2830 switch (User->getOpcode()) {
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002831 case Instruction::Cast:
2832 // If this is a cast from a signed-integer type to a floating point type,
2833 // fold the cast here.
2834 if (getClass(User->getType()) == cFP &&
2835 (I.getType() == Type::ShortTy || I.getType() == Type::IntTy ||
2836 I.getType() == Type::LongTy)) {
2837 unsigned DestReg = getReg(User);
2838 static const unsigned Opcode[] = {
2839 0/*BYTE*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m
2840 };
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002841 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
2842 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
2843 addFullAddress(BuildMI(BB, Opcode[Class], 5, DestReg),
2844 BaseReg, Scale, IndexReg, Disp);
2845 return;
2846 } else {
2847 User = 0;
2848 }
2849 break;
Chris Lattner13c07fe2004-04-12 00:12:04 +00002850
Chris Lattner7dee5da2004-03-08 01:58:35 +00002851 case Instruction::Add:
2852 case Instruction::Sub:
2853 case Instruction::And:
2854 case Instruction::Or:
2855 case Instruction::Xor:
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002856 if (Class == cLong) User = 0;
Chris Lattner7dee5da2004-03-08 01:58:35 +00002857 break;
Chris Lattner95157f72004-04-11 22:05:45 +00002858 case Instruction::Mul:
2859 case Instruction::Div:
Chris Lattner13c07fe2004-04-12 00:12:04 +00002860 if (Class != cFP) User = 0;
Chris Lattnerfeac3e12004-04-11 23:21:26 +00002861 break; // Folding only implemented for floating point.
Chris Lattner95157f72004-04-11 22:05:45 +00002862 default: User = 0; break;
Chris Lattner7dee5da2004-03-08 01:58:35 +00002863 }
2864
2865 if (User) {
2866 // Okay, we found a user. If the load is the first operand and there is
2867 // no second operand load, reverse the operand ordering. Note that this
2868 // can fail for a subtract (ie, no change will be made).
2869 if (!isa<LoadInst>(User->getOperand(1)))
2870 cast<BinaryOperator>(User)->swapOperands();
2871
2872 // Okay, now that everything is set up, if this load is used by the second
2873 // operand, and if there are no instructions that invalidate the load
2874 // before the binary operator, eliminate the load.
2875 if (User->getOperand(1) == &I &&
2876 isSafeToFoldLoadIntoInstruction(I, *User))
2877 return; // Eliminate the load!
Chris Lattner95157f72004-04-11 22:05:45 +00002878
2879 // If this is a floating point sub or div, we won't be able to swap the
2880 // operands, but we will still be able to eliminate the load.
2881 if (Class == cFP && User->getOperand(0) == &I &&
2882 !isa<LoadInst>(User->getOperand(1)) &&
2883 (User->getOpcode() == Instruction::Sub ||
2884 User->getOpcode() == Instruction::Div) &&
2885 isSafeToFoldLoadIntoInstruction(I, *User))
2886 return; // Eliminate the load!
Chris Lattner7dee5da2004-03-08 01:58:35 +00002887 }
2888 }
2889
Chris Lattner94af4142002-12-25 05:13:53 +00002890 unsigned DestReg = getReg(I);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002891 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
Chris Lattner721d2d42004-03-08 01:18:36 +00002892 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
Chris Lattnere8f0d922002-12-24 00:03:11 +00002893
Chris Lattner6ac1d712003-10-20 04:48:06 +00002894 if (Class == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002895 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002896 BaseReg, Scale, IndexReg, Disp);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002897 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002898 BaseReg, Scale, IndexReg, Disp+4);
Chris Lattner94af4142002-12-25 05:13:53 +00002899 return;
2900 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00002901
Chris Lattner6ac1d712003-10-20 04:48:06 +00002902 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002903 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m
Chris Lattner3e130a22003-01-13 00:32:26 +00002904 };
Chris Lattner6ac1d712003-10-20 04:48:06 +00002905 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002906 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
Chris Lattnerb6bac512004-02-25 06:13:04 +00002907 addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
2908 BaseReg, Scale, IndexReg, Disp);
Chris Lattner3e130a22003-01-13 00:32:26 +00002909}
2910
Chris Lattner6fc3c522002-11-17 21:11:55 +00002911/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
2912/// instruction.
2913///
2914void ISel::visitStoreInst(StoreInst &I) {
Chris Lattner721d2d42004-03-08 01:18:36 +00002915 unsigned BaseReg, Scale, IndexReg, Disp;
2916 getAddressingMode(I.getOperand(1), BaseReg, Scale, IndexReg, Disp);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002917
Chris Lattner6c09db22003-10-20 04:11:23 +00002918 const Type *ValTy = I.getOperand(0)->getType();
2919 unsigned Class = getClassB(ValTy);
Chris Lattner6ac1d712003-10-20 04:48:06 +00002920
Chris Lattner5a830962004-02-25 02:56:58 +00002921 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
2922 uint64_t Val = CI->getRawValue();
2923 if (Class == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002924 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002925 BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002926 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002927 BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
Chris Lattner5a830962004-02-25 02:56:58 +00002928 } else {
2929 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002930 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
Chris Lattner5a830962004-02-25 02:56:58 +00002931 };
2932 unsigned Opcode = Opcodes[Class];
Chris Lattnerb6bac512004-02-25 06:13:04 +00002933 addFullAddress(BuildMI(BB, Opcode, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002934 BaseReg, Scale, IndexReg, Disp).addImm(Val);
Chris Lattner5a830962004-02-25 02:56:58 +00002935 }
2936 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002937 addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002938 BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
Chris Lattnere7a31c92004-05-07 21:18:15 +00002939 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) {
2940 // Store constant FP values with integer instructions to avoid having to
2941 // load the constants from the constant pool then do a store.
2942 if (CFP->getType() == Type::FloatTy) {
2943 union {
2944 unsigned I;
2945 float F;
2946 } V;
2947 V.F = CFP->getValue();
2948 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2949 BaseReg, Scale, IndexReg, Disp).addImm(V.I);
Chris Lattner5a830962004-02-25 02:56:58 +00002950 } else {
Chris Lattnere7a31c92004-05-07 21:18:15 +00002951 union {
2952 uint64_t I;
2953 double F;
2954 } V;
2955 V.F = CFP->getValue();
2956 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2957 BaseReg, Scale, IndexReg, Disp).addImm((unsigned)V.I);
2958 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2959 BaseReg, Scale, IndexReg, Disp+4).addImm(
2960 unsigned(V.I >> 32));
Chris Lattner5a830962004-02-25 02:56:58 +00002961 }
Chris Lattnere7a31c92004-05-07 21:18:15 +00002962
2963 } else if (Class == cLong) {
2964 unsigned ValReg = getReg(I.getOperand(0));
2965 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2966 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2967 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2968 BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
2969 } else {
2970 unsigned ValReg = getReg(I.getOperand(0));
2971 static const unsigned Opcodes[] = {
2972 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
2973 };
2974 unsigned Opcode = Opcodes[Class];
2975 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
2976 addFullAddress(BuildMI(BB, Opcode, 1+4),
2977 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
Chris Lattner94af4142002-12-25 05:13:53 +00002978 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00002979}
2980
2981
Misha Brukman538607f2004-03-01 23:53:11 +00002982/// visitCastInst - Here we have various kinds of copying with or without sign
2983/// extension going on.
2984///
Chris Lattner3e130a22003-01-13 00:32:26 +00002985void ISel::visitCastInst(CastInst &CI) {
Chris Lattnerf5854472003-06-21 16:01:24 +00002986 Value *Op = CI.getOperand(0);
Chris Lattner427aeb42004-04-11 19:21:59 +00002987
Chris Lattner99382862004-04-12 00:23:04 +00002988 unsigned SrcClass = getClassB(Op->getType());
2989 unsigned DestClass = getClassB(CI.getType());
2990 // Noop casts are not emitted: getReg will return the source operand as the
2991 // register to use for any uses of the noop cast.
2992 if (DestClass == SrcClass)
Chris Lattner427aeb42004-04-11 19:21:59 +00002993 return;
2994
Chris Lattnerf5854472003-06-21 16:01:24 +00002995 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2996 // of the case are GEP instructions, then the cast does not need to be
2997 // generated explicitly, it will be folded into the GEP.
Chris Lattner99382862004-04-12 00:23:04 +00002998 if (DestClass == cLong && SrcClass == cInt) {
Chris Lattnerf5854472003-06-21 16:01:24 +00002999 bool AllUsesAreGEPs = true;
3000 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
3001 if (!isa<GetElementPtrInst>(*I)) {
3002 AllUsesAreGEPs = false;
3003 break;
3004 }
3005
3006 // No need to codegen this cast if all users are getelementptr instrs...
3007 if (AllUsesAreGEPs) return;
3008 }
3009
Chris Lattner99382862004-04-12 00:23:04 +00003010 // If this cast converts a load from a short,int, or long integer to a FP
3011 // value, we will have folded this cast away.
3012 if (DestClass == cFP && isa<LoadInst>(Op) && Op->hasOneUse() &&
3013 (Op->getType() == Type::ShortTy || Op->getType() == Type::IntTy ||
3014 Op->getType() == Type::LongTy))
3015 return;
3016
3017
Chris Lattner548f61d2003-04-23 17:22:12 +00003018 unsigned DestReg = getReg(CI);
3019 MachineBasicBlock::iterator MI = BB->end();
Chris Lattnerf5854472003-06-21 16:01:24 +00003020 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
Chris Lattner548f61d2003-04-23 17:22:12 +00003021}
3022
Misha Brukman538607f2004-03-01 23:53:11 +00003023/// emitCastOperation - Common code shared between visitCastInst and constant
3024/// expression cast support.
3025///
Chris Lattner548f61d2003-04-23 17:22:12 +00003026void ISel::emitCastOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003027 MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +00003028 Value *Src, const Type *DestTy,
3029 unsigned DestReg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003030 const Type *SrcTy = Src->getType();
3031 unsigned SrcClass = getClassB(SrcTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00003032 unsigned DestClass = getClassB(DestTy);
Chris Lattnerfeac3e12004-04-11 23:21:26 +00003033 unsigned SrcReg = getReg(Src, BB, IP);
3034
Chris Lattner3e130a22003-01-13 00:32:26 +00003035 // Implement casts to bool by using compare on the operand followed by set if
3036 // not zero on the result.
3037 if (DestTy == Type::BoolTy) {
Chris Lattner20772542003-06-01 03:38:24 +00003038 switch (SrcClass) {
3039 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003040 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003041 break;
3042 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003043 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003044 break;
3045 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003046 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00003047 break;
3048 case cLong: {
3049 unsigned TmpReg = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003050 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
Chris Lattner20772542003-06-01 03:38:24 +00003051 break;
3052 }
3053 case cFP:
Chris Lattneree352852004-02-29 07:22:16 +00003054 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003055 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +00003056 BuildMI(*BB, IP, X86::SAHF, 1);
Chris Lattner311ca2e2004-02-23 03:21:41 +00003057 break;
Chris Lattner20772542003-06-01 03:38:24 +00003058 }
3059
3060 // If the zero flag is not set, then the value is true, set the byte to
3061 // true.
Chris Lattneree352852004-02-29 07:22:16 +00003062 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
Chris Lattner94af4142002-12-25 05:13:53 +00003063 return;
3064 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003065
3066 static const unsigned RegRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003067 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
Chris Lattner3e130a22003-01-13 00:32:26 +00003068 };
3069
3070 // Implement casts between values of the same type class (as determined by
3071 // getClass) by using a register-to-register move.
3072 if (SrcClass == DestClass) {
3073 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
Chris Lattneree352852004-02-29 07:22:16 +00003074 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003075 } else if (SrcClass == cFP) {
3076 if (SrcTy == Type::FloatTy) { // double -> float
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003077 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
Chris Lattneree352852004-02-29 07:22:16 +00003078 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003079 } else { // float -> double
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003080 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
3081 "Unknown cFP member!");
3082 // Truncate from double to float by storing to memory as short, then
3083 // reading it back.
3084 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
Chris Lattner3e130a22003-01-13 00:32:26 +00003085 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003086 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
3087 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003088 }
3089 } else if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003090 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3091 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003092 } else {
Chris Lattnerc53544a2003-05-12 20:16:58 +00003093 assert(0 && "Cannot handle this type of cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00003094 abort();
Brian Gaeked474e9c2002-12-06 10:49:33 +00003095 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003096 return;
3097 }
3098
3099 // Handle cast of SMALLER int to LARGER int using a move with sign extension
3100 // or zero extension, depending on whether the source type was signed.
3101 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
3102 SrcClass < DestClass) {
3103 bool isLong = DestClass == cLong;
3104 if (isLong) DestClass = cInt;
3105
3106 static const unsigned Opc[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003107 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
3108 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
Chris Lattner3e130a22003-01-13 00:32:26 +00003109 };
3110
Chris Lattner96e3b422004-05-09 22:28:45 +00003111 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
Chris Lattneree352852004-02-29 07:22:16 +00003112 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
Chris Lattner548f61d2003-04-23 17:22:12 +00003113 DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003114
3115 if (isLong) { // Handle upper 32 bits as appropriate...
3116 if (isUnsigned) // Zero out top bits...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003117 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00003118 else // Sign extend bottom half...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003119 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
Brian Gaeked474e9c2002-12-06 10:49:33 +00003120 }
Chris Lattner3e130a22003-01-13 00:32:26 +00003121 return;
3122 }
3123
3124 // Special case long -> int ...
3125 if (SrcClass == cLong && DestClass == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003126 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003127 return;
3128 }
3129
3130 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
3131 // move out of AX or AL.
3132 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
3133 && SrcClass > DestClass) {
3134 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
Chris Lattneree352852004-02-29 07:22:16 +00003135 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
3136 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
Chris Lattner3e130a22003-01-13 00:32:26 +00003137 return;
3138 }
3139
3140 // Handle casts from integer to floating point now...
3141 if (DestClass == cFP) {
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003142 // Promote the integer to a type supported by FLD. We do this because there
3143 // are no unsigned FLD instructions, so we must promote an unsigned value to
3144 // a larger signed value, then use FLD on the larger value.
3145 //
3146 const Type *PromoteType = 0;
Chris Lattner85aa7092004-04-10 18:32:01 +00003147 unsigned PromoteOpcode = 0;
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003148 unsigned RealDestReg = DestReg;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003149 switch (SrcTy->getPrimitiveID()) {
3150 case Type::BoolTyID:
3151 case Type::SByteTyID:
3152 // We don't have the facilities for directly loading byte sized data from
3153 // memory (even signed). Promote it to 16 bits.
3154 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003155 PromoteOpcode = X86::MOVSX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003156 break;
3157 case Type::UByteTyID:
3158 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003159 PromoteOpcode = X86::MOVZX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003160 break;
3161 case Type::UShortTyID:
3162 PromoteType = Type::IntTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003163 PromoteOpcode = X86::MOVZX32rr16;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003164 break;
3165 case Type::UIntTyID: {
3166 // Make a 64 bit temporary... and zero out the top of it...
3167 unsigned TmpReg = makeAnotherReg(Type::LongTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003168 BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
3169 BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003170 SrcTy = Type::LongTy;
3171 SrcClass = cLong;
3172 SrcReg = TmpReg;
3173 break;
3174 }
3175 case Type::ULongTyID:
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003176 // Don't fild into the read destination.
3177 DestReg = makeAnotherReg(Type::DoubleTy);
3178 break;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003179 default: // No promotion needed...
3180 break;
3181 }
3182
3183 if (PromoteType) {
3184 unsigned TmpReg = makeAnotherReg(PromoteType);
Chris Lattner7b92de1e2004-04-06 19:29:36 +00003185 BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00003186 SrcTy = PromoteType;
3187 SrcClass = getClass(PromoteType);
Chris Lattner3e130a22003-01-13 00:32:26 +00003188 SrcReg = TmpReg;
3189 }
3190
3191 // Spill the integer to memory and reload it from there...
Chris Lattnerb6bac512004-02-25 06:13:04 +00003192 int FrameIdx =
3193 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
Chris Lattner3e130a22003-01-13 00:32:26 +00003194
3195 if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003196 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Chris Lattneree352852004-02-29 07:22:16 +00003197 FrameIdx).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003198 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003199 FrameIdx, 4).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003200 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003201 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
Chris Lattneree352852004-02-29 07:22:16 +00003202 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
3203 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003204 }
3205
3206 static const unsigned Op2[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003207 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
Chris Lattneree352852004-02-29 07:22:16 +00003208 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003209
3210 // We need special handling for unsigned 64-bit integer sources. If the
3211 // input number has the "sign bit" set, then we loaded it incorrectly as a
3212 // negative 64-bit number. In this case, add an offset value.
3213 if (SrcTy == Type::ULongTy) {
3214 // Emit a test instruction to see if the dynamic input value was signed.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003215 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003216
Chris Lattnerb6bac512004-02-25 06:13:04 +00003217 // If the sign bit is set, get a pointer to an offset, otherwise get a
3218 // pointer to a zero.
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003219 MachineConstantPool *CP = F->getConstantPool();
3220 unsigned Zero = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003221 Constant *Null = Constant::getNullValue(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003222 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003223 CP->getConstantPoolIndex(Null));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003224 unsigned Offset = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003225 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
3226
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003227 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003228 CP->getConstantPoolIndex(OffsetCst));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003229 unsigned Addr = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003230 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003231
3232 // Load the constant for an add. FIXME: this could make an 'fadd' that
3233 // reads directly from memory, but we don't support these yet.
3234 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003235 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003236
Chris Lattneree352852004-02-29 07:22:16 +00003237 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
3238 .addReg(ConstReg).addReg(DestReg);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00003239 }
3240
Chris Lattner3e130a22003-01-13 00:32:26 +00003241 return;
3242 }
3243
3244 // Handle casts from floating point to integer now...
3245 if (SrcClass == cFP) {
3246 // Change the floating point control register to use "round towards zero"
3247 // mode when truncating to an integer value.
3248 //
3249 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003250 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003251
3252 // Load the old value of the high byte of the control word...
3253 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003254 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
Chris Lattneree352852004-02-29 07:22:16 +00003255 CWFrameIdx, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +00003256
3257 // Set the high part to be round to zero...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003258 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00003259 CWFrameIdx, 1).addImm(12);
Chris Lattner3e130a22003-01-13 00:32:26 +00003260
3261 // Reload the modified control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003262 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003263
3264 // Restore the memory image of control word to original value
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003265 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003266 CWFrameIdx, 1).addReg(HighPartOfCW);
Chris Lattner3e130a22003-01-13 00:32:26 +00003267
3268 // We don't have the facilities for directly storing byte sized data to
3269 // memory. Promote it to 16 bits. We also must promote unsigned values to
3270 // larger classes because we only have signed FP stores.
3271 unsigned StoreClass = DestClass;
3272 const Type *StoreTy = DestTy;
3273 if (StoreClass == cByte || DestTy->isUnsigned())
3274 switch (StoreClass) {
3275 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
3276 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
3277 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
Brian Gaeked4615052003-07-18 20:23:43 +00003278 // The following treatment of cLong may not be perfectly right,
3279 // but it survives chains of casts of the form
3280 // double->ulong->double.
3281 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
Chris Lattner3e130a22003-01-13 00:32:26 +00003282 default: assert(0 && "Unknown store class!");
3283 }
3284
3285 // Spill the integer to memory and reload it from there...
3286 int FrameIdx =
3287 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
3288
3289 static const unsigned Op1[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003290 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
Chris Lattneree352852004-02-29 07:22:16 +00003291 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
3292 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00003293
3294 if (DestClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003295 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
3296 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
Chris Lattneree352852004-02-29 07:22:16 +00003297 FrameIdx, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +00003298 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003299 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
Chris Lattneree352852004-02-29 07:22:16 +00003300 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003301 }
3302
3303 // Reload the original control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003304 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00003305 return;
3306 }
3307
Brian Gaeked474e9c2002-12-06 10:49:33 +00003308 // Anything we haven't handled already, we can't (yet) handle at all.
Chris Lattnerc53544a2003-05-12 20:16:58 +00003309 assert(0 && "Unhandled cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00003310 abort();
Brian Gaekefa8d5712002-11-22 11:07:01 +00003311}
Brian Gaekea1719c92002-10-31 23:03:59 +00003312
Chris Lattner73815062003-10-18 05:56:40 +00003313/// visitVANextInst - Implement the va_next instruction...
Chris Lattnereca195e2003-05-08 19:44:13 +00003314///
Chris Lattner73815062003-10-18 05:56:40 +00003315void ISel::visitVANextInst(VANextInst &I) {
3316 unsigned VAList = getReg(I.getOperand(0));
Chris Lattnereca195e2003-05-08 19:44:13 +00003317 unsigned DestReg = getReg(I);
3318
Chris Lattnereca195e2003-05-08 19:44:13 +00003319 unsigned Size;
Chris Lattner73815062003-10-18 05:56:40 +00003320 switch (I.getArgType()->getPrimitiveID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00003321 default:
3322 std::cerr << I;
Chris Lattner73815062003-10-18 05:56:40 +00003323 assert(0 && "Error: bad type for va_next instruction!");
Chris Lattnereca195e2003-05-08 19:44:13 +00003324 return;
3325 case Type::PointerTyID:
3326 case Type::UIntTyID:
3327 case Type::IntTyID:
3328 Size = 4;
Chris Lattnereca195e2003-05-08 19:44:13 +00003329 break;
3330 case Type::ULongTyID:
3331 case Type::LongTyID:
Chris Lattnereca195e2003-05-08 19:44:13 +00003332 case Type::DoubleTyID:
3333 Size = 8;
Chris Lattnereca195e2003-05-08 19:44:13 +00003334 break;
3335 }
3336
3337 // Increment the VAList pointer...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003338 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
Chris Lattner73815062003-10-18 05:56:40 +00003339}
Chris Lattnereca195e2003-05-08 19:44:13 +00003340
Chris Lattner73815062003-10-18 05:56:40 +00003341void ISel::visitVAArgInst(VAArgInst &I) {
3342 unsigned VAList = getReg(I.getOperand(0));
3343 unsigned DestReg = getReg(I);
3344
3345 switch (I.getType()->getPrimitiveID()) {
3346 default:
3347 std::cerr << I;
3348 assert(0 && "Error: bad type for va_next instruction!");
3349 return;
3350 case Type::PointerTyID:
3351 case Type::UIntTyID:
3352 case Type::IntTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003353 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00003354 break;
3355 case Type::ULongTyID:
3356 case Type::LongTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003357 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3358 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
Chris Lattner73815062003-10-18 05:56:40 +00003359 break;
3360 case Type::DoubleTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003361 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00003362 break;
3363 }
Chris Lattnereca195e2003-05-08 19:44:13 +00003364}
3365
Misha Brukman538607f2004-03-01 23:53:11 +00003366/// visitGetElementPtrInst - instruction-select GEP instructions
3367///
Chris Lattner3e130a22003-01-13 00:32:26 +00003368void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00003369 // If this GEP instruction will be folded into all of its users, we don't need
3370 // to explicitly calculate it!
3371 unsigned A, B, C, D;
3372 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
3373 // Check all of the users of the instruction to see if they are loads and
3374 // stores.
3375 bool AllWillFold = true;
3376 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
3377 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
3378 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
3379 cast<Instruction>(*UI)->getOperand(0) == &I) {
3380 AllWillFold = false;
3381 break;
3382 }
3383
3384 // If the instruction is foldable, and will be folded into all users, don't
3385 // emit it!
3386 if (AllWillFold) return;
3387 }
3388
Chris Lattner3e130a22003-01-13 00:32:26 +00003389 unsigned outputReg = getReg(I);
Chris Lattner827832c2004-02-22 17:05:38 +00003390 emitGEPOperation(BB, BB->end(), I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +00003391 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +00003392}
3393
Chris Lattner985fe3d2004-02-25 03:45:50 +00003394/// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
3395/// GEPTypes (the derived types being stepped through at each level). On return
3396/// from this function, if some indexes of the instruction are representable as
3397/// an X86 lea instruction, the machine operands are put into the Ops
3398/// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
3399/// lists. Otherwise, GEPOps.size() is returned. If this returns a an
3400/// addressing mode that only partially consumes the input, the BaseReg input of
3401/// the addressing mode must be left free.
3402///
3403/// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
3404///
Chris Lattnerb6bac512004-02-25 06:13:04 +00003405void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
3406 std::vector<Value*> &GEPOps,
3407 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
3408 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
3409 const TargetData &TD = TM.getTargetData();
3410
Chris Lattner985fe3d2004-02-25 03:45:50 +00003411 // Clear out the state we are working with...
Chris Lattnerb6bac512004-02-25 06:13:04 +00003412 BaseReg = 0; // No base register
3413 Scale = 1; // Unit scale
3414 IndexReg = 0; // No index register
3415 Disp = 0; // No displacement
3416
Chris Lattner985fe3d2004-02-25 03:45:50 +00003417 // While there are GEP indexes that can be folded into the current address,
3418 // keep processing them.
3419 while (!GEPTypes.empty()) {
3420 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
3421 // It's a struct access. CUI is the index into the structure,
3422 // which names the field. This index must have unsigned type.
3423 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
3424
3425 // Use the TargetData structure to pick out what the layout of the
3426 // structure is in memory. Since the structure index must be constant, we
3427 // can get its value and use it to find the right byte offset from the
3428 // StructLayout class's list of structure member offsets.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003429 Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
Chris Lattner985fe3d2004-02-25 03:45:50 +00003430 GEPOps.pop_back(); // Consume a GEP operand
3431 GEPTypes.pop_back();
3432 } else {
3433 // It's an array or pointer access: [ArraySize x ElementType].
3434 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3435 Value *idx = GEPOps.back();
3436
3437 // idx is the index into the array. Unlike with structure
3438 // indices, we may not know its actual value at code-generation
3439 // time.
Chris Lattner985fe3d2004-02-25 03:45:50 +00003440
3441 // If idx is a constant, fold it into the offset.
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003442 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
Chris Lattner985fe3d2004-02-25 03:45:50 +00003443 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003444 Disp += TypeSize*CSI->getValue();
Chris Lattner28977af2004-04-05 01:30:19 +00003445 } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
3446 Disp += TypeSize*CUI->getValue();
Chris Lattner985fe3d2004-02-25 03:45:50 +00003447 } else {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003448 // If the index reg is already taken, we can't handle this index.
3449 if (IndexReg) return;
3450
3451 // If this is a size that we can handle, then add the index as
3452 switch (TypeSize) {
3453 case 1: case 2: case 4: case 8:
3454 // These are all acceptable scales on X86.
3455 Scale = TypeSize;
3456 break;
3457 default:
3458 // Otherwise, we can't handle this scale
3459 return;
3460 }
3461
3462 if (CastInst *CI = dyn_cast<CastInst>(idx))
3463 if (CI->getOperand(0)->getType() == Type::IntTy ||
3464 CI->getOperand(0)->getType() == Type::UIntTy)
3465 idx = CI->getOperand(0);
3466
3467 IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003468 }
3469
3470 GEPOps.pop_back(); // Consume a GEP operand
3471 GEPTypes.pop_back();
3472 }
3473 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003474
3475 // GEPTypes is empty, which means we have a single operand left. See if we
3476 // can set it as the base register.
3477 //
3478 // FIXME: When addressing modes are more powerful/correct, we could load
3479 // global addresses directly as 32-bit immediates.
3480 assert(BaseReg == 0);
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003481 BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
Chris Lattnerb6bac512004-02-25 06:13:04 +00003482 GEPOps.pop_back(); // Consume the last GEP operand
Chris Lattner985fe3d2004-02-25 03:45:50 +00003483}
3484
3485
Chris Lattnerb6bac512004-02-25 06:13:04 +00003486/// isGEPFoldable - Return true if the specified GEP can be completely
3487/// folded into the addressing mode of a load/store or lea instruction.
3488bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
3489 Value *Src, User::op_iterator IdxBegin,
3490 User::op_iterator IdxEnd, unsigned &BaseReg,
3491 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
Chris Lattner7ca04092004-02-22 17:35:42 +00003492 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
3493 Src = CPR->getValue();
3494
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003495 std::vector<Value*> GEPOps;
3496 GEPOps.resize(IdxEnd-IdxBegin+1);
3497 GEPOps[0] = Src;
3498 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3499
3500 std::vector<const Type*> GEPTypes;
3501 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3502 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3503
Chris Lattnerb6bac512004-02-25 06:13:04 +00003504 MachineBasicBlock::iterator IP;
3505 if (MBB) IP = MBB->end();
3506 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
3507
3508 // We can fold it away iff the getGEPIndex call eliminated all operands.
3509 return GEPOps.empty();
3510}
3511
3512void ISel::emitGEPOperation(MachineBasicBlock *MBB,
3513 MachineBasicBlock::iterator IP,
3514 Value *Src, User::op_iterator IdxBegin,
3515 User::op_iterator IdxEnd, unsigned TargetReg) {
3516 const TargetData &TD = TM.getTargetData();
3517 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
3518 Src = CPR->getValue();
3519
3520 std::vector<Value*> GEPOps;
3521 GEPOps.resize(IdxEnd-IdxBegin+1);
3522 GEPOps[0] = Src;
3523 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3524
3525 std::vector<const Type*> GEPTypes;
3526 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3527 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
Chris Lattner985fe3d2004-02-25 03:45:50 +00003528
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003529 // Keep emitting instructions until we consume the entire GEP instruction.
3530 while (!GEPOps.empty()) {
3531 unsigned OldSize = GEPOps.size();
Chris Lattnerb6bac512004-02-25 06:13:04 +00003532 unsigned BaseReg, Scale, IndexReg, Disp;
3533 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003534
Chris Lattner985fe3d2004-02-25 03:45:50 +00003535 if (GEPOps.size() != OldSize) {
3536 // getGEPIndex consumed some of the input. Build an LEA instruction here.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003537 unsigned NextTarget = 0;
3538 if (!GEPOps.empty()) {
3539 assert(BaseReg == 0 &&
3540 "getGEPIndex should have left the base register open for chaining!");
3541 NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
Chris Lattner985fe3d2004-02-25 03:45:50 +00003542 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003543
3544 if (IndexReg == 0 && Disp == 0)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003545 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003546 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003547 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003548 BaseReg, Scale, IndexReg, Disp);
3549 --IP;
3550 TargetReg = NextTarget;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003551 } else if (GEPTypes.empty()) {
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003552 // The getGEPIndex operation didn't want to build an LEA. Check to see if
3553 // all operands are consumed but the base pointer. If so, just load it
3554 // into the register.
Chris Lattner7ca04092004-02-22 17:35:42 +00003555 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003556 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
Chris Lattner7ca04092004-02-22 17:35:42 +00003557 } else {
3558 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003559 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattner7ca04092004-02-22 17:35:42 +00003560 }
3561 break; // we are now done
Chris Lattnerb6bac512004-02-25 06:13:04 +00003562
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003563 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +00003564 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003565 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3566 Value *idx = GEPOps.back();
3567 GEPOps.pop_back(); // Consume a GEP operand
3568 GEPTypes.pop_back();
Chris Lattner8a307e82002-12-16 19:32:50 +00003569
Chris Lattner28977af2004-04-05 01:30:19 +00003570 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
Chris Lattnerf5854472003-06-21 16:01:24 +00003571 // operand on X86. Handle this case directly now...
3572 if (CastInst *CI = dyn_cast<CastInst>(idx))
3573 if (CI->getOperand(0)->getType() == Type::IntTy ||
3574 CI->getOperand(0)->getType() == Type::UIntTy)
3575 idx = CI->getOperand(0);
3576
Chris Lattner3e130a22003-01-13 00:32:26 +00003577 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
Chris Lattner8a307e82002-12-16 19:32:50 +00003578 // must find the size of the pointed-to type (Not coincidentally, the next
3579 // type is the type of the elements in the array).
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003580 const Type *ElTy = SqTy->getElementType();
3581 unsigned elementSize = TD.getTypeSize(ElTy);
Chris Lattner8a307e82002-12-16 19:32:50 +00003582
3583 // If idxReg is a constant, we don't need to perform the multiply!
Chris Lattner28977af2004-04-05 01:30:19 +00003584 if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003585 if (!CSI->isNullValue()) {
Chris Lattner28977af2004-04-05 01:30:19 +00003586 unsigned Offset = elementSize*CSI->getRawValue();
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003587 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003588 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00003589 .addReg(Reg).addImm(Offset);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003590 --IP; // Insert the next instruction before this one.
3591 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003592 }
3593 } else if (elementSize == 1) {
3594 // If the element size is 1, we don't have to multiply, just add
3595 unsigned idxReg = getReg(idx, MBB, IP);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003596 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003597 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003598 --IP; // Insert the next instruction before this one.
3599 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003600 } else {
3601 unsigned idxReg = getReg(idx, MBB, IP);
3602 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00003603
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003604 // Make sure we can back the iterator up to point to the first
3605 // instruction emitted.
3606 MachineBasicBlock::iterator BeforeIt = IP;
3607 if (IP == MBB->begin())
3608 BeforeIt = MBB->end();
3609 else
3610 --BeforeIt;
Chris Lattnerb2acc512003-10-19 21:09:10 +00003611 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
3612
Chris Lattner8a307e82002-12-16 19:32:50 +00003613 // Emit an ADD to add OffsetReg to the basePtr.
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003614 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003615 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00003616 .addReg(Reg).addReg(OffsetReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003617
3618 // Step to the first instruction of the multiply.
3619 if (BeforeIt == MBB->end())
3620 IP = MBB->begin();
3621 else
3622 IP = ++BeforeIt;
3623
3624 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003625 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003626 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003627 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003628}
3629
3630
Chris Lattner065faeb2002-12-28 20:24:02 +00003631/// visitAllocaInst - If this is a fixed size alloca, allocate space from the
3632/// frame manager, otherwise do it the hard way.
3633///
3634void ISel::visitAllocaInst(AllocaInst &I) {
Chris Lattnercb2fd552004-05-13 07:40:27 +00003635 if (dyn_castFixedAlloca(&I)) return;
3636
Brian Gaekee48ec012002-12-13 06:46:31 +00003637 // Find the data size of the alloca inst's getAllocatedType.
Chris Lattner065faeb2002-12-28 20:24:02 +00003638 const Type *Ty = I.getAllocatedType();
3639 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
3640
Chris Lattner065faeb2002-12-28 20:24:02 +00003641 // Create a register to hold the temporary result of multiplying the type size
3642 // constant by the variable amount.
3643 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
3644 unsigned SrcReg1 = getReg(I.getArraySize());
Chris Lattner065faeb2002-12-28 20:24:02 +00003645
3646 // TotalSizeReg = mul <numelements>, <TypeSize>
3647 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00003648 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
Chris Lattner065faeb2002-12-28 20:24:02 +00003649
3650 // AddedSize = add <TotalSizeReg>, 15
3651 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003652 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
Chris Lattner065faeb2002-12-28 20:24:02 +00003653
3654 // AlignedSize = and <AddedSize>, ~15
3655 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003656 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
Chris Lattner065faeb2002-12-28 20:24:02 +00003657
Brian Gaekee48ec012002-12-13 06:46:31 +00003658 // Subtract size from stack pointer, thereby allocating some space.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003659 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
Chris Lattner065faeb2002-12-28 20:24:02 +00003660
Brian Gaekee48ec012002-12-13 06:46:31 +00003661 // Put a pointer to the space into the result register, by copying
3662 // the stack pointer.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003663 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
Chris Lattner065faeb2002-12-28 20:24:02 +00003664
Misha Brukman48196b32003-05-03 02:18:17 +00003665 // Inform the Frame Information that we have just allocated a variable-sized
Chris Lattner065faeb2002-12-28 20:24:02 +00003666 // object.
3667 F->getFrameInfo()->CreateVariableSizedObject();
Brian Gaeke20244b72002-12-12 15:33:40 +00003668}
Chris Lattner3e130a22003-01-13 00:32:26 +00003669
3670/// visitMallocInst - Malloc instructions are code generated into direct calls
3671/// to the library malloc.
3672///
3673void ISel::visitMallocInst(MallocInst &I) {
3674 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
3675 unsigned Arg;
3676
3677 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
3678 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
3679 } else {
3680 Arg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00003681 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattner3e130a22003-01-13 00:32:26 +00003682 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00003683 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
Chris Lattner3e130a22003-01-13 00:32:26 +00003684 }
3685
3686 std::vector<ValueRecord> Args;
3687 Args.push_back(ValueRecord(Arg, Type::UIntTy));
3688 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003689 1).addExternalSymbol("malloc", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00003690 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
3691}
3692
3693
3694/// visitFreeInst - Free instructions are code gen'd to call the free libc
3695/// function.
3696///
3697void ISel::visitFreeInst(FreeInst &I) {
3698 std::vector<ValueRecord> Args;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00003699 Args.push_back(ValueRecord(I.getOperand(0)));
Chris Lattner3e130a22003-01-13 00:32:26 +00003700 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003701 1).addExternalSymbol("free", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00003702 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
3703}
3704
Chris Lattnerd281de22003-07-26 23:49:58 +00003705/// createX86SimpleInstructionSelector - This pass converts an LLVM function
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00003706/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00003707/// generated code sucks but the implementation is nice and simple.
3708///
Chris Lattnerf70e0c22003-12-28 21:23:38 +00003709FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
3710 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00003711}