blob: 98587829fd091bf0f0fc52e943f21f4909b9ff0a [file] [log] [blame]
Chris Lattner72614082002-10-25 22:55:53 +00001//===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner72614082002-10-25 22:55:53 +00009//
Chris Lattner3e130a22003-01-13 00:32:26 +000010// This file defines a simple peephole instruction selector for the x86 target
Chris Lattner72614082002-10-25 22:55:53 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "X86.h"
Chris Lattner6fc3c522002-11-17 21:11:55 +000015#include "X86InstrBuilder.h"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000016#include "X86InstrInfo.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
Chris Lattner72614082002-10-25 22:55:53 +000019#include "llvm/Function.h"
Chris Lattner67580ed2003-05-13 20:21:19 +000020#include "llvm/Instructions.h"
Chris Lattner44827152003-12-28 09:47:19 +000021#include "llvm/IntrinsicLowering.h"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000022#include "llvm/Pass.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
Chris Lattner341a9372002-10-29 17:43:55 +000025#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner94af4142002-12-25 05:13:53 +000026#include "llvm/CodeGen/SSARegMap.h"
Misha Brukmand2cc0172002-11-20 00:58:23 +000027#include "llvm/Target/MRegisterInfo.h"
Misha Brukmanc8893fc2003-10-23 16:22:08 +000028#include "llvm/Target/TargetMachine.h"
Chris Lattner3f1e8e72004-02-22 07:04:00 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner67580ed2003-05-13 20:21:19 +000030#include "llvm/Support/InstVisitor.h"
Chris Lattnercf93cdd2004-01-30 22:13:44 +000031#include "llvm/Support/CFG.h"
Chris Lattner986618e2004-02-22 19:47:26 +000032#include "Support/Statistic.h"
Chris Lattner44827152003-12-28 09:47:19 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Chris Lattner986618e2004-02-22 19:47:26 +000035namespace {
36 Statistic<>
37 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
38}
Chris Lattnercf93cdd2004-01-30 22:13:44 +000039
Chris Lattner72614082002-10-25 22:55:53 +000040namespace {
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000041 struct ISel : public FunctionPass, InstVisitor<ISel> {
42 TargetMachine &TM;
Chris Lattnereca195e2003-05-08 19:44:13 +000043 MachineFunction *F; // The function we are compiling into
44 MachineBasicBlock *BB; // The current MBB we are compiling
45 int VarArgsFrameIndex; // FrameIndex for start of varargs area
Chris Lattner0e5b79c2004-02-15 01:04:03 +000046 int ReturnAddressIndex; // FrameIndex for the return address
Chris Lattner72614082002-10-25 22:55:53 +000047
Chris Lattner72614082002-10-25 22:55:53 +000048 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
49
Chris Lattner333b2fa2002-12-13 10:09:43 +000050 // MBBMap - Mapping between LLVM BB -> Machine BB
51 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
52
Chris Lattnerf70e0c22003-12-28 21:23:38 +000053 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
Chris Lattner72614082002-10-25 22:55:53 +000054
55 /// runOnFunction - Top level implementation of instruction selection for
56 /// the entire function.
57 ///
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000058 bool runOnFunction(Function &Fn) {
Chris Lattner44827152003-12-28 09:47:19 +000059 // First pass over the function, lower any unknown intrinsic functions
60 // with the IntrinsicLowering class.
61 LowerUnknownIntrinsicFunctionCalls(Fn);
62
Chris Lattner36b36032002-10-29 23:40:58 +000063 F = &MachineFunction::construct(&Fn, TM);
Chris Lattner333b2fa2002-12-13 10:09:43 +000064
Chris Lattner065faeb2002-12-28 20:24:02 +000065 // Create all of the machine basic blocks for the function...
Chris Lattner333b2fa2002-12-13 10:09:43 +000066 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
67 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
68
Chris Lattner14aa7fe2002-12-16 22:54:46 +000069 BB = &F->front();
Chris Lattnerdbd73722003-05-06 21:32:22 +000070
Chris Lattner0e5b79c2004-02-15 01:04:03 +000071 // Set up a frame object for the return address. This is used by the
72 // llvm.returnaddress & llvm.frameaddress intrinisics.
73 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
74
Chris Lattnerdbd73722003-05-06 21:32:22 +000075 // Copy incoming arguments off of the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +000076 LoadArgumentsToVirtualRegs(Fn);
Chris Lattner14aa7fe2002-12-16 22:54:46 +000077
Chris Lattner333b2fa2002-12-13 10:09:43 +000078 // Instruction select everything except PHI nodes
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000079 visit(Fn);
Chris Lattner333b2fa2002-12-13 10:09:43 +000080
81 // Select the PHI nodes
82 SelectPHINodes();
83
Chris Lattner986618e2004-02-22 19:47:26 +000084 // Insert the FP_REG_KILL instructions into blocks that need them.
85 InsertFPRegKills();
86
Chris Lattner72614082002-10-25 22:55:53 +000087 RegMap.clear();
Chris Lattner333b2fa2002-12-13 10:09:43 +000088 MBBMap.clear();
Chris Lattnerb4f68ed2002-10-29 22:37:54 +000089 F = 0;
Chris Lattner2a865b02003-07-26 23:05:37 +000090 // We always build a machine code representation for the function
91 return true;
Chris Lattner72614082002-10-25 22:55:53 +000092 }
93
Chris Lattnerf0eb7be2002-12-15 21:13:40 +000094 virtual const char *getPassName() const {
95 return "X86 Simple Instruction Selection";
96 }
97
Chris Lattner72614082002-10-25 22:55:53 +000098 /// visitBasicBlock - This method is called when we are visiting a new basic
Chris Lattner33f53b52002-10-29 20:48:56 +000099 /// block. This simply creates a new MachineBasicBlock to emit code into
100 /// and adds it to the current MachineFunction. Subsequent visit* for
101 /// instructions will be invoked for all instructions in the basic block.
Chris Lattner72614082002-10-25 22:55:53 +0000102 ///
103 void visitBasicBlock(BasicBlock &LLVM_BB) {
Chris Lattner333b2fa2002-12-13 10:09:43 +0000104 BB = MBBMap[&LLVM_BB];
Chris Lattner72614082002-10-25 22:55:53 +0000105 }
106
Chris Lattner44827152003-12-28 09:47:19 +0000107 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
108 /// function, lowering any calls to unknown intrinsic functions into the
109 /// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +0000110 ///
Chris Lattner44827152003-12-28 09:47:19 +0000111 void LowerUnknownIntrinsicFunctionCalls(Function &F);
112
Chris Lattner065faeb2002-12-28 20:24:02 +0000113 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
114 /// from the stack into virtual registers.
115 ///
116 void LoadArgumentsToVirtualRegs(Function &F);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000117
118 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
119 /// because we have to generate our sources into the source basic blocks,
120 /// not the current one.
121 ///
122 void SelectPHINodes();
123
Chris Lattner986618e2004-02-22 19:47:26 +0000124 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
125 /// that need them. This only occurs due to the floating point stackifier
126 /// not being aggressive enough to handle arbitrary global stackification.
127 ///
128 void InsertFPRegKills();
129
Chris Lattner72614082002-10-25 22:55:53 +0000130 // Visitation methods for various instructions. These methods simply emit
131 // fixed X86 code for each instruction.
132 //
Brian Gaekefa8d5712002-11-22 11:07:01 +0000133
134 // Control flow operators
Chris Lattner72614082002-10-25 22:55:53 +0000135 void visitReturnInst(ReturnInst &RI);
Chris Lattner2df035b2002-11-02 19:27:56 +0000136 void visitBranchInst(BranchInst &BI);
Chris Lattner3e130a22003-01-13 00:32:26 +0000137
138 struct ValueRecord {
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000139 Value *Val;
Chris Lattner3e130a22003-01-13 00:32:26 +0000140 unsigned Reg;
141 const Type *Ty;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +0000142 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
143 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
Chris Lattner3e130a22003-01-13 00:32:26 +0000144 };
145 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000146 const std::vector<ValueRecord> &Args);
Brian Gaekefa8d5712002-11-22 11:07:01 +0000147 void visitCallInst(CallInst &I);
Brian Gaeked0fde302003-11-11 22:41:34 +0000148 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
Chris Lattnere2954c82002-11-02 20:04:26 +0000149
150 // Arithmetic operators
Chris Lattnerf01729e2002-11-02 20:54:46 +0000151 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
Chris Lattner68aad932002-11-02 20:13:22 +0000152 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
153 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000154 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +0000155 unsigned DestReg, const Type *DestTy,
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000156 unsigned Op0Reg, unsigned Op1Reg);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000157 void doMultiplyConst(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000158 MachineBasicBlock::iterator MBBI,
Chris Lattnerb2acc512003-10-19 21:09:10 +0000159 unsigned DestReg, const Type *DestTy,
160 unsigned Op0Reg, unsigned Op1Val);
Chris Lattnerca9671d2002-11-02 20:28:58 +0000161 void visitMul(BinaryOperator &B);
Chris Lattnere2954c82002-11-02 20:04:26 +0000162
Chris Lattnerf01729e2002-11-02 20:54:46 +0000163 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
164 void visitRem(BinaryOperator &B) { visitDivRem(B); }
165 void visitDivRem(BinaryOperator &B);
166
Chris Lattnere2954c82002-11-02 20:04:26 +0000167 // Bitwise operators
Chris Lattner68aad932002-11-02 20:13:22 +0000168 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
169 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
170 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
Chris Lattnere2954c82002-11-02 20:04:26 +0000171
Chris Lattner6d40c192003-01-16 16:43:00 +0000172 // Comparison operators...
173 void visitSetCondInst(SetCondInst &I);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000174 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
175 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000176 MachineBasicBlock::iterator MBBI);
Chris Lattner12d96a02004-03-30 21:22:00 +0000177 void visitSelectInst(SelectInst &SI);
178
Chris Lattnerb2acc512003-10-19 21:09:10 +0000179
Chris Lattner6fc3c522002-11-17 21:11:55 +0000180 // Memory Instructions
181 void visitLoadInst(LoadInst &I);
182 void visitStoreInst(StoreInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000183 void visitGetElementPtrInst(GetElementPtrInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000184 void visitAllocaInst(AllocaInst &I);
Chris Lattner3e130a22003-01-13 00:32:26 +0000185 void visitMallocInst(MallocInst &I);
186 void visitFreeInst(FreeInst &I);
Brian Gaeke20244b72002-12-12 15:33:40 +0000187
Chris Lattnere2954c82002-11-02 20:04:26 +0000188 // Other operators
Brian Gaekea1719c92002-10-31 23:03:59 +0000189 void visitShiftInst(ShiftInst &I);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000190 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
Brian Gaekefa8d5712002-11-22 11:07:01 +0000191 void visitCastInst(CastInst &I);
Chris Lattner73815062003-10-18 05:56:40 +0000192 void visitVANextInst(VANextInst &I);
193 void visitVAArgInst(VAArgInst &I);
Chris Lattner72614082002-10-25 22:55:53 +0000194
195 void visitInstruction(Instruction &I) {
196 std::cerr << "Cannot instruction select: " << I;
197 abort();
198 }
199
Brian Gaeke95780cc2002-12-13 07:56:18 +0000200 /// promote32 - Make a value 32-bits wide, and put it somewhere.
Chris Lattner3e130a22003-01-13 00:32:26 +0000201 ///
202 void promote32(unsigned targetReg, const ValueRecord &VR);
203
Chris Lattner721d2d42004-03-08 01:18:36 +0000204 /// getAddressingMode - Get the addressing mode to use to address the
205 /// specified value. The returned value should be used with addFullAddress.
206 void getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
207 unsigned &IndexReg, unsigned &Disp);
208
209
210 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
211 /// expressions.
Chris Lattnerb6bac512004-02-25 06:13:04 +0000212 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
213 std::vector<Value*> &GEPOps,
214 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
215 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
216
217 /// isGEPFoldable - Return true if the specified GEP can be completely
218 /// folded into the addressing mode of a load/store or lea instruction.
219 bool isGEPFoldable(MachineBasicBlock *MBB,
220 Value *Src, User::op_iterator IdxBegin,
221 User::op_iterator IdxEnd, unsigned &BaseReg,
222 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
223
Chris Lattner3e130a22003-01-13 00:32:26 +0000224 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
225 /// constant expression GEP support.
226 ///
Chris Lattner827832c2004-02-22 17:05:38 +0000227 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
Chris Lattner333b2fa2002-12-13 10:09:43 +0000228 Value *Src, User::op_iterator IdxBegin,
Chris Lattnerc0812d82002-12-13 06:56:29 +0000229 User::op_iterator IdxEnd, unsigned TargetReg);
230
Chris Lattner548f61d2003-04-23 17:22:12 +0000231 /// emitCastOperation - Common code shared between visitCastInst and
232 /// constant expression cast support.
Misha Brukman538607f2004-03-01 23:53:11 +0000233 ///
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000234 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +0000235 Value *Src, const Type *DestTy, unsigned TargetReg);
236
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000237 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
238 /// and constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000239 ///
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000240 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000241 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000242 Value *Op0, Value *Op1,
243 unsigned OperatorClass, unsigned TargetReg);
244
Chris Lattnercadff442003-10-23 17:21:43 +0000245 void emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000246 MachineBasicBlock::iterator IP,
Chris Lattnercadff442003-10-23 17:21:43 +0000247 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
248 const Type *Ty, unsigned TargetReg);
249
Chris Lattner58c41fe2003-08-24 19:19:47 +0000250 /// emitSetCCOperation - Common code shared between visitSetCondInst and
251 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000252 ///
Chris Lattner58c41fe2003-08-24 19:19:47 +0000253 void emitSetCCOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000254 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +0000255 Value *Op0, Value *Op1, unsigned Opcode,
256 unsigned TargetReg);
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000257
258 /// emitShiftOperation - Common code shared between visitShiftInst and
259 /// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000260 ///
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000261 void emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000262 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000263 Value *Op, Value *ShiftAmount, bool isLeftShift,
264 const Type *ResultTy, unsigned DestReg);
265
Chris Lattner12d96a02004-03-30 21:22:00 +0000266 /// emitSelectOperation - Common code shared between visitSelectInst and the
267 /// constant expression support.
268 void emitSelectOperation(MachineBasicBlock *MBB,
269 MachineBasicBlock::iterator IP,
270 Value *Cond, Value *TrueVal, Value *FalseVal,
271 unsigned DestReg);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000272
Chris Lattnerc5291f52002-10-27 21:16:59 +0000273 /// copyConstantToRegister - Output the instructions required to put the
274 /// specified constant into the specified register.
275 ///
Chris Lattner8a307e82002-12-16 19:32:50 +0000276 void copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000277 MachineBasicBlock::iterator MBBI,
Chris Lattner8a307e82002-12-16 19:32:50 +0000278 Constant *C, unsigned Reg);
Chris Lattnerc5291f52002-10-27 21:16:59 +0000279
Chris Lattner3e130a22003-01-13 00:32:26 +0000280 /// makeAnotherReg - This method returns the next register number we haven't
281 /// yet used.
282 ///
283 /// Long values are handled somewhat specially. They are always allocated
284 /// as pairs of 32 bit integer values. The register number returned is the
285 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
286 /// of the long value.
287 ///
Chris Lattnerc0812d82002-12-13 06:56:29 +0000288 unsigned makeAnotherReg(const Type *Ty) {
Chris Lattner7db1fa92003-07-30 05:33:48 +0000289 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
290 "Current target doesn't have X86 reg info??");
291 const X86RegisterInfo *MRI =
292 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
Chris Lattner3e130a22003-01-13 00:32:26 +0000293 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000294 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
295 // Create the lower part
296 F->getSSARegMap()->createVirtualRegister(RC);
297 // Create the upper part.
298 return F->getSSARegMap()->createVirtualRegister(RC)-1;
Chris Lattner3e130a22003-01-13 00:32:26 +0000299 }
300
Chris Lattnerc0812d82002-12-13 06:56:29 +0000301 // Add the mapping of regnumber => reg class to MachineFunction
Chris Lattner7db1fa92003-07-30 05:33:48 +0000302 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
Chris Lattner3e130a22003-01-13 00:32:26 +0000303 return F->getSSARegMap()->createVirtualRegister(RC);
Brian Gaeke20244b72002-12-12 15:33:40 +0000304 }
305
Chris Lattner72614082002-10-25 22:55:53 +0000306 /// getReg - This method turns an LLVM value into a register number. This
307 /// is guaranteed to produce the same register number for a particular value
308 /// every time it is queried.
309 ///
310 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000311 unsigned getReg(Value *V) {
312 // Just append to the end of the current bb.
313 MachineBasicBlock::iterator It = BB->end();
314 return getReg(V, BB, It);
315 }
Brian Gaeke71794c02002-12-13 11:22:48 +0000316 unsigned getReg(Value *V, MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000317 MachineBasicBlock::iterator IPt) {
Chris Lattner72614082002-10-25 22:55:53 +0000318 unsigned &Reg = RegMap[V];
Misha Brukmand2cc0172002-11-20 00:58:23 +0000319 if (Reg == 0) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000320 Reg = makeAnotherReg(V->getType());
Misha Brukmand2cc0172002-11-20 00:58:23 +0000321 RegMap[V] = Reg;
Misha Brukmand2cc0172002-11-20 00:58:23 +0000322 }
Chris Lattner72614082002-10-25 22:55:53 +0000323
Chris Lattner6f8fd252002-10-27 21:23:43 +0000324 // If this operand is a constant, emit the code to copy the constant into
325 // the register here...
326 //
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000327 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner8a307e82002-12-16 19:32:50 +0000328 copyConstantToRegister(MBB, IPt, C, Reg);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000329 RegMap.erase(V); // Assign a new name to this constant if ref'd again
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000330 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
331 // Move the address of the global into the register
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000332 BuildMI(*MBB, IPt, X86::MOV32ri, 1, Reg).addGlobalAddress(GV);
Chris Lattner14aa7fe2002-12-16 22:54:46 +0000333 RegMap.erase(V); // Assign a new name to this address if ref'd again
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000334 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000335
Chris Lattner72614082002-10-25 22:55:53 +0000336 return Reg;
337 }
Chris Lattner72614082002-10-25 22:55:53 +0000338 };
339}
340
Chris Lattner43189d12002-11-17 20:07:45 +0000341/// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
342/// Representation.
343///
344enum TypeClass {
Chris Lattner94af4142002-12-25 05:13:53 +0000345 cByte, cShort, cInt, cFP, cLong
Chris Lattner43189d12002-11-17 20:07:45 +0000346};
347
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000348/// getClass - Turn a primitive type into a "class" number which is based on the
349/// size of the type, and whether or not it is floating point.
350///
Chris Lattner43189d12002-11-17 20:07:45 +0000351static inline TypeClass getClass(const Type *Ty) {
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000352 switch (Ty->getPrimitiveID()) {
353 case Type::SByteTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000354 case Type::UByteTyID: return cByte; // Byte operands are class #0
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000355 case Type::ShortTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000356 case Type::UShortTyID: return cShort; // Short operands are class #1
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000357 case Type::IntTyID:
358 case Type::UIntTyID:
Chris Lattner43189d12002-11-17 20:07:45 +0000359 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000360
Chris Lattner94af4142002-12-25 05:13:53 +0000361 case Type::FloatTyID:
362 case Type::DoubleTyID: return cFP; // Floating Point is #3
Chris Lattner3e130a22003-01-13 00:32:26 +0000363
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000364 case Type::LongTyID:
Chris Lattner3e130a22003-01-13 00:32:26 +0000365 case Type::ULongTyID: return cLong; // Longs are class #4
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000366 default:
367 assert(0 && "Invalid type to getClass!");
Chris Lattner43189d12002-11-17 20:07:45 +0000368 return cByte; // not reached
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000369 }
370}
Chris Lattnerc5291f52002-10-27 21:16:59 +0000371
Chris Lattner6b993cc2002-12-15 08:02:15 +0000372// getClassB - Just like getClass, but treat boolean values as bytes.
373static inline TypeClass getClassB(const Type *Ty) {
374 if (Ty == Type::BoolTy) return cByte;
375 return getClass(Ty);
376}
377
Chris Lattner06925362002-11-17 21:56:38 +0000378
Chris Lattnerc5291f52002-10-27 21:16:59 +0000379/// copyConstantToRegister - Output the instructions required to put the
380/// specified constant into the specified register.
381///
Chris Lattner8a307e82002-12-16 19:32:50 +0000382void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000383 MachineBasicBlock::iterator IP,
Chris Lattner8a307e82002-12-16 19:32:50 +0000384 Constant *C, unsigned R) {
Chris Lattnerc0812d82002-12-13 06:56:29 +0000385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000386 unsigned Class = 0;
387 switch (CE->getOpcode()) {
388 case Instruction::GetElementPtr:
Brian Gaeke68b1edc2002-12-16 04:23:29 +0000389 emitGEPOperation(MBB, IP, CE->getOperand(0),
Chris Lattner333b2fa2002-12-13 10:09:43 +0000390 CE->op_begin()+1, CE->op_end(), R);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000391 return;
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000392 case Instruction::Cast:
Chris Lattner548f61d2003-04-23 17:22:12 +0000393 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
Chris Lattner4b12cde2003-04-21 21:33:44 +0000394 return;
Chris Lattnerc0812d82002-12-13 06:56:29 +0000395
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000396 case Instruction::Xor: ++Class; // FALL THROUGH
397 case Instruction::Or: ++Class; // FALL THROUGH
398 case Instruction::And: ++Class; // FALL THROUGH
399 case Instruction::Sub: ++Class; // FALL THROUGH
400 case Instruction::Add:
401 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
402 Class, R);
403 return;
404
Chris Lattnercadff442003-10-23 17:21:43 +0000405 case Instruction::Mul: {
406 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
407 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
408 doMultiply(MBB, IP, R, CE->getType(), Op0Reg, Op1Reg);
409 return;
410 }
411 case Instruction::Div:
412 case Instruction::Rem: {
413 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
414 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
415 emitDivRemOperation(MBB, IP, Op0Reg, Op1Reg,
416 CE->getOpcode() == Instruction::Div,
417 CE->getType(), R);
418 return;
419 }
420
Chris Lattner58c41fe2003-08-24 19:19:47 +0000421 case Instruction::SetNE:
422 case Instruction::SetEQ:
423 case Instruction::SetLT:
424 case Instruction::SetGT:
425 case Instruction::SetLE:
426 case Instruction::SetGE:
427 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
428 CE->getOpcode(), R);
429 return;
430
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000431 case Instruction::Shl:
432 case Instruction::Shr:
433 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
Brian Gaekedfcc9cf2003-11-22 06:49:41 +0000434 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
435 return;
Brian Gaeke2dd3e1b2003-11-22 05:18:35 +0000436
Chris Lattner12d96a02004-03-30 21:22:00 +0000437 case Instruction::Select:
438 emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
439 CE->getOperand(2), R);
440 return;
441
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000442 default:
443 std::cerr << "Offending expr: " << C << "\n";
Chris Lattnerb2acc512003-10-19 21:09:10 +0000444 assert(0 && "Constant expression not yet handled!\n");
Chris Lattnerb515f6d2003-05-08 20:49:25 +0000445 }
Brian Gaeke20244b72002-12-12 15:33:40 +0000446 }
Chris Lattnerc5291f52002-10-27 21:16:59 +0000447
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000448 if (C->getType()->isIntegral()) {
Chris Lattner6b993cc2002-12-15 08:02:15 +0000449 unsigned Class = getClassB(C->getType());
Chris Lattner3e130a22003-01-13 00:32:26 +0000450
451 if (Class == cLong) {
452 // Copy the value into the register pair.
Chris Lattnerc07736a2003-07-23 15:22:26 +0000453 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000454 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
455 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
Chris Lattner3e130a22003-01-13 00:32:26 +0000456 return;
457 }
458
Chris Lattner94af4142002-12-25 05:13:53 +0000459 assert(Class <= cInt && "Type not handled yet!");
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000460
461 static const unsigned IntegralOpcodeTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000462 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000463 };
464
Chris Lattner6b993cc2002-12-15 08:02:15 +0000465 if (C->getType() == Type::BoolTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000466 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000467 } else {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000468 ConstantInt *CI = cast<ConstantInt>(C);
Chris Lattneree352852004-02-29 07:22:16 +0000469 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000470 }
Chris Lattner94af4142002-12-25 05:13:53 +0000471 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattneraf703622004-02-02 18:56:30 +0000472 if (CFP->isExactlyValue(+0.0))
Chris Lattneree352852004-02-29 07:22:16 +0000473 BuildMI(*MBB, IP, X86::FLD0, 0, R);
Chris Lattneraf703622004-02-02 18:56:30 +0000474 else if (CFP->isExactlyValue(+1.0))
Chris Lattneree352852004-02-29 07:22:16 +0000475 BuildMI(*MBB, IP, X86::FLD1, 0, R);
Chris Lattner94af4142002-12-25 05:13:53 +0000476 else {
Chris Lattner3e130a22003-01-13 00:32:26 +0000477 // Otherwise we need to spill the constant to memory...
478 MachineConstantPool *CP = F->getConstantPool();
479 unsigned CPI = CP->getConstantPoolIndex(CFP);
Chris Lattner6c09db22003-10-20 04:11:23 +0000480 const Type *Ty = CFP->getType();
481
482 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000483 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
Chris Lattneree352852004-02-29 07:22:16 +0000484 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
Chris Lattner94af4142002-12-25 05:13:53 +0000485 }
486
Chris Lattnerf08ad9f2002-12-13 10:50:40 +0000487 } else if (isa<ConstantPointerNull>(C)) {
Brian Gaeke20244b72002-12-12 15:33:40 +0000488 // Copy zero (null pointer) to the register.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000489 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
Chris Lattnerc0812d82002-12-13 06:56:29 +0000490 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000491 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(CPR->getValue());
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000492 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +0000493 std::cerr << "Offending constant: " << C << "\n";
Chris Lattnerb1761fc2002-11-02 01:15:18 +0000494 assert(0 && "Type not handled yet!");
Chris Lattnerc5291f52002-10-27 21:16:59 +0000495 }
496}
497
Chris Lattner065faeb2002-12-28 20:24:02 +0000498/// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
499/// the stack into virtual registers.
500///
501void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
502 // Emit instructions to load the arguments... On entry to a function on the
503 // X86, the stack frame looks like this:
504 //
505 // [ESP] -- return address
Chris Lattner3e130a22003-01-13 00:32:26 +0000506 // [ESP + 4] -- first argument (leftmost lexically)
507 // [ESP + 8] -- second argument, if first argument is four bytes in size
Chris Lattner065faeb2002-12-28 20:24:02 +0000508 // ...
509 //
Chris Lattnerf158da22003-01-16 02:20:12 +0000510 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
Chris Lattneraa09b752002-12-28 21:08:28 +0000511 MachineFrameInfo *MFI = F->getFrameInfo();
Chris Lattner065faeb2002-12-28 20:24:02 +0000512
513 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
514 unsigned Reg = getReg(*I);
515
Chris Lattner065faeb2002-12-28 20:24:02 +0000516 int FI; // Frame object index
Chris Lattner065faeb2002-12-28 20:24:02 +0000517 switch (getClassB(I->getType())) {
518 case cByte:
Chris Lattneraa09b752002-12-28 21:08:28 +0000519 FI = MFI->CreateFixedObject(1, ArgOffset);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000520 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000521 break;
522 case cShort:
Chris Lattneraa09b752002-12-28 21:08:28 +0000523 FI = MFI->CreateFixedObject(2, ArgOffset);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000524 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000525 break;
526 case cInt:
Chris Lattneraa09b752002-12-28 21:08:28 +0000527 FI = MFI->CreateFixedObject(4, ArgOffset);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000528 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
Chris Lattner065faeb2002-12-28 20:24:02 +0000529 break;
Chris Lattner3e130a22003-01-13 00:32:26 +0000530 case cLong:
531 FI = MFI->CreateFixedObject(8, ArgOffset);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000532 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
533 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +0000534 ArgOffset += 4; // longs require 4 additional bytes
535 break;
Chris Lattner065faeb2002-12-28 20:24:02 +0000536 case cFP:
537 unsigned Opcode;
538 if (I->getType() == Type::FloatTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000539 Opcode = X86::FLD32m;
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000540 FI = MFI->CreateFixedObject(4, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000541 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000542 Opcode = X86::FLD64m;
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000543 FI = MFI->CreateFixedObject(8, ArgOffset);
544 ArgOffset += 4; // doubles require 4 additional bytes
Chris Lattner065faeb2002-12-28 20:24:02 +0000545 }
546 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
547 break;
548 default:
549 assert(0 && "Unhandled argument type!");
550 }
Chris Lattner3e130a22003-01-13 00:32:26 +0000551 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
Chris Lattner065faeb2002-12-28 20:24:02 +0000552 }
Chris Lattnereca195e2003-05-08 19:44:13 +0000553
554 // If the function takes variable number of arguments, add a frame offset for
555 // the start of the first vararg value... this is used to expand
556 // llvm.va_start.
557 if (Fn.getFunctionType()->isVarArg())
558 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
Chris Lattner065faeb2002-12-28 20:24:02 +0000559}
560
561
Chris Lattner333b2fa2002-12-13 10:09:43 +0000562/// SelectPHINodes - Insert machine code to generate phis. This is tricky
563/// because we have to generate our sources into the source basic blocks, not
564/// the current one.
565///
566void ISel::SelectPHINodes() {
Chris Lattner3501fea2003-01-14 22:00:31 +0000567 const TargetInstrInfo &TII = TM.getInstrInfo();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000568 const Function &LF = *F->getFunction(); // The LLVM function...
569 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
570 const BasicBlock *BB = I;
Chris Lattner168aa902004-02-29 07:10:16 +0000571 MachineBasicBlock &MBB = *MBBMap[I];
Chris Lattner333b2fa2002-12-13 10:09:43 +0000572
573 // Loop over all of the PHI nodes in the LLVM basic block...
Chris Lattner168aa902004-02-29 07:10:16 +0000574 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
Chris Lattner333b2fa2002-12-13 10:09:43 +0000575 for (BasicBlock::const_iterator I = BB->begin();
Chris Lattnera81fc682003-10-19 00:26:11 +0000576 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
Chris Lattner3e130a22003-01-13 00:32:26 +0000577
Chris Lattner333b2fa2002-12-13 10:09:43 +0000578 // Create a new machine instr PHI node, and insert it.
Chris Lattner3e130a22003-01-13 00:32:26 +0000579 unsigned PHIReg = getReg(*PN);
Chris Lattner168aa902004-02-29 07:10:16 +0000580 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
581 X86::PHI, PN->getNumOperands(), PHIReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000582
583 MachineInstr *LongPhiMI = 0;
Chris Lattner168aa902004-02-29 07:10:16 +0000584 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
585 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
586 X86::PHI, PN->getNumOperands(), PHIReg+1);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000587
Chris Lattnera6e73f12003-05-12 14:22:21 +0000588 // PHIValues - Map of blocks to incoming virtual registers. We use this
589 // so that we only initialize one incoming value for a particular block,
590 // even if the block has multiple entries in the PHI node.
591 //
592 std::map<MachineBasicBlock*, unsigned> PHIValues;
593
Chris Lattner333b2fa2002-12-13 10:09:43 +0000594 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
595 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
Chris Lattnera6e73f12003-05-12 14:22:21 +0000596 unsigned ValReg;
597 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
598 PHIValues.lower_bound(PredMBB);
Chris Lattner333b2fa2002-12-13 10:09:43 +0000599
Chris Lattnera6e73f12003-05-12 14:22:21 +0000600 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
601 // We already inserted an initialization of the register for this
602 // predecessor. Recycle it.
603 ValReg = EntryIt->second;
604
605 } else {
Chris Lattnera81fc682003-10-19 00:26:11 +0000606 // Get the incoming value into a virtual register.
Chris Lattnera6e73f12003-05-12 14:22:21 +0000607 //
Chris Lattnera81fc682003-10-19 00:26:11 +0000608 Value *Val = PN->getIncomingValue(i);
609
610 // If this is a constant or GlobalValue, we may have to insert code
611 // into the basic block to compute it into a virtual register.
612 if (isa<Constant>(Val) || isa<GlobalValue>(Val)) {
Chris Lattner6f2ab042004-03-30 19:10:12 +0000613 if (isa<ConstantExpr>(Val)) {
614 // Because we don't want to clobber any values which might be in
615 // physical registers with the computation of this constant (which
616 // might be arbitrarily complex if it is a constant expression),
617 // just insert the computation at the top of the basic block.
618 MachineBasicBlock::iterator PI = PredMBB->begin();
619
620 // Skip over any PHI nodes though!
621 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
622 ++PI;
623
624 ValReg = getReg(Val, PredMBB, PI);
625 } else {
626 // Simple constants get emitted at the end of the basic block,
627 // before any terminator instructions. We "know" that the code to
628 // move a constant into a register will never clobber any flags.
629 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
630 }
Chris Lattnera81fc682003-10-19 00:26:11 +0000631 } else {
632 ValReg = getReg(Val);
633 }
Chris Lattnera6e73f12003-05-12 14:22:21 +0000634
635 // Remember that we inserted a value for this PHI for this predecessor
636 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
637 }
638
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000639 PhiMI->addRegOperand(ValReg);
Chris Lattner3e130a22003-01-13 00:32:26 +0000640 PhiMI->addMachineBasicBlockOperand(PredMBB);
Misha Brukmanc8893fc2003-10-23 16:22:08 +0000641 if (LongPhiMI) {
642 LongPhiMI->addRegOperand(ValReg+1);
643 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
644 }
Chris Lattner333b2fa2002-12-13 10:09:43 +0000645 }
Chris Lattner168aa902004-02-29 07:10:16 +0000646
647 // Now that we emitted all of the incoming values for the PHI node, make
648 // sure to reposition the InsertPoint after the PHI that we just added.
649 // This is needed because we might have inserted a constant into this
650 // block, right after the PHI's which is before the old insert point!
651 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
652 ++PHIInsertPoint;
Chris Lattner333b2fa2002-12-13 10:09:43 +0000653 }
654 }
655}
656
Chris Lattner986618e2004-02-22 19:47:26 +0000657/// RequiresFPRegKill - The floating point stackifier pass cannot insert
658/// compensation code on critical edges. As such, it requires that we kill all
659/// FP registers on the exit from any blocks that either ARE critical edges, or
660/// branch to a block that has incoming critical edges.
661///
662/// Note that this kill instruction will eventually be eliminated when
663/// restrictions in the stackifier are relaxed.
664///
665static bool RequiresFPRegKill(const BasicBlock *BB) {
666#if 0
667 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
668 const BasicBlock *Succ = *SI;
669 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
670 ++PI; // Block have at least one predecessory
671 if (PI != PE) { // If it has exactly one, this isn't crit edge
672 // If this block has more than one predecessor, check all of the
673 // predecessors to see if they have multiple successors. If so, then the
674 // block we are analyzing needs an FPRegKill.
675 for (PI = pred_begin(Succ); PI != PE; ++PI) {
676 const BasicBlock *Pred = *PI;
677 succ_const_iterator SI2 = succ_begin(Pred);
678 ++SI2; // There must be at least one successor of this block.
679 if (SI2 != succ_end(Pred))
680 return true; // Yes, we must insert the kill on this edge.
681 }
682 }
683 }
684 // If we got this far, there is no need to insert the kill instruction.
685 return false;
686#else
687 return true;
688#endif
689}
690
691// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
692// need them. This only occurs due to the floating point stackifier not being
693// aggressive enough to handle arbitrary global stackification.
694//
695// Currently we insert an FP_REG_KILL instruction into each block that uses or
696// defines a floating point virtual register.
697//
698// When the global register allocators (like linear scan) finally update live
699// variable analysis, we can keep floating point values in registers across
700// portions of the CFG that do not involve critical edges. This will be a big
701// win, but we are waiting on the global allocators before we can do this.
702//
703// With a bit of work, the floating point stackifier pass can be enhanced to
704// break critical edges as needed (to make a place to put compensation code),
705// but this will require some infrastructure improvements as well.
706//
707void ISel::InsertFPRegKills() {
708 SSARegMap &RegMap = *F->getSSARegMap();
Chris Lattner986618e2004-02-22 19:47:26 +0000709
710 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner986618e2004-02-22 19:47:26 +0000711 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000712 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
713 MachineOperand& MO = I->getOperand(i);
714 if (MO.isRegister() && MO.getReg()) {
715 unsigned Reg = MO.getReg();
Chris Lattner986618e2004-02-22 19:47:26 +0000716 if (MRegisterInfo::isVirtualRegister(Reg))
Chris Lattner65cf42d2004-02-23 07:29:45 +0000717 if (RegMap.getRegClass(Reg)->getSize() == 10)
718 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000719 }
Alkis Evlogimenos71e353e2004-02-26 22:00:20 +0000720 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000721 // If we haven't found an FP register use or def in this basic block, check
722 // to see if any of our successors has an FP PHI node, which will cause a
723 // copy to be inserted into this block.
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000724 for (succ_const_iterator SI = succ_begin(BB->getBasicBlock()),
725 E = succ_end(BB->getBasicBlock()); SI != E; ++SI) {
726 MachineBasicBlock *SBB = MBBMap[*SI];
727 for (MachineBasicBlock::iterator I = SBB->begin();
728 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
729 if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
730 goto UsesFPReg;
Chris Lattner986618e2004-02-22 19:47:26 +0000731 }
Chris Lattnerfbc39d52004-02-23 07:42:19 +0000732 }
Chris Lattner65cf42d2004-02-23 07:29:45 +0000733 continue;
734 UsesFPReg:
735 // Okay, this block uses an FP register. If the block has successors (ie,
736 // it's not an unwind/return), insert the FP_REG_KILL instruction.
737 if (BB->getBasicBlock()->getTerminator()->getNumSuccessors() &&
738 RequiresFPRegKill(BB->getBasicBlock())) {
Chris Lattneree352852004-02-29 07:22:16 +0000739 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
Chris Lattner65cf42d2004-02-23 07:29:45 +0000740 ++NumFPKill;
Chris Lattner986618e2004-02-22 19:47:26 +0000741 }
742 }
743}
744
745
Chris Lattner307ecba2004-03-30 22:39:09 +0000746// canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
747// it into the conditional branch or select instruction which is the only user
748// of the cc instruction. This is the case if the conditional branch is the
749// only user of the setcc, and if the setcc is in the same basic block as the
750// conditional branch. We also don't handle long arguments below, so we reject
751// them here as well.
Chris Lattner6d40c192003-01-16 16:43:00 +0000752//
Chris Lattner307ecba2004-03-30 22:39:09 +0000753static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
Chris Lattner6d40c192003-01-16 16:43:00 +0000754 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
Chris Lattner307ecba2004-03-30 22:39:09 +0000755 if (SCI->hasOneUse()) {
756 Instruction *User = cast<Instruction>(SCI->use_back());
757 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
758 SCI->getParent() == User->getParent() &&
Chris Lattner48c937e2004-04-06 17:34:50 +0000759 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
760 SCI->getOpcode() == Instruction::SetEQ ||
761 SCI->getOpcode() == Instruction::SetNE))
Chris Lattner6d40c192003-01-16 16:43:00 +0000762 return SCI;
763 }
764 return 0;
765}
Chris Lattner333b2fa2002-12-13 10:09:43 +0000766
Chris Lattner6d40c192003-01-16 16:43:00 +0000767// Return a fixed numbering for setcc instructions which does not depend on the
768// order of the opcodes.
769//
770static unsigned getSetCCNumber(unsigned Opcode) {
771 switch(Opcode) {
772 default: assert(0 && "Unknown setcc instruction!");
773 case Instruction::SetEQ: return 0;
774 case Instruction::SetNE: return 1;
775 case Instruction::SetLT: return 2;
Chris Lattner55f6fab2003-01-16 18:07:23 +0000776 case Instruction::SetGE: return 3;
777 case Instruction::SetGT: return 4;
778 case Instruction::SetLE: return 5;
Chris Lattner6d40c192003-01-16 16:43:00 +0000779 }
780}
Chris Lattner06925362002-11-17 21:56:38 +0000781
Chris Lattner6d40c192003-01-16 16:43:00 +0000782// LLVM -> X86 signed X86 unsigned
783// ----- ---------- ------------
784// seteq -> sete sete
785// setne -> setne setne
786// setlt -> setl setb
Chris Lattner55f6fab2003-01-16 18:07:23 +0000787// setge -> setge setae
Chris Lattner6d40c192003-01-16 16:43:00 +0000788// setgt -> setg seta
789// setle -> setle setbe
Chris Lattnerb2acc512003-10-19 21:09:10 +0000790// ----
791// sets // Used by comparison with 0 optimization
792// setns
793static const unsigned SetCCOpcodeTab[2][8] = {
794 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
795 0, 0 },
796 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
797 X86::SETSr, X86::SETNSr },
Chris Lattner6d40c192003-01-16 16:43:00 +0000798};
799
Chris Lattnerb2acc512003-10-19 21:09:10 +0000800// EmitComparison - This function emits a comparison of the two operands,
801// returning the extended setcc code to use.
802unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
803 MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000804 MachineBasicBlock::iterator IP) {
Brian Gaeke1749d632002-11-07 17:59:21 +0000805 // The arguments are already supposed to be of the same type.
Chris Lattner6d40c192003-01-16 16:43:00 +0000806 const Type *CompTy = Op0->getType();
Chris Lattner3e130a22003-01-13 00:32:26 +0000807 unsigned Class = getClassB(CompTy);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000808 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattner333864d2003-06-05 19:30:30 +0000809
810 // Special case handling of: cmp R, i
Chris Lattnere80e6372004-04-06 16:02:27 +0000811 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
812 if (Class == cByte || Class == cShort || Class == cInt) {
813 unsigned Op1v = CI->getRawValue();
Chris Lattnerc07736a2003-07-23 15:22:26 +0000814
Chris Lattner333864d2003-06-05 19:30:30 +0000815 // Mask off any upper bits of the constant, if there are any...
816 Op1v &= (1ULL << (8 << Class)) - 1;
817
Chris Lattnerb2acc512003-10-19 21:09:10 +0000818 // If this is a comparison against zero, emit more efficient code. We
819 // can't handle unsigned comparisons against zero unless they are == or
820 // !=. These should have been strength reduced already anyway.
821 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
822 static const unsigned TESTTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000823 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
Chris Lattnerb2acc512003-10-19 21:09:10 +0000824 };
Chris Lattneree352852004-02-29 07:22:16 +0000825 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000826
827 if (OpNum == 2) return 6; // Map jl -> js
828 if (OpNum == 3) return 7; // Map jg -> jns
829 return OpNum;
Chris Lattner333864d2003-06-05 19:30:30 +0000830 }
Chris Lattnerb2acc512003-10-19 21:09:10 +0000831
832 static const unsigned CMPTab[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000833 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
Chris Lattnerb2acc512003-10-19 21:09:10 +0000834 };
835
Chris Lattneree352852004-02-29 07:22:16 +0000836 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000837 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +0000838 } else {
839 assert(Class == cLong && "Unknown integer class!");
840 unsigned LowCst = CI->getRawValue();
841 unsigned HiCst = CI->getRawValue() >> 32;
842 if (OpNum < 2) { // seteq, setne
843 unsigned LoTmp = Op0r;
844 if (LowCst != 0) {
845 LoTmp = makeAnotherReg(Type::IntTy);
846 BuildMI(*MBB, IP, X86::XOR32ri, 2, LoTmp).addReg(Op0r).addImm(LowCst);
847 }
848 unsigned HiTmp = Op0r+1;
849 if (HiCst != 0) {
850 HiTmp = makeAnotherReg(Type::IntTy);
Chris Lattner48c937e2004-04-06 17:34:50 +0000851 BuildMI(*MBB, IP, X86::XOR32ri, 2,HiTmp).addReg(Op0r+1).addImm(HiCst);
Chris Lattnere80e6372004-04-06 16:02:27 +0000852 }
853 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
854 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
855 return OpNum;
Chris Lattner48c937e2004-04-06 17:34:50 +0000856 } else {
857 // Emit a sequence of code which compares the high and low parts once
858 // each, then uses a conditional move to handle the overflow case. For
859 // example, a setlt for long would generate code like this:
860 //
861 // AL = lo(op1) < lo(op2) // Signedness depends on operands
862 // BL = hi(op1) < hi(op2) // Always unsigned comparison
863 // dest = hi(op1) == hi(op2) ? AL : BL;
864 //
865
866 // FIXME: This would be much better if we had hierarchical register
867 // classes! Until then, hardcode registers so that we can deal with
868 // their aliases (because we don't have conditional byte moves).
869 //
870 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(LowCst);
871 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
872 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r+1).addImm(HiCst);
873 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0,X86::BL);
874 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
875 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
876 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
877 .addReg(X86::AX);
878 // NOTE: visitSetCondInst knows that the value is dumped into the BL
879 // register at this point for long values...
880 return OpNum;
Chris Lattnere80e6372004-04-06 16:02:27 +0000881 }
Chris Lattner333864d2003-06-05 19:30:30 +0000882 }
Chris Lattnere80e6372004-04-06 16:02:27 +0000883 }
Chris Lattner333864d2003-06-05 19:30:30 +0000884
Chris Lattner9f08a922004-02-03 18:54:04 +0000885 // Special case handling of comparison against +/- 0.0
886 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
887 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
Chris Lattneree352852004-02-29 07:22:16 +0000888 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000889 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +0000890 BuildMI(*MBB, IP, X86::SAHF, 1);
Chris Lattner9f08a922004-02-03 18:54:04 +0000891 return OpNum;
892 }
893
Chris Lattner58c41fe2003-08-24 19:19:47 +0000894 unsigned Op1r = getReg(Op1, MBB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +0000895 switch (Class) {
896 default: assert(0 && "Unknown type class!");
897 // Emit: cmp <var1>, <var2> (do the comparison). We can
898 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
899 // 32-bit.
900 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000901 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000902 break;
903 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000904 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000905 break;
906 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000907 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattner3e130a22003-01-13 00:32:26 +0000908 break;
909 case cFP:
Chris Lattneree352852004-02-29 07:22:16 +0000910 BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000911 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +0000912 BuildMI(*MBB, IP, X86::SAHF, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +0000913 break;
914
915 case cLong:
916 if (OpNum < 2) { // seteq, setne
917 unsigned LoTmp = makeAnotherReg(Type::IntTy);
918 unsigned HiTmp = makeAnotherReg(Type::IntTy);
919 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000920 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
921 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
922 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
Chris Lattner3e130a22003-01-13 00:32:26 +0000923 break; // Allow the sete or setne to be generated from flags set by OR
924 } else {
925 // Emit a sequence of code which compares the high and low parts once
926 // each, then uses a conditional move to handle the overflow case. For
927 // example, a setlt for long would generate code like this:
928 //
929 // AL = lo(op1) < lo(op2) // Signedness depends on operands
930 // BL = hi(op1) < hi(op2) // Always unsigned comparison
931 // dest = hi(op1) == hi(op2) ? AL : BL;
932 //
933
Chris Lattner6d40c192003-01-16 16:43:00 +0000934 // FIXME: This would be much better if we had hierarchical register
Chris Lattner3e130a22003-01-13 00:32:26 +0000935 // classes! Until then, hardcode registers so that we can deal with their
936 // aliases (because we don't have conditional byte moves).
937 //
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000938 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
Chris Lattneree352852004-02-29 07:22:16 +0000939 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000940 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
Chris Lattneree352852004-02-29 07:22:16 +0000941 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
942 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
943 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000944 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
Chris Lattneree352852004-02-29 07:22:16 +0000945 .addReg(X86::AX);
Chris Lattner6d40c192003-01-16 16:43:00 +0000946 // NOTE: visitSetCondInst knows that the value is dumped into the BL
947 // register at this point for long values...
Chris Lattnerb2acc512003-10-19 21:09:10 +0000948 return OpNum;
Chris Lattner3e130a22003-01-13 00:32:26 +0000949 }
950 }
Chris Lattnerb2acc512003-10-19 21:09:10 +0000951 return OpNum;
Chris Lattner6d40c192003-01-16 16:43:00 +0000952}
Chris Lattner3e130a22003-01-13 00:32:26 +0000953
Chris Lattner6d40c192003-01-16 16:43:00 +0000954/// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
955/// register, then move it to wherever the result should be.
956///
957void ISel::visitSetCondInst(SetCondInst &I) {
Chris Lattner307ecba2004-03-30 22:39:09 +0000958 if (canFoldSetCCIntoBranchOrSelect(&I))
959 return; // Fold this into a branch or select.
Chris Lattner6d40c192003-01-16 16:43:00 +0000960
Chris Lattner6d40c192003-01-16 16:43:00 +0000961 unsigned DestReg = getReg(I);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000962 MachineBasicBlock::iterator MII = BB->end();
963 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
964 DestReg);
965}
Chris Lattner6d40c192003-01-16 16:43:00 +0000966
Chris Lattner58c41fe2003-08-24 19:19:47 +0000967/// emitSetCCOperation - Common code shared between visitSetCondInst and
968/// constant expression support.
Misha Brukman538607f2004-03-01 23:53:11 +0000969///
Chris Lattner58c41fe2003-08-24 19:19:47 +0000970void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +0000971 MachineBasicBlock::iterator IP,
Chris Lattner58c41fe2003-08-24 19:19:47 +0000972 Value *Op0, Value *Op1, unsigned Opcode,
973 unsigned TargetReg) {
974 unsigned OpNum = getSetCCNumber(Opcode);
Chris Lattnerb2acc512003-10-19 21:09:10 +0000975 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
Chris Lattner58c41fe2003-08-24 19:19:47 +0000976
Chris Lattnerb2acc512003-10-19 21:09:10 +0000977 const Type *CompTy = Op0->getType();
978 unsigned CompClass = getClassB(CompTy);
979 bool isSigned = CompTy->isSigned() && CompClass != cFP;
980
981 if (CompClass != cLong || OpNum < 2) {
Chris Lattner6d40c192003-01-16 16:43:00 +0000982 // Handle normal comparisons with a setcc instruction...
Chris Lattneree352852004-02-29 07:22:16 +0000983 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
Chris Lattner6d40c192003-01-16 16:43:00 +0000984 } else {
985 // Handle long comparisons by copying the value which is already in BL into
986 // the register we want...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +0000987 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
Chris Lattner6d40c192003-01-16 16:43:00 +0000988 }
Brian Gaeke1749d632002-11-07 17:59:21 +0000989}
Chris Lattner51b49a92002-11-02 19:45:49 +0000990
Chris Lattner12d96a02004-03-30 21:22:00 +0000991void ISel::visitSelectInst(SelectInst &SI) {
992 unsigned DestReg = getReg(SI);
993 MachineBasicBlock::iterator MII = BB->end();
994 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
995 SI.getFalseValue(), DestReg);
996}
997
998/// emitSelect - Common code shared between visitSelectInst and the constant
999/// expression support.
1000void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1001 MachineBasicBlock::iterator IP,
1002 Value *Cond, Value *TrueVal, Value *FalseVal,
1003 unsigned DestReg) {
1004 unsigned SelectClass = getClassB(TrueVal->getType());
1005
1006 // We don't support 8-bit conditional moves. If we have incoming constants,
1007 // transform them into 16-bit constants to avoid having a run-time conversion.
1008 if (SelectClass == cByte) {
1009 if (Constant *T = dyn_cast<Constant>(TrueVal))
1010 TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
1011 if (Constant *F = dyn_cast<Constant>(FalseVal))
1012 FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
1013 }
1014
Chris Lattner307ecba2004-03-30 22:39:09 +00001015
1016 unsigned Opcode;
1017 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1018 // We successfully folded the setcc into the select instruction.
1019
1020 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1021 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1022 IP);
1023
1024 const Type *CompTy = SCI->getOperand(0)->getType();
1025 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1026
1027 // LLVM -> X86 signed X86 unsigned
1028 // ----- ---------- ------------
1029 // seteq -> cmovNE cmovNE
1030 // setne -> cmovE cmovE
1031 // setlt -> cmovGE cmovAE
1032 // setge -> cmovL cmovB
1033 // setgt -> cmovLE cmovBE
1034 // setle -> cmovG cmovA
1035 // ----
1036 // cmovNS // Used by comparison with 0 optimization
1037 // cmovS
1038
1039 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001040 default: assert(0 && "Unknown value class!");
1041 case cFP: {
1042 // Annoyingly, we don't have a full set of floating point conditional
1043 // moves. :(
1044 static const unsigned OpcodeTab[2][8] = {
1045 { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
1046 X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1047 { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1048 };
1049 Opcode = OpcodeTab[isSigned][OpNum];
1050
1051 // If opcode == 0, we hit a case that we don't support. Output a setcc
1052 // and compare the result against zero.
1053 if (Opcode == 0) {
1054 unsigned CompClass = getClassB(CompTy);
1055 unsigned CondReg;
1056 if (CompClass != cLong || OpNum < 2) {
1057 CondReg = makeAnotherReg(Type::BoolTy);
1058 // Handle normal comparisons with a setcc instruction...
1059 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1060 } else {
1061 // Long comparisons end up in the BL register.
1062 CondReg = X86::BL;
1063 }
1064
Chris Lattner68626c22004-03-31 22:22:36 +00001065 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner352eb482004-03-31 22:03:35 +00001066 Opcode = X86::FCMOVE;
1067 }
1068 break;
1069 }
Chris Lattner307ecba2004-03-30 22:39:09 +00001070 case cByte:
1071 case cShort: {
1072 static const unsigned OpcodeTab[2][8] = {
1073 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1074 X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1075 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1076 X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1077 };
1078 Opcode = OpcodeTab[isSigned][OpNum];
1079 break;
1080 }
1081 case cInt:
1082 case cLong: {
1083 static const unsigned OpcodeTab[2][8] = {
1084 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1085 X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1086 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1087 X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1088 };
1089 Opcode = OpcodeTab[isSigned][OpNum];
1090 break;
1091 }
1092 }
1093 } else {
1094 // Get the value being branched on, and use it to set the condition codes.
1095 unsigned CondReg = getReg(Cond, MBB, IP);
Chris Lattner68626c22004-03-31 22:22:36 +00001096 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
Chris Lattner307ecba2004-03-30 22:39:09 +00001097 switch (SelectClass) {
Chris Lattner352eb482004-03-31 22:03:35 +00001098 default: assert(0 && "Unknown value class!");
1099 case cFP: Opcode = X86::FCMOVE; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001100 case cByte:
Chris Lattner352eb482004-03-31 22:03:35 +00001101 case cShort: Opcode = X86::CMOVE16rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001102 case cInt:
Chris Lattner352eb482004-03-31 22:03:35 +00001103 case cLong: Opcode = X86::CMOVE32rr; break;
Chris Lattner307ecba2004-03-30 22:39:09 +00001104 }
1105 }
Chris Lattner12d96a02004-03-30 21:22:00 +00001106
1107 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1108 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1109 unsigned RealDestReg = DestReg;
Chris Lattner12d96a02004-03-30 21:22:00 +00001110
Chris Lattner12d96a02004-03-30 21:22:00 +00001111
1112 // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves. Because of
1113 // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1114 // cmove, then truncate the result.
1115 if (SelectClass == cByte) {
1116 DestReg = makeAnotherReg(Type::ShortTy);
1117 if (getClassB(TrueVal->getType()) == cByte) {
1118 // Promote the true value, by storing it into AL, and reading from AX.
1119 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1120 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1121 TrueReg = makeAnotherReg(Type::ShortTy);
1122 BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1123 }
1124 if (getClassB(FalseVal->getType()) == cByte) {
1125 // Promote the true value, by storing it into CL, and reading from CX.
1126 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1127 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1128 FalseReg = makeAnotherReg(Type::ShortTy);
1129 BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1130 }
1131 }
1132
1133 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1134
1135 switch (SelectClass) {
1136 case cByte:
1137 // We did the computation with 16-bit registers. Truncate back to our
1138 // result by copying into AX then copying out AL.
1139 BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1140 BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1141 break;
1142 case cLong:
1143 // Move the upper half of the value as well.
1144 BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1145 break;
1146 }
1147}
Chris Lattner58c41fe2003-08-24 19:19:47 +00001148
1149
1150
Brian Gaekec2505982002-11-30 11:57:28 +00001151/// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1152/// operand, in the specified target register.
Misha Brukman538607f2004-03-01 23:53:11 +00001153///
Chris Lattner3e130a22003-01-13 00:32:26 +00001154void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1155 bool isUnsigned = VR.Ty->isUnsigned();
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001156
Chris Lattner29bf0622004-04-06 01:21:00 +00001157 Value *Val = VR.Val;
1158 const Type *Ty = VR.Ty;
Chris Lattner502e36c2004-04-06 01:25:33 +00001159 if (Val) {
Chris Lattner29bf0622004-04-06 01:21:00 +00001160 if (Constant *C = dyn_cast<Constant>(Val)) {
1161 Val = ConstantExpr::getCast(C, Type::IntTy);
1162 Ty = Type::IntTy;
1163 }
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001164
Chris Lattner502e36c2004-04-06 01:25:33 +00001165 // If this is a simple constant, just emit a MOVri directly to avoid the
1166 // copy.
1167 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1168 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1169 BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
1170 return;
1171 }
1172 }
1173
Chris Lattner29bf0622004-04-06 01:21:00 +00001174 // Make sure we have the register number for this value...
1175 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1176
1177 switch (getClassB(Ty)) {
Chris Lattner94af4142002-12-25 05:13:53 +00001178 case cByte:
1179 // Extend value into target register (8->32)
1180 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001181 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001182 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001183 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001184 break;
1185 case cShort:
1186 // Extend value into target register (16->32)
1187 if (isUnsigned)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001188 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001189 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001190 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001191 break;
1192 case cInt:
1193 // Move value into target register (32->32)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001194 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001195 break;
1196 default:
1197 assert(0 && "Unpromotable operand class in promote32");
1198 }
Brian Gaekec2505982002-11-30 11:57:28 +00001199}
Chris Lattnerc5291f52002-10-27 21:16:59 +00001200
Chris Lattner72614082002-10-25 22:55:53 +00001201/// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
1202/// we have the following possibilities:
1203///
1204/// ret void: No return value, simply emit a 'ret' instruction
1205/// ret sbyte, ubyte : Extend value into EAX and return
1206/// ret short, ushort: Extend value into EAX and return
1207/// ret int, uint : Move value into EAX and return
1208/// ret pointer : Move value into EAX and return
Chris Lattner06925362002-11-17 21:56:38 +00001209/// ret long, ulong : Move value into EAX/EDX and return
1210/// ret float/double : Top of FP stack
Chris Lattner72614082002-10-25 22:55:53 +00001211///
Chris Lattner3e130a22003-01-13 00:32:26 +00001212void ISel::visitReturnInst(ReturnInst &I) {
Chris Lattner94af4142002-12-25 05:13:53 +00001213 if (I.getNumOperands() == 0) {
1214 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1215 return;
1216 }
1217
1218 Value *RetVal = I.getOperand(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00001219 switch (getClassB(RetVal->getType())) {
Chris Lattner94af4142002-12-25 05:13:53 +00001220 case cByte: // integral return values: extend or move into EAX and return
1221 case cShort:
1222 case cInt:
Chris Lattner29bf0622004-04-06 01:21:00 +00001223 promote32(X86::EAX, ValueRecord(RetVal));
Chris Lattnerdbd73722003-05-06 21:32:22 +00001224 // Declare that EAX is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +00001225 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +00001226 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001227 case cFP: { // Floats & Doubles: Return in ST(0)
1228 unsigned RetReg = getReg(RetVal);
Chris Lattner3e130a22003-01-13 00:32:26 +00001229 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
Chris Lattnerdbd73722003-05-06 21:32:22 +00001230 // Declare that top-of-stack is live on exit
Chris Lattnerc2489032003-05-07 19:21:28 +00001231 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
Chris Lattner94af4142002-12-25 05:13:53 +00001232 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001233 }
1234 case cLong: {
1235 unsigned RetReg = getReg(RetVal);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001236 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1237 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
Chris Lattnerdbd73722003-05-06 21:32:22 +00001238 // Declare that EAX & EDX are live on exit
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001239 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1240 .addReg(X86::ESP);
Chris Lattner3e130a22003-01-13 00:32:26 +00001241 break;
Chris Lattner29bf0622004-04-06 01:21:00 +00001242 }
Chris Lattner94af4142002-12-25 05:13:53 +00001243 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00001244 visitInstruction(I);
Chris Lattner94af4142002-12-25 05:13:53 +00001245 }
Chris Lattner43189d12002-11-17 20:07:45 +00001246 // Emit a 'ret' instruction
Chris Lattner94af4142002-12-25 05:13:53 +00001247 BuildMI(BB, X86::RET, 0);
Chris Lattner72614082002-10-25 22:55:53 +00001248}
1249
Chris Lattner55f6fab2003-01-16 18:07:23 +00001250// getBlockAfter - Return the basic block which occurs lexically after the
1251// specified one.
1252static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1253 Function::iterator I = BB; ++I; // Get iterator to next block
1254 return I != BB->getParent()->end() ? &*I : 0;
1255}
1256
Chris Lattner51b49a92002-11-02 19:45:49 +00001257/// visitBranchInst - Handle conditional and unconditional branches here. Note
1258/// that since code layout is frozen at this point, that if we are trying to
1259/// jump to a block that is the immediate successor of the current block, we can
Chris Lattner6d40c192003-01-16 16:43:00 +00001260/// just make a fall-through (but we don't currently).
Chris Lattner51b49a92002-11-02 19:45:49 +00001261///
Chris Lattner94af4142002-12-25 05:13:53 +00001262void ISel::visitBranchInst(BranchInst &BI) {
Chris Lattner55f6fab2003-01-16 18:07:23 +00001263 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1264
1265 if (!BI.isConditional()) { // Unconditional branch?
Chris Lattnercf93cdd2004-01-30 22:13:44 +00001266 if (BI.getSuccessor(0) != NextBB)
Chris Lattner55f6fab2003-01-16 18:07:23 +00001267 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
Chris Lattner6d40c192003-01-16 16:43:00 +00001268 return;
1269 }
1270
1271 // See if we can fold the setcc into the branch itself...
Chris Lattner307ecba2004-03-30 22:39:09 +00001272 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
Chris Lattner6d40c192003-01-16 16:43:00 +00001273 if (SCI == 0) {
1274 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1275 // computed some other way...
Chris Lattner065faeb2002-12-28 20:24:02 +00001276 unsigned condReg = getReg(BI.getCondition());
Chris Lattner68626c22004-03-31 22:22:36 +00001277 BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
Chris Lattner55f6fab2003-01-16 18:07:23 +00001278 if (BI.getSuccessor(1) == NextBB) {
1279 if (BI.getSuccessor(0) != NextBB)
1280 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1281 } else {
1282 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1283
1284 if (BI.getSuccessor(0) != NextBB)
1285 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1286 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001287 return;
Chris Lattner94af4142002-12-25 05:13:53 +00001288 }
Chris Lattner6d40c192003-01-16 16:43:00 +00001289
1290 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
Chris Lattner58c41fe2003-08-24 19:19:47 +00001291 MachineBasicBlock::iterator MII = BB->end();
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001292 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001293
1294 const Type *CompTy = SCI->getOperand(0)->getType();
1295 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
Chris Lattner6d40c192003-01-16 16:43:00 +00001296
Chris Lattnerb2acc512003-10-19 21:09:10 +00001297
Chris Lattner6d40c192003-01-16 16:43:00 +00001298 // LLVM -> X86 signed X86 unsigned
1299 // ----- ---------- ------------
1300 // seteq -> je je
1301 // setne -> jne jne
1302 // setlt -> jl jb
Chris Lattner55f6fab2003-01-16 18:07:23 +00001303 // setge -> jge jae
Chris Lattner6d40c192003-01-16 16:43:00 +00001304 // setgt -> jg ja
1305 // setle -> jle jbe
Chris Lattnerb2acc512003-10-19 21:09:10 +00001306 // ----
1307 // js // Used by comparison with 0 optimization
1308 // jns
1309
1310 static const unsigned OpcodeTab[2][8] = {
1311 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1312 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1313 X86::JS, X86::JNS },
Chris Lattner6d40c192003-01-16 16:43:00 +00001314 };
1315
Chris Lattner55f6fab2003-01-16 18:07:23 +00001316 if (BI.getSuccessor(0) != NextBB) {
1317 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1318 if (BI.getSuccessor(1) != NextBB)
1319 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1320 } else {
1321 // Change to the inverse condition...
1322 if (BI.getSuccessor(1) != NextBB) {
1323 OpNum ^= 1;
1324 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1325 }
1326 }
Chris Lattner2df035b2002-11-02 19:27:56 +00001327}
1328
Chris Lattner3e130a22003-01-13 00:32:26 +00001329
1330/// doCall - This emits an abstract call instruction, setting up the arguments
1331/// and the return value as appropriate. For the actual function call itself,
1332/// it inserts the specified CallMI instruction into the stream.
1333///
1334void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001335 const std::vector<ValueRecord> &Args) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001336
Chris Lattner065faeb2002-12-28 20:24:02 +00001337 // Count how many bytes are to be pushed on the stack...
1338 unsigned NumBytes = 0;
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001339
Chris Lattner3e130a22003-01-13 00:32:26 +00001340 if (!Args.empty()) {
1341 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1342 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001343 case cByte: case cShort: case cInt:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001344 NumBytes += 4; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001345 case cLong:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001346 NumBytes += 8; break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001347 case cFP:
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001348 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1349 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001350 default: assert(0 && "Unknown class!");
1351 }
1352
1353 // Adjust the stack pointer for the new arguments...
Chris Lattneree352852004-02-29 07:22:16 +00001354 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
Chris Lattner065faeb2002-12-28 20:24:02 +00001355
1356 // Arguments go on the stack in reverse order, as specified by the ABI.
1357 unsigned ArgOffset = 0;
Chris Lattner3e130a22003-01-13 00:32:26 +00001358 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Chris Lattnerce6096f2004-03-01 02:34:08 +00001359 unsigned ArgReg;
Chris Lattner3e130a22003-01-13 00:32:26 +00001360 switch (getClassB(Args[i].Ty)) {
Chris Lattner065faeb2002-12-28 20:24:02 +00001361 case cByte:
Chris Lattner21585222004-03-01 02:42:43 +00001362 case cShort:
1363 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1364 // Zero/Sign extend constant, then stuff into memory.
1365 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1366 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1367 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1368 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1369 } else {
1370 // Promote arg to 32 bits wide into a temporary register...
1371 ArgReg = makeAnotherReg(Type::UIntTy);
1372 promote32(ArgReg, Args[i]);
1373 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1374 X86::ESP, ArgOffset).addReg(ArgReg);
1375 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001376 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001377 case cInt:
Chris Lattner21585222004-03-01 02:42:43 +00001378 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1379 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1380 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1381 X86::ESP, ArgOffset).addImm(Val);
1382 } else {
1383 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1384 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1385 X86::ESP, ArgOffset).addReg(ArgReg);
1386 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001387 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001388 case cLong:
Chris Lattner92900a62004-04-06 03:23:00 +00001389 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1390 uint64_t Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1391 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1392 X86::ESP, ArgOffset).addImm(Val & ~0U);
1393 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1394 X86::ESP, ArgOffset+4).addImm(Val >> 32ULL);
1395 } else {
1396 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1397 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1398 X86::ESP, ArgOffset).addReg(ArgReg);
1399 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1400 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1401 }
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001402 ArgOffset += 4; // 8 byte entry, not 4.
1403 break;
1404
Chris Lattner065faeb2002-12-28 20:24:02 +00001405 case cFP:
Chris Lattnerce6096f2004-03-01 02:34:08 +00001406 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001407 if (Args[i].Ty == Type::FloatTy) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001408 addRegOffset(BuildMI(BB, X86::FST32m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001409 X86::ESP, ArgOffset).addReg(ArgReg);
1410 } else {
1411 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001412 addRegOffset(BuildMI(BB, X86::FST64m, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001413 X86::ESP, ArgOffset).addReg(ArgReg);
1414 ArgOffset += 4; // 8 byte entry, not 4.
1415 }
1416 break;
Chris Lattner065faeb2002-12-28 20:24:02 +00001417
Chris Lattner3e130a22003-01-13 00:32:26 +00001418 default: assert(0 && "Unknown class!");
Chris Lattner065faeb2002-12-28 20:24:02 +00001419 }
1420 ArgOffset += 4;
Chris Lattner94af4142002-12-25 05:13:53 +00001421 }
Chris Lattner3e130a22003-01-13 00:32:26 +00001422 } else {
Chris Lattneree352852004-02-29 07:22:16 +00001423 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
Chris Lattner94af4142002-12-25 05:13:53 +00001424 }
Chris Lattner6e49a4b2002-12-13 14:13:27 +00001425
Chris Lattner3e130a22003-01-13 00:32:26 +00001426 BB->push_back(CallMI);
Misha Brukman0d2cf3a2002-12-04 19:22:53 +00001427
Chris Lattneree352852004-02-29 07:22:16 +00001428 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
Chris Lattnera3243642002-12-04 23:45:28 +00001429
1430 // If there is a return value, scavenge the result from the location the call
1431 // leaves it in...
1432 //
Chris Lattner3e130a22003-01-13 00:32:26 +00001433 if (Ret.Ty != Type::VoidTy) {
1434 unsigned DestClass = getClassB(Ret.Ty);
1435 switch (DestClass) {
Brian Gaeke20244b72002-12-12 15:33:40 +00001436 case cByte:
1437 case cShort:
1438 case cInt: {
1439 // Integral results are in %eax, or the appropriate portion
1440 // thereof.
1441 static const unsigned regRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001442 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
Brian Gaeke20244b72002-12-12 15:33:40 +00001443 };
1444 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
Chris Lattner3e130a22003-01-13 00:32:26 +00001445 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001446 break;
Brian Gaeke20244b72002-12-12 15:33:40 +00001447 }
Chris Lattner94af4142002-12-25 05:13:53 +00001448 case cFP: // Floating-point return values live in %ST(0)
Chris Lattner3e130a22003-01-13 00:32:26 +00001449 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
Brian Gaeke20244b72002-12-12 15:33:40 +00001450 break;
Chris Lattner3e130a22003-01-13 00:32:26 +00001451 case cLong: // Long values are left in EDX:EAX
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001452 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1453 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
Chris Lattner3e130a22003-01-13 00:32:26 +00001454 break;
1455 default: assert(0 && "Unknown class!");
Chris Lattner4fa1acc2002-12-04 23:50:28 +00001456 }
Chris Lattnera3243642002-12-04 23:45:28 +00001457 }
Brian Gaekefa8d5712002-11-22 11:07:01 +00001458}
Chris Lattner2df035b2002-11-02 19:27:56 +00001459
Chris Lattner3e130a22003-01-13 00:32:26 +00001460
1461/// visitCallInst - Push args on stack and do a procedure call instruction.
1462void ISel::visitCallInst(CallInst &CI) {
1463 MachineInstr *TheCall;
1464 if (Function *F = CI.getCalledFunction()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001465 // Is it an intrinsic function call?
Brian Gaeked0fde302003-11-11 22:41:34 +00001466 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001467 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1468 return;
1469 }
1470
Chris Lattner3e130a22003-01-13 00:32:26 +00001471 // Emit a CALL instruction with PC-relative displacement.
1472 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1473 } else { // Emit an indirect call...
1474 unsigned Reg = getReg(CI.getCalledValue());
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001475 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
Chris Lattner3e130a22003-01-13 00:32:26 +00001476 }
1477
1478 std::vector<ValueRecord> Args;
1479 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00001480 Args.push_back(ValueRecord(CI.getOperand(i)));
Chris Lattner3e130a22003-01-13 00:32:26 +00001481
1482 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1483 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00001484}
Chris Lattner3e130a22003-01-13 00:32:26 +00001485
Chris Lattneraeb54b82003-08-28 21:23:43 +00001486
Chris Lattner44827152003-12-28 09:47:19 +00001487/// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1488/// function, lowering any calls to unknown intrinsic functions into the
1489/// equivalent LLVM code.
Misha Brukman538607f2004-03-01 23:53:11 +00001490///
Chris Lattner44827152003-12-28 09:47:19 +00001491void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1492 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1493 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1494 if (CallInst *CI = dyn_cast<CallInst>(I++))
1495 if (Function *F = CI->getCalledFunction())
1496 switch (F->getIntrinsicID()) {
Chris Lattneraed386e2003-12-28 09:53:23 +00001497 case Intrinsic::not_intrinsic:
Chris Lattner317201d2004-03-13 00:24:00 +00001498 case Intrinsic::vastart:
1499 case Intrinsic::vacopy:
1500 case Intrinsic::vaend:
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001501 case Intrinsic::returnaddress:
1502 case Intrinsic::frameaddress:
Chris Lattner915e5e52004-02-12 17:53:22 +00001503 case Intrinsic::memcpy:
Chris Lattner2a0f2242004-02-14 04:46:05 +00001504 case Intrinsic::memset:
John Criswell4ffff9e2004-04-08 20:31:47 +00001505 case Intrinsic::readport:
1506 case Intrinsic::writeport:
Chris Lattner44827152003-12-28 09:47:19 +00001507 // We directly implement these intrinsics
1508 break;
1509 default:
1510 // All other intrinsic calls we must lower.
1511 Instruction *Before = CI->getPrev();
Chris Lattnerf70e0c22003-12-28 21:23:38 +00001512 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
Chris Lattner44827152003-12-28 09:47:19 +00001513 if (Before) { // Move iterator to instruction after call
1514 I = Before; ++I;
1515 } else {
1516 I = BB->begin();
1517 }
1518 }
1519
1520}
1521
Brian Gaeked0fde302003-11-11 22:41:34 +00001522void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
Chris Lattnereca195e2003-05-08 19:44:13 +00001523 unsigned TmpReg1, TmpReg2;
1524 switch (ID) {
Chris Lattner5634b9f2004-03-13 00:24:52 +00001525 case Intrinsic::vastart:
Chris Lattnereca195e2003-05-08 19:44:13 +00001526 // Get the address of the first vararg value...
Chris Lattner73815062003-10-18 05:56:40 +00001527 TmpReg1 = getReg(CI);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001528 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
Chris Lattnereca195e2003-05-08 19:44:13 +00001529 return;
1530
Chris Lattner5634b9f2004-03-13 00:24:52 +00001531 case Intrinsic::vacopy:
Chris Lattner73815062003-10-18 05:56:40 +00001532 TmpReg1 = getReg(CI);
1533 TmpReg2 = getReg(CI.getOperand(1));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001534 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
Chris Lattnereca195e2003-05-08 19:44:13 +00001535 return;
Chris Lattner5634b9f2004-03-13 00:24:52 +00001536 case Intrinsic::vaend: return; // Noop on X86
Chris Lattnereca195e2003-05-08 19:44:13 +00001537
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001538 case Intrinsic::returnaddress:
1539 case Intrinsic::frameaddress:
1540 TmpReg1 = getReg(CI);
1541 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1542 if (ID == Intrinsic::returnaddress) {
1543 // Just load the return address
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001544 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001545 ReturnAddressIndex);
1546 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001547 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001548 ReturnAddressIndex, -4);
1549 }
1550 } else {
1551 // Values other than zero are not implemented yet.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001552 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
Chris Lattner0e5b79c2004-02-15 01:04:03 +00001553 }
1554 return;
1555
Chris Lattner915e5e52004-02-12 17:53:22 +00001556 case Intrinsic::memcpy: {
1557 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1558 unsigned Align = 1;
1559 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1560 Align = AlignC->getRawValue();
1561 if (Align == 0) Align = 1;
1562 }
1563
1564 // Turn the byte code into # iterations
Chris Lattner915e5e52004-02-12 17:53:22 +00001565 unsigned CountReg;
Chris Lattner2a0f2242004-02-14 04:46:05 +00001566 unsigned Opcode;
Chris Lattner915e5e52004-02-12 17:53:22 +00001567 switch (Align & 3) {
1568 case 2: // WORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001569 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1570 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1571 } else {
1572 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001573 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001574 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner07122832004-02-13 23:36:47 +00001575 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001576 Opcode = X86::REP_MOVSW;
Chris Lattner915e5e52004-02-12 17:53:22 +00001577 break;
1578 case 0: // DWORD aligned
Chris Lattner07122832004-02-13 23:36:47 +00001579 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1580 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1581 } else {
1582 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001583 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001584 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner07122832004-02-13 23:36:47 +00001585 }
Chris Lattner2a0f2242004-02-14 04:46:05 +00001586 Opcode = X86::REP_MOVSD;
Chris Lattner915e5e52004-02-12 17:53:22 +00001587 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001588 default: // BYTE aligned
Chris Lattner07122832004-02-13 23:36:47 +00001589 CountReg = getReg(CI.getOperand(3));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001590 Opcode = X86::REP_MOVSB;
Chris Lattner915e5e52004-02-12 17:53:22 +00001591 break;
1592 }
1593
1594 // No matter what the alignment is, we put the source in ESI, the
1595 // destination in EDI, and the count in ECX.
1596 TmpReg1 = getReg(CI.getOperand(1));
1597 TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001598 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1599 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1600 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001601 BuildMI(BB, Opcode, 0);
1602 return;
1603 }
1604 case Intrinsic::memset: {
1605 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1606 unsigned Align = 1;
1607 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1608 Align = AlignC->getRawValue();
1609 if (Align == 0) Align = 1;
Chris Lattner915e5e52004-02-12 17:53:22 +00001610 }
1611
Chris Lattner2a0f2242004-02-14 04:46:05 +00001612 // Turn the byte code into # iterations
Chris Lattner2a0f2242004-02-14 04:46:05 +00001613 unsigned CountReg;
1614 unsigned Opcode;
1615 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1616 unsigned Val = ValC->getRawValue() & 255;
1617
1618 // If the value is a constant, then we can potentially use larger copies.
1619 switch (Align & 3) {
1620 case 2: // WORD aligned
1621 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001622 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001623 } else {
1624 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001625 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001626 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001627 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001628 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001629 Opcode = X86::REP_STOSW;
1630 break;
1631 case 0: // DWORD aligned
1632 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
Chris Lattner300d0ed2004-02-14 06:00:36 +00001633 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
Chris Lattner2a0f2242004-02-14 04:46:05 +00001634 } else {
1635 CountReg = makeAnotherReg(Type::IntTy);
Chris Lattner8dd8d262004-02-26 01:20:02 +00001636 unsigned ByteReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001637 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001638 }
1639 Val = (Val << 8) | Val;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001640 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001641 Opcode = X86::REP_STOSD;
1642 break;
Chris Lattner8dd8d262004-02-26 01:20:02 +00001643 default: // BYTE aligned
Chris Lattner2a0f2242004-02-14 04:46:05 +00001644 CountReg = getReg(CI.getOperand(3));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001645 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001646 Opcode = X86::REP_STOSB;
1647 break;
1648 }
1649 } else {
1650 // If it's not a constant value we are storing, just fall back. We could
1651 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1652 unsigned ValReg = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001653 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001654 CountReg = getReg(CI.getOperand(3));
1655 Opcode = X86::REP_STOSB;
1656 }
1657
1658 // No matter what the alignment is, we put the source in ESI, the
1659 // destination in EDI, and the count in ECX.
1660 TmpReg1 = getReg(CI.getOperand(1));
1661 //TmpReg2 = getReg(CI.getOperand(2));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001662 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1663 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
Chris Lattner2a0f2242004-02-14 04:46:05 +00001664 BuildMI(BB, Opcode, 0);
Chris Lattner915e5e52004-02-12 17:53:22 +00001665 return;
1666 }
1667
John Criswell4ffff9e2004-04-08 20:31:47 +00001668 case Intrinsic::readport:
1669 //
1670 // First, determine that the size of the operand falls within the
1671 // acceptable range for this architecture.
1672 //
John Criswellca6ea0f2004-04-08 22:39:13 +00001673 if ((CI.getOperand(1)->getType()->getPrimitiveSize()) != 2) {
1674 std::cerr << "llvm.readport: Address size is not 16 bits\n";
1675 exit (1);
1676 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001677
1678 //
1679 // Now, move the I/O port address into the DX register and use the IN
1680 // instruction to get the input data.
1681 //
1682 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(getReg(CI.getOperand(1)));
1683 switch (CI.getCalledFunction()->getReturnType()->getPrimitiveSize()) {
1684 case 1:
John Criswellca6ea0f2004-04-08 22:39:13 +00001685 BuildMI(BB, X86::IN8, 0);
John Criswell4ffff9e2004-04-08 20:31:47 +00001686 break;
1687 case 2:
John Criswellca6ea0f2004-04-08 22:39:13 +00001688 BuildMI(BB, X86::IN16, 0);
John Criswell4ffff9e2004-04-08 20:31:47 +00001689 break;
1690 case 4:
John Criswellca6ea0f2004-04-08 22:39:13 +00001691 BuildMI(BB, X86::IN32, 0);
John Criswell4ffff9e2004-04-08 20:31:47 +00001692 break;
1693 default:
John Criswellaee0cf32004-04-09 15:10:15 +00001694 std::cerr << "Cannot do input on this data type";
1695 exit (1);
John Criswell4ffff9e2004-04-08 20:31:47 +00001696 }
1697 return;
1698
1699 case Intrinsic::writeport:
1700 //
1701 // First, determine that the size of the operand falls within the
1702 // acceptable range for this architecture.
1703 //
John Criswellca6ea0f2004-04-08 22:39:13 +00001704 //
John Criswell6d804f42004-04-09 19:09:14 +00001705 if ((CI.getOperand(2)->getType()->getPrimitiveSize()) != 2) {
John Criswellca6ea0f2004-04-08 22:39:13 +00001706 std::cerr << "llvm.writeport: Address size is not 16 bits\n";
1707 exit (1);
1708 }
John Criswell4ffff9e2004-04-08 20:31:47 +00001709
1710 //
1711 // Now, move the I/O port address into the DX register and the value to
1712 // write into the AL/AX/EAX register.
1713 //
John Criswell6d804f42004-04-09 19:09:14 +00001714 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(getReg(CI.getOperand(2)));
1715 switch (CI.getOperand(1)->getType()->getPrimitiveSize()) {
John Criswell4ffff9e2004-04-08 20:31:47 +00001716 case 1:
John Criswell6d804f42004-04-09 19:09:14 +00001717 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(getReg(CI.getOperand(1)));
John Criswellca6ea0f2004-04-08 22:39:13 +00001718 BuildMI(BB, X86::OUT8, 0);
John Criswell4ffff9e2004-04-08 20:31:47 +00001719 break;
1720 case 2:
John Criswell6d804f42004-04-09 19:09:14 +00001721 BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(getReg(CI.getOperand(1)));
John Criswellca6ea0f2004-04-08 22:39:13 +00001722 BuildMI(BB, X86::OUT16, 0);
John Criswell4ffff9e2004-04-08 20:31:47 +00001723 break;
1724 case 4:
John Criswell6d804f42004-04-09 19:09:14 +00001725 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(getReg(CI.getOperand(1)));
John Criswellca6ea0f2004-04-08 22:39:13 +00001726 BuildMI(BB, X86::OUT32, 0);
John Criswell4ffff9e2004-04-08 20:31:47 +00001727 break;
1728 default:
John Criswellaee0cf32004-04-09 15:10:15 +00001729 std::cerr << "Cannot do output on this data type";
1730 exit (1);
John Criswell4ffff9e2004-04-08 20:31:47 +00001731 }
1732 return;
1733
Chris Lattner44827152003-12-28 09:47:19 +00001734 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
Chris Lattnereca195e2003-05-08 19:44:13 +00001735 }
1736}
1737
Chris Lattner7dee5da2004-03-08 01:58:35 +00001738static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1739 if (LI.getParent() != User.getParent())
1740 return false;
1741 BasicBlock::iterator It = &LI;
1742 // Check all of the instructions between the load and the user. We should
1743 // really use alias analysis here, but for now we just do something simple.
1744 for (++It; It != BasicBlock::iterator(&User); ++It) {
1745 switch (It->getOpcode()) {
Chris Lattner85c84e72004-03-18 06:29:54 +00001746 case Instruction::Free:
Chris Lattner7dee5da2004-03-08 01:58:35 +00001747 case Instruction::Store:
1748 case Instruction::Call:
1749 case Instruction::Invoke:
1750 return false;
1751 }
1752 }
1753 return true;
1754}
1755
Chris Lattnereca195e2003-05-08 19:44:13 +00001756
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001757/// visitSimpleBinary - Implement simple binary operators for integral types...
1758/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1759/// Xor.
Misha Brukman538607f2004-03-01 23:53:11 +00001760///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001761void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1762 unsigned DestReg = getReg(B);
1763 MachineBasicBlock::iterator MI = BB->end();
Chris Lattner721d2d42004-03-08 01:18:36 +00001764 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1765
Chris Lattner7dee5da2004-03-08 01:58:35 +00001766 // Special case: op Reg, load [mem]
1767 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
1768 if (!B.swapOperands())
1769 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
1770
1771 unsigned Class = getClassB(B.getType());
1772 if (isa<LoadInst>(Op1) && Class < cFP &&
1773 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
1774
1775 static const unsigned OpcodeTab[][3] = {
1776 // Arithmetic operators
1777 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
1778 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
1779
1780 // Bitwise operators
1781 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
1782 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
1783 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
1784 };
1785
1786 assert(Class < cFP && "General code handles 64-bit integer types!");
1787 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1788
1789 unsigned BaseReg, Scale, IndexReg, Disp;
1790 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), BaseReg,
1791 Scale, IndexReg, Disp);
1792
1793 unsigned Op0r = getReg(Op0);
1794 addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r),
1795 BaseReg, Scale, IndexReg, Disp);
1796 return;
1797 }
1798
Chris Lattner721d2d42004-03-08 01:18:36 +00001799 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001800}
Chris Lattner3e130a22003-01-13 00:32:26 +00001801
Chris Lattnerb2acc512003-10-19 21:09:10 +00001802/// emitSimpleBinaryOperation - Implement simple binary operators for integral
1803/// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1804/// Or, 4 for Xor.
Chris Lattner68aad932002-11-02 20:13:22 +00001805///
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001806/// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1807/// and constant expression support.
Chris Lattnerb2acc512003-10-19 21:09:10 +00001808///
1809void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001810 MachineBasicBlock::iterator IP,
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001811 Value *Op0, Value *Op1,
Chris Lattnerb2acc512003-10-19 21:09:10 +00001812 unsigned OperatorClass, unsigned DestReg) {
Chris Lattnerb515f6d2003-05-08 20:49:25 +00001813 unsigned Class = getClassB(Op0->getType());
Chris Lattnerb2acc512003-10-19 21:09:10 +00001814
1815 // sub 0, X -> neg X
Chris Lattneredd5e492004-04-06 01:48:06 +00001816 if (OperatorClass == 1)
Chris Lattneraf703622004-02-02 18:56:30 +00001817 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
Chris Lattnerb2acc512003-10-19 21:09:10 +00001818 if (CI->isNullValue()) {
1819 unsigned op1Reg = getReg(Op1, MBB, IP);
Alkis Evlogimenosbee8a092004-04-02 18:11:32 +00001820 static unsigned const NEGTab[] = {
Chris Lattneredd5e492004-04-06 01:48:06 +00001821 X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
Alkis Evlogimenosbee8a092004-04-02 18:11:32 +00001822 };
1823 BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
Chris Lattneredd5e492004-04-06 01:48:06 +00001824
1825 if (Class == cLong) {
1826 // We just emitted: Dl = neg Sl
1827 // Now emit : T = addc Sh, 0
1828 // : Dh = neg T
1829 unsigned T = makeAnotherReg(Type::IntTy);
1830 BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
1831 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
1832 }
Alkis Evlogimenosbee8a092004-04-02 18:11:32 +00001833 return;
Chris Lattnerb2acc512003-10-19 21:09:10 +00001834 }
Chris Lattner9f8fd6d2004-02-02 19:31:38 +00001835 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1836 if (CFP->isExactlyValue(-0.0)) {
1837 // -0.0 - X === -X
1838 unsigned op1Reg = getReg(Op1, MBB, IP);
Chris Lattneree352852004-02-29 07:22:16 +00001839 BuildMI(*MBB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
Chris Lattner9f8fd6d2004-02-02 19:31:38 +00001840 return;
1841 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001842
Chris Lattnerb2acc512003-10-19 21:09:10 +00001843 // Special case: op Reg, <const>
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001844 if (isa<ConstantInt>(Op1)) {
Chris Lattner721d2d42004-03-08 01:18:36 +00001845 ConstantInt *Op1C = cast<ConstantInt>(Op1);
1846 unsigned Op0r = getReg(Op0, MBB, IP);
Chris Lattnerb2acc512003-10-19 21:09:10 +00001847
Chris Lattner721d2d42004-03-08 01:18:36 +00001848 // xor X, -1 -> not X
1849 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001850 static unsigned const NOTTab[] = {
1851 X86::NOT8r, X86::NOT16r, X86::NOT32r, 0, X86::NOT32r
1852 };
Chris Lattner721d2d42004-03-08 01:18:36 +00001853 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001854 if (Class == cLong) // Invert the top part too
1855 BuildMI(*MBB, IP, X86::NOT32r, 1, DestReg+1).addReg(Op0r+1);
Chris Lattner721d2d42004-03-08 01:18:36 +00001856 return;
1857 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001858
Chris Lattner721d2d42004-03-08 01:18:36 +00001859 // add X, -1 -> dec X
Chris Lattner06521672004-04-06 03:36:57 +00001860 if (OperatorClass == 0 && Op1C->isAllOnesValue() && Class != cLong) {
1861 // Note that we can't use dec for 64-bit decrements, because it does not
1862 // set the carry flag!
1863 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
Chris Lattner721d2d42004-03-08 01:18:36 +00001864 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1865 return;
1866 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001867
Chris Lattner721d2d42004-03-08 01:18:36 +00001868 // add X, 1 -> inc X
Chris Lattner06521672004-04-06 03:36:57 +00001869 if (OperatorClass == 0 && Op1C->equalsInt(1) && Class != cLong) {
1870 // Note that we can't use inc for 64-bit increments, because it does not
1871 // set the carry flag!
1872 static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
Alkis Evlogimenosbee8a092004-04-02 18:11:32 +00001873 BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
Chris Lattner721d2d42004-03-08 01:18:36 +00001874 return;
1875 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00001876
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001877 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00001878 // Arithmetic operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001879 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri }, // ADD
1880 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri }, // SUB
Chris Lattnerb2acc512003-10-19 21:09:10 +00001881
Chris Lattner721d2d42004-03-08 01:18:36 +00001882 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001883 { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri }, // AND
1884 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri }, // OR
1885 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri }, // XOR
Chris Lattner721d2d42004-03-08 01:18:36 +00001886 };
1887
Chris Lattner721d2d42004-03-08 01:18:36 +00001888 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner33f7fa32004-04-06 03:15:53 +00001889 unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
Chris Lattner721d2d42004-03-08 01:18:36 +00001890
Chris Lattner33f7fa32004-04-06 03:15:53 +00001891 if (Class != cLong) {
1892 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
1893 return;
1894 } else {
1895 // If this is a long value and the high or low bits have a special
1896 // property, emit some special cases.
1897 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001898
Chris Lattner33f7fa32004-04-06 03:15:53 +00001899 // If the constant is zero in the low 32-bits, just copy the low part
1900 // across and apply the normal 32-bit operation to the high parts. There
1901 // will be no carry or borrow into the top.
1902 if (Op1l == 0) {
1903 if (OperatorClass != 2) // All but and...
1904 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0r);
1905 else
1906 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
1907 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg+1)
1908 .addReg(Op0r+1).addImm(Op1h);
1909 return;
1910 }
1911
1912 // If this is a logical operation and the top 32-bits are zero, just
1913 // operate on the lower 32.
1914 if (Op1h == 0 && OperatorClass > 1) {
1915 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg)
1916 .addReg(Op0r).addImm(Op1l);
1917 if (OperatorClass != 2) // All but and
1918 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(Op0r+1);
1919 else
1920 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
1921 return;
1922 }
1923
1924 // TODO: We could handle lots of other special cases here, such as AND'ing
1925 // with 0xFFFFFFFF00000000 -> noop, etc.
1926
1927 // Otherwise, code generate the full operation with a constant.
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001928 static const unsigned TopTab[] = {
1929 X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
1930 };
Chris Lattner33f7fa32004-04-06 03:15:53 +00001931
1932 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001933 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
Chris Lattner33f7fa32004-04-06 03:15:53 +00001934 .addReg(Op0r+1).addImm(Op1h);
1935 return;
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001936 }
Chris Lattner721d2d42004-03-08 01:18:36 +00001937 }
1938
1939 // Finally, handle the general case now.
Chris Lattner7ba92302004-04-06 02:13:25 +00001940 static const unsigned OpcodeTab[][5] = {
Chris Lattner721d2d42004-03-08 01:18:36 +00001941 // Arithmetic operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001942 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, X86::FpADD, X86::ADD32rr },// ADD
1943 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::FpSUB, X86::SUB32rr },// SUB
Chris Lattner721d2d42004-03-08 01:18:36 +00001944
Chris Lattnerb2acc512003-10-19 21:09:10 +00001945 // Bitwise operators
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001946 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr }, // AND
1947 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr }, // OR
1948 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr }, // XOR
Chris Lattnerb2acc512003-10-19 21:09:10 +00001949 };
Chris Lattner721d2d42004-03-08 01:18:36 +00001950
Chris Lattnerb2acc512003-10-19 21:09:10 +00001951 unsigned Opcode = OpcodeTab[OperatorClass][Class];
Chris Lattner721d2d42004-03-08 01:18:36 +00001952 assert(Opcode && "Floating point arguments to logical inst?");
1953 unsigned Op0r = getReg(Op0, MBB, IP);
1954 unsigned Op1r = getReg(Op1, MBB, IP);
1955 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1956
Chris Lattnerab1d0e02004-04-06 02:11:49 +00001957 if (Class == cLong) { // Handle the upper 32 bits of long values...
Chris Lattner721d2d42004-03-08 01:18:36 +00001958 static const unsigned TopTab[] = {
1959 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
1960 };
1961 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
1962 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1963 }
Chris Lattnere2954c82002-11-02 20:04:26 +00001964}
1965
Chris Lattner3e130a22003-01-13 00:32:26 +00001966/// doMultiply - Emit appropriate instructions to multiply together the
1967/// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1968/// result should be given as DestTy.
1969///
Chris Lattnerbaa58a52004-02-23 03:10:10 +00001970void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
Chris Lattner3e130a22003-01-13 00:32:26 +00001971 unsigned DestReg, const Type *DestTy,
Chris Lattner8a307e82002-12-16 19:32:50 +00001972 unsigned op0Reg, unsigned op1Reg) {
Chris Lattner3e130a22003-01-13 00:32:26 +00001973 unsigned Class = getClass(DestTy);
Chris Lattner94af4142002-12-25 05:13:53 +00001974 switch (Class) {
1975 case cFP: // Floating point multiply
Chris Lattneree352852004-02-29 07:22:16 +00001976 BuildMI(*MBB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
Chris Lattner94af4142002-12-25 05:13:53 +00001977 return;
Chris Lattner0f1c4612003-06-21 17:16:58 +00001978 case cInt:
1979 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001980 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
Chris Lattner0f1c4612003-06-21 17:16:58 +00001981 .addReg(op0Reg).addReg(op1Reg);
1982 return;
1983 case cByte:
1984 // Must use the MUL instruction, which forces use of AL...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00001985 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
1986 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
1987 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
Chris Lattner0f1c4612003-06-21 17:16:58 +00001988 return;
Chris Lattner94af4142002-12-25 05:13:53 +00001989 default:
Chris Lattner3e130a22003-01-13 00:32:26 +00001990 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
Chris Lattner94af4142002-12-25 05:13:53 +00001991 }
Brian Gaeke20244b72002-12-12 15:33:40 +00001992}
1993
Chris Lattnerb2acc512003-10-19 21:09:10 +00001994// ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1995// returns zero when the input is not exactly a power of two.
1996static unsigned ExactLog2(unsigned Val) {
1997 if (Val == 0) return 0;
1998 unsigned Count = 0;
1999 while (Val != 1) {
2000 if (Val & 1) return 0;
2001 Val >>= 1;
2002 ++Count;
2003 }
2004 return Count+1;
2005}
2006
2007void ISel::doMultiplyConst(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002008 MachineBasicBlock::iterator IP,
Chris Lattnerb2acc512003-10-19 21:09:10 +00002009 unsigned DestReg, const Type *DestTy,
2010 unsigned op0Reg, unsigned ConstRHS) {
Chris Lattner6ab06d52004-04-06 04:55:43 +00002011 static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
2012 static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
2013
Chris Lattnerb2acc512003-10-19 21:09:10 +00002014 unsigned Class = getClass(DestTy);
2015
Chris Lattner6ab06d52004-04-06 04:55:43 +00002016 if (ConstRHS == 0) {
2017 BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
2018 return;
2019 } else if (ConstRHS == 1) {
2020 BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
2021 return;
2022 }
2023
Chris Lattnerb2acc512003-10-19 21:09:10 +00002024 // If the element size is exactly a power of 2, use a shift to get it.
2025 if (unsigned Shift = ExactLog2(ConstRHS)) {
2026 switch (Class) {
2027 default: assert(0 && "Unknown class for this function!");
2028 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002029 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002030 return;
2031 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002032 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002033 return;
2034 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002035 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002036 return;
2037 }
2038 }
Chris Lattnerc01d1232003-10-20 03:42:58 +00002039
2040 if (Class == cShort) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002041 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002042 return;
2043 } else if (Class == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002044 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
Chris Lattnerc01d1232003-10-20 03:42:58 +00002045 return;
2046 }
Chris Lattnerb2acc512003-10-19 21:09:10 +00002047
2048 // Most general case, emit a normal multiply...
Chris Lattnerb2acc512003-10-19 21:09:10 +00002049 unsigned TmpReg = makeAnotherReg(DestTy);
Chris Lattneree352852004-02-29 07:22:16 +00002050 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
Chris Lattnerb2acc512003-10-19 21:09:10 +00002051
2052 // Emit a MUL to multiply the register holding the index by
2053 // elementSize, putting the result in OffsetReg.
2054 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
2055}
2056
Chris Lattnerca9671d2002-11-02 20:28:58 +00002057/// visitMul - Multiplies are not simple binary operators because they must deal
2058/// with the EAX register explicitly.
2059///
2060void ISel::visitMul(BinaryOperator &I) {
Chris Lattner202a2d02002-12-13 13:07:42 +00002061 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattner3e130a22003-01-13 00:32:26 +00002062 unsigned DestReg = getReg(I);
2063
2064 // Simple scalar multiply?
Chris Lattner028adc42004-04-06 04:29:36 +00002065 if (getClass(I.getType()) != cLong) {
Chris Lattnerb2acc512003-10-19 21:09:10 +00002066 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
2067 unsigned Val = (unsigned)CI->getRawValue(); // Cannot be 64-bit constant
2068 MachineBasicBlock::iterator MBBI = BB->end();
2069 doMultiplyConst(BB, MBBI, DestReg, I.getType(), Op0Reg, Val);
2070 } else {
2071 unsigned Op1Reg = getReg(I.getOperand(1));
2072 MachineBasicBlock::iterator MBBI = BB->end();
2073 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
2074 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002075 } else {
2076 // Long value. We have to do things the hard way...
Chris Lattner028adc42004-04-06 04:29:36 +00002077 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
2078 unsigned CLow = CI->getRawValue();
2079 unsigned CHi = CI->getRawValue() >> 32;
Chris Lattner3e130a22003-01-13 00:32:26 +00002080
Chris Lattner6ab06d52004-04-06 04:55:43 +00002081 if (CLow == 0) {
2082 // If the low part of the constant is all zeros, things are simple.
2083 BuildMI(BB, X86::MOV32ri, 1, DestReg).addImm(0);
2084 doMultiplyConst(BB, BB->end(), DestReg+1, Type::UIntTy, Op0Reg, CHi);
2085 return;
2086 }
2087
Chris Lattner028adc42004-04-06 04:29:36 +00002088 // Multiply the two low parts... capturing carry into EDX
Chris Lattner6ab06d52004-04-06 04:55:43 +00002089 unsigned OverflowReg = 0;
2090 if (CLow == 1) {
2091 BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
2092 } else {
2093 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2094 OverflowReg = makeAnotherReg(Type::UIntTy);
2095 BuildMI(BB, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
2096 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2097 BuildMI(BB, X86::MUL32r, 1).addReg(Op1RegL); // AL*BL
Chris Lattner028adc42004-04-06 04:29:36 +00002098
Chris Lattner6ab06d52004-04-06 04:55:43 +00002099 BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2100 BuildMI(BB, X86::MOV32rr, 1,OverflowReg).addReg(X86::EDX);// AL*BL >> 32
2101 }
Chris Lattner028adc42004-04-06 04:29:36 +00002102
2103 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
Chris Lattner6ab06d52004-04-06 04:55:43 +00002104 doMultiplyConst(BB, BB->end(), AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
Chris Lattner028adc42004-04-06 04:29:36 +00002105
Chris Lattner6ab06d52004-04-06 04:55:43 +00002106 unsigned AHBLplusOverflowReg;
2107 if (OverflowReg) {
2108 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2109 BuildMI(BB, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2110 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2111 } else {
2112 AHBLplusOverflowReg = AHBLReg;
2113 }
Chris Lattner028adc42004-04-06 04:29:36 +00002114
Chris Lattner6ab06d52004-04-06 04:55:43 +00002115 if (CHi == 0) {
2116 BuildMI(BB, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
2117 } else {
Chris Lattner028adc42004-04-06 04:29:36 +00002118 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
Chris Lattner6ab06d52004-04-06 04:55:43 +00002119 doMultiplyConst(BB, BB->end(), ALBHReg, Type::UIntTy, Op0Reg, CHi);
Chris Lattner028adc42004-04-06 04:29:36 +00002120
2121 BuildMI(BB, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2122 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
Chris Lattner028adc42004-04-06 04:29:36 +00002123 }
2124 } else {
2125 unsigned Op1Reg = getReg(I.getOperand(1));
2126 // Multiply the two low parts... capturing carry into EDX
2127 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2128 BuildMI(BB, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
2129
2130 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2131 BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2132 BuildMI(BB, X86::MOV32rr, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2133
2134 MachineBasicBlock::iterator MBBI = BB->end();
2135 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2136 BuildMI(*BB, MBBI, X86::IMUL32rr, 2,
2137 AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2138
2139 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2140 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2141 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2142
2143 MBBI = BB->end();
2144 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2145 BuildMI(*BB, MBBI, X86::IMUL32rr, 2,
2146 ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2147
2148 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2149 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2150 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002151 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00002152}
Chris Lattnerca9671d2002-11-02 20:28:58 +00002153
Chris Lattner06925362002-11-17 21:56:38 +00002154
Chris Lattnerf01729e2002-11-02 20:54:46 +00002155/// visitDivRem - Handle division and remainder instructions... these
2156/// instruction both require the same instructions to be generated, they just
2157/// select the result from a different register. Note that both of these
2158/// instructions work differently for signed and unsigned operands.
2159///
2160void ISel::visitDivRem(BinaryOperator &I) {
Chris Lattnercadff442003-10-23 17:21:43 +00002161 unsigned Op0Reg = getReg(I.getOperand(0));
2162 unsigned Op1Reg = getReg(I.getOperand(1));
2163 unsigned ResultReg = getReg(I);
Chris Lattner94af4142002-12-25 05:13:53 +00002164
Chris Lattnercadff442003-10-23 17:21:43 +00002165 MachineBasicBlock::iterator IP = BB->end();
2166 emitDivRemOperation(BB, IP, Op0Reg, Op1Reg, I.getOpcode() == Instruction::Div,
2167 I.getType(), ResultReg);
2168}
2169
2170void ISel::emitDivRemOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002171 MachineBasicBlock::iterator IP,
Chris Lattnercadff442003-10-23 17:21:43 +00002172 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
2173 const Type *Ty, unsigned ResultReg) {
2174 unsigned Class = getClass(Ty);
Chris Lattner94af4142002-12-25 05:13:53 +00002175 switch (Class) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002176 case cFP: // Floating point divide
Chris Lattnercadff442003-10-23 17:21:43 +00002177 if (isDiv) {
Chris Lattneree352852004-02-29 07:22:16 +00002178 BuildMI(*BB, IP, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00002179 } else { // Floating point remainder...
Chris Lattner3e130a22003-01-13 00:32:26 +00002180 MachineInstr *TheCall =
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002181 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00002182 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002183 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2184 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002185 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
2186 }
Chris Lattner94af4142002-12-25 05:13:53 +00002187 return;
Chris Lattner3e130a22003-01-13 00:32:26 +00002188 case cLong: {
2189 static const char *FnName[] =
2190 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
2191
Chris Lattnercadff442003-10-23 17:21:43 +00002192 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
Chris Lattner3e130a22003-01-13 00:32:26 +00002193 MachineInstr *TheCall =
2194 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
2195
2196 std::vector<ValueRecord> Args;
Chris Lattnercadff442003-10-23 17:21:43 +00002197 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2198 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
Chris Lattner3e130a22003-01-13 00:32:26 +00002199 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
2200 return;
2201 }
2202 case cByte: case cShort: case cInt:
Misha Brukmancf00c4a2003-10-10 17:57:28 +00002203 break; // Small integrals, handled below...
Chris Lattner3e130a22003-01-13 00:32:26 +00002204 default: assert(0 && "Unknown class!");
Chris Lattner94af4142002-12-25 05:13:53 +00002205 }
Chris Lattnerf01729e2002-11-02 20:54:46 +00002206
2207 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002208 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
2209 static const unsigned SarOpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
2210 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
Chris Lattnerf01729e2002-11-02 20:54:46 +00002211 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
2212
2213 static const unsigned DivOpcode[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002214 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
2215 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
Chris Lattnerf01729e2002-11-02 20:54:46 +00002216 };
2217
Chris Lattnercadff442003-10-23 17:21:43 +00002218 bool isSigned = Ty->isSigned();
Chris Lattnerf01729e2002-11-02 20:54:46 +00002219 unsigned Reg = Regs[Class];
2220 unsigned ExtReg = ExtRegs[Class];
Chris Lattnerf01729e2002-11-02 20:54:46 +00002221
2222 // Put the first operand into one of the A registers...
Chris Lattneree352852004-02-29 07:22:16 +00002223 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002224
2225 if (isSigned) {
2226 // Emit a sign extension instruction...
Chris Lattnercadff442003-10-23 17:21:43 +00002227 unsigned ShiftResult = makeAnotherReg(Ty);
Chris Lattneree352852004-02-29 07:22:16 +00002228 BuildMI(*BB, IP, SarOpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
2229 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002230 } else {
Alkis Evlogimenosf998a7e2004-01-12 07:22:45 +00002231 // If unsigned, emit a zeroing instruction... (reg = 0)
Chris Lattneree352852004-02-29 07:22:16 +00002232 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
Chris Lattnerf01729e2002-11-02 20:54:46 +00002233 }
2234
Chris Lattner06925362002-11-17 21:56:38 +00002235 // Emit the appropriate divide or remainder instruction...
Chris Lattneree352852004-02-29 07:22:16 +00002236 BuildMI(*BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
Chris Lattner06925362002-11-17 21:56:38 +00002237
Chris Lattnerf01729e2002-11-02 20:54:46 +00002238 // Figure out which register we want to pick the result out of...
Chris Lattnercadff442003-10-23 17:21:43 +00002239 unsigned DestReg = isDiv ? Reg : ExtReg;
Chris Lattnerf01729e2002-11-02 20:54:46 +00002240
Chris Lattnerf01729e2002-11-02 20:54:46 +00002241 // Put the result into the destination register...
Chris Lattneree352852004-02-29 07:22:16 +00002242 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
Chris Lattnerca9671d2002-11-02 20:28:58 +00002243}
Chris Lattnere2954c82002-11-02 20:04:26 +00002244
Chris Lattner06925362002-11-17 21:56:38 +00002245
Brian Gaekea1719c92002-10-31 23:03:59 +00002246/// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2247/// for constant immediate shift values, and for constant immediate
2248/// shift values equal to 1. Even the general case is sort of special,
2249/// because the shift amount has to be in CL, not just any old register.
2250///
Chris Lattner3e130a22003-01-13 00:32:26 +00002251void ISel::visitShiftInst(ShiftInst &I) {
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002252 MachineBasicBlock::iterator IP = BB->end ();
2253 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2254 I.getOpcode () == Instruction::Shl, I.getType (),
2255 getReg (I));
2256}
2257
2258/// emitShiftOperation - Common code shared between visitShiftInst and
2259/// constant expression support.
2260void ISel::emitShiftOperation(MachineBasicBlock *MBB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002261 MachineBasicBlock::iterator IP,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002262 Value *Op, Value *ShiftAmount, bool isLeftShift,
2263 const Type *ResultTy, unsigned DestReg) {
2264 unsigned SrcReg = getReg (Op, MBB, IP);
2265 bool isSigned = ResultTy->isSigned ();
2266 unsigned Class = getClass (ResultTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00002267
2268 static const unsigned ConstantOperand[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002269 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 }, // SHR
2270 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 }, // SAR
2271 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SHL
2272 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00002273 };
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002274
Chris Lattner3e130a22003-01-13 00:32:26 +00002275 static const unsigned NonConstantOperand[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002276 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
2277 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
2278 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
2279 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
Chris Lattner3e130a22003-01-13 00:32:26 +00002280 };
Chris Lattner796df732002-11-02 00:44:25 +00002281
Chris Lattner3e130a22003-01-13 00:32:26 +00002282 // Longs, as usual, are handled specially...
2283 if (Class == cLong) {
2284 // If we have a constant shift, we can generate much more efficient code
2285 // than otherwise...
2286 //
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002287 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002288 unsigned Amount = CUI->getValue();
2289 if (Amount < 32) {
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002290 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2291 if (isLeftShift) {
Chris Lattneree352852004-02-29 07:22:16 +00002292 BuildMI(*MBB, IP, Opc[3], 3,
2293 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
2294 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002295 } else {
Chris Lattneree352852004-02-29 07:22:16 +00002296 BuildMI(*MBB, IP, Opc[3], 3,
2297 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
2298 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002299 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002300 } else { // Shifting more than 32 bits
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002301 Amount -= 32;
2302 if (isLeftShift) {
Chris Lattner722070e2004-04-06 03:42:38 +00002303 if (Amount != 0) {
2304 BuildMI(*MBB, IP, X86::SHL32ri, 2,
2305 DestReg + 1).addReg(SrcReg).addImm(Amount);
2306 } else {
2307 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
2308 }
2309 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002310 } else {
Chris Lattner722070e2004-04-06 03:42:38 +00002311 if (Amount != 0) {
2312 BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
2313 DestReg).addReg(SrcReg+1).addImm(Amount);
2314 } else {
2315 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
2316 }
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002317 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002318 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002319 }
2320 } else {
Chris Lattner9171ef52003-06-01 01:56:54 +00002321 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2322
2323 if (!isLeftShift && isSigned) {
2324 // If this is a SHR of a Long, then we need to do funny sign extension
2325 // stuff. TmpReg gets the value to use as the high-part if we are
2326 // shifting more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002327 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
Chris Lattner9171ef52003-06-01 01:56:54 +00002328 } else {
2329 // Other shifts use a fixed zero value if the shift is more than 32
2330 // bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002331 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
Chris Lattner9171ef52003-06-01 01:56:54 +00002332 }
2333
2334 // Initialize CL with the shift amount...
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002335 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002336 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002337
2338 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2339 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2340 if (isLeftShift) {
2341 // TmpReg2 = shld inHi, inLo
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002342 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
Chris Lattneree352852004-02-29 07:22:16 +00002343 .addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002344 // TmpReg3 = shl inLo, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002345 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002346
2347 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002348 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00002349
2350 // DestHi = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002351 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002352 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
2353 // DestLo = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002354 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002355 DestReg).addReg(TmpReg3).addReg(TmpReg);
Chris Lattner9171ef52003-06-01 01:56:54 +00002356 } else {
2357 // TmpReg2 = shrd inLo, inHi
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002358 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
Chris Lattneree352852004-02-29 07:22:16 +00002359 .addReg(SrcReg+1);
Chris Lattner9171ef52003-06-01 01:56:54 +00002360 // TmpReg3 = s[ah]r inHi, CL
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002361 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
Chris Lattner9171ef52003-06-01 01:56:54 +00002362 .addReg(SrcReg+1);
2363
2364 // Set the flags to indicate whether the shift was by more than 32 bits.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002365 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
Chris Lattner9171ef52003-06-01 01:56:54 +00002366
2367 // DestLo = (>32) ? TmpReg3 : TmpReg2;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002368 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002369 DestReg).addReg(TmpReg2).addReg(TmpReg3);
2370
2371 // DestHi = (>32) ? TmpReg : TmpReg3;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002372 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
Chris Lattner9171ef52003-06-01 01:56:54 +00002373 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
2374 }
Brian Gaekea1719c92002-10-31 23:03:59 +00002375 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002376 return;
2377 }
Chris Lattnere9913f22002-11-02 01:41:55 +00002378
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002379 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00002380 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2381 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002382
Chris Lattner3e130a22003-01-13 00:32:26 +00002383 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00002384 BuildMI(*MBB, IP, Opc[Class], 2,
2385 DestReg).addReg(SrcReg).addImm(CUI->getValue());
Chris Lattner3e130a22003-01-13 00:32:26 +00002386 } else { // The shift amount is non-constant.
Brian Gaekedfcc9cf2003-11-22 06:49:41 +00002387 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002388 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002389
Chris Lattner3e130a22003-01-13 00:32:26 +00002390 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
Chris Lattneree352852004-02-29 07:22:16 +00002391 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002392 }
2393}
Chris Lattnerb1761fc2002-11-02 01:15:18 +00002394
Chris Lattner3e130a22003-01-13 00:32:26 +00002395
Chris Lattner721d2d42004-03-08 01:18:36 +00002396void ISel::getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
2397 unsigned &IndexReg, unsigned &Disp) {
2398 BaseReg = 0; Scale = 1; IndexReg = 0; Disp = 0;
2399 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
2400 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
2401 BaseReg, Scale, IndexReg, Disp))
2402 return;
2403 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2404 if (CE->getOpcode() == Instruction::GetElementPtr)
2405 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
2406 BaseReg, Scale, IndexReg, Disp))
2407 return;
2408 }
2409
2410 // If it's not foldable, reset addr mode.
2411 BaseReg = getReg(Addr);
2412 Scale = 1; IndexReg = 0; Disp = 0;
2413}
2414
2415
Chris Lattner6fc3c522002-11-17 21:11:55 +00002416/// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
Chris Lattnere8f0d922002-12-24 00:03:11 +00002417/// instruction. The load and store instructions are the only place where we
2418/// need to worry about the memory layout of the target machine.
Chris Lattner6fc3c522002-11-17 21:11:55 +00002419///
2420void ISel::visitLoadInst(LoadInst &I) {
Chris Lattner7dee5da2004-03-08 01:58:35 +00002421 // Check to see if this load instruction is going to be folded into a binary
2422 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
2423 // pattern matching instruction selector be nice?
2424 if (I.hasOneUse() && getClassB(I.getType()) < cFP) {
2425 Instruction *User = cast<Instruction>(I.use_back());
2426 switch (User->getOpcode()) {
2427 default: User = 0; break;
2428 case Instruction::Add:
2429 case Instruction::Sub:
2430 case Instruction::And:
2431 case Instruction::Or:
2432 case Instruction::Xor:
2433 break;
2434 }
2435
2436 if (User) {
2437 // Okay, we found a user. If the load is the first operand and there is
2438 // no second operand load, reverse the operand ordering. Note that this
2439 // can fail for a subtract (ie, no change will be made).
2440 if (!isa<LoadInst>(User->getOperand(1)))
2441 cast<BinaryOperator>(User)->swapOperands();
2442
2443 // Okay, now that everything is set up, if this load is used by the second
2444 // operand, and if there are no instructions that invalidate the load
2445 // before the binary operator, eliminate the load.
2446 if (User->getOperand(1) == &I &&
2447 isSafeToFoldLoadIntoInstruction(I, *User))
2448 return; // Eliminate the load!
2449 }
2450 }
2451
Chris Lattner94af4142002-12-25 05:13:53 +00002452 unsigned DestReg = getReg(I);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002453 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
Chris Lattner721d2d42004-03-08 01:18:36 +00002454 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
Chris Lattnere8f0d922002-12-24 00:03:11 +00002455
Brian Gaekebfedb912003-07-17 21:30:06 +00002456 unsigned Class = getClassB(I.getType());
Chris Lattner6ac1d712003-10-20 04:48:06 +00002457 if (Class == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002458 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002459 BaseReg, Scale, IndexReg, Disp);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002460 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002461 BaseReg, Scale, IndexReg, Disp+4);
Chris Lattner94af4142002-12-25 05:13:53 +00002462 return;
2463 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00002464
Chris Lattner6ac1d712003-10-20 04:48:06 +00002465 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002466 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m
Chris Lattner3e130a22003-01-13 00:32:26 +00002467 };
Chris Lattner6ac1d712003-10-20 04:48:06 +00002468 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002469 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
Chris Lattnerb6bac512004-02-25 06:13:04 +00002470 addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
2471 BaseReg, Scale, IndexReg, Disp);
Chris Lattner3e130a22003-01-13 00:32:26 +00002472}
2473
Chris Lattner6fc3c522002-11-17 21:11:55 +00002474/// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
2475/// instruction.
2476///
2477void ISel::visitStoreInst(StoreInst &I) {
Chris Lattner721d2d42004-03-08 01:18:36 +00002478 unsigned BaseReg, Scale, IndexReg, Disp;
2479 getAddressingMode(I.getOperand(1), BaseReg, Scale, IndexReg, Disp);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002480
Chris Lattner6c09db22003-10-20 04:11:23 +00002481 const Type *ValTy = I.getOperand(0)->getType();
2482 unsigned Class = getClassB(ValTy);
Chris Lattner6ac1d712003-10-20 04:48:06 +00002483
Chris Lattner5a830962004-02-25 02:56:58 +00002484 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
2485 uint64_t Val = CI->getRawValue();
2486 if (Class == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002487 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002488 BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002489 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002490 BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
Chris Lattner5a830962004-02-25 02:56:58 +00002491 } else {
2492 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002493 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
Chris Lattner5a830962004-02-25 02:56:58 +00002494 };
2495 unsigned Opcode = Opcodes[Class];
Chris Lattnerb6bac512004-02-25 06:13:04 +00002496 addFullAddress(BuildMI(BB, Opcode, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002497 BaseReg, Scale, IndexReg, Disp).addImm(Val);
Chris Lattner5a830962004-02-25 02:56:58 +00002498 }
2499 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002500 addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002501 BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
Chris Lattner5a830962004-02-25 02:56:58 +00002502 } else {
2503 if (Class == cLong) {
2504 unsigned ValReg = getReg(I.getOperand(0));
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002505 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002506 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002507 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002508 BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
Chris Lattner5a830962004-02-25 02:56:58 +00002509 } else {
2510 unsigned ValReg = getReg(I.getOperand(0));
2511 static const unsigned Opcodes[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002512 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
Chris Lattner5a830962004-02-25 02:56:58 +00002513 };
2514 unsigned Opcode = Opcodes[Class];
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002515 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
Chris Lattnerb6bac512004-02-25 06:13:04 +00002516 addFullAddress(BuildMI(BB, Opcode, 1+4),
2517 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
Chris Lattner5a830962004-02-25 02:56:58 +00002518 }
Chris Lattner94af4142002-12-25 05:13:53 +00002519 }
Chris Lattner6fc3c522002-11-17 21:11:55 +00002520}
2521
2522
Misha Brukman538607f2004-03-01 23:53:11 +00002523/// visitCastInst - Here we have various kinds of copying with or without sign
2524/// extension going on.
2525///
Chris Lattner3e130a22003-01-13 00:32:26 +00002526void ISel::visitCastInst(CastInst &CI) {
Chris Lattnerf5854472003-06-21 16:01:24 +00002527 Value *Op = CI.getOperand(0);
2528 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2529 // of the case are GEP instructions, then the cast does not need to be
2530 // generated explicitly, it will be folded into the GEP.
2531 if (CI.getType() == Type::LongTy &&
2532 (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
2533 bool AllUsesAreGEPs = true;
2534 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2535 if (!isa<GetElementPtrInst>(*I)) {
2536 AllUsesAreGEPs = false;
2537 break;
2538 }
2539
2540 // No need to codegen this cast if all users are getelementptr instrs...
2541 if (AllUsesAreGEPs) return;
2542 }
2543
Chris Lattner548f61d2003-04-23 17:22:12 +00002544 unsigned DestReg = getReg(CI);
2545 MachineBasicBlock::iterator MI = BB->end();
Chris Lattnerf5854472003-06-21 16:01:24 +00002546 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
Chris Lattner548f61d2003-04-23 17:22:12 +00002547}
2548
Misha Brukman538607f2004-03-01 23:53:11 +00002549/// emitCastOperation - Common code shared between visitCastInst and constant
2550/// expression cast support.
2551///
Chris Lattner548f61d2003-04-23 17:22:12 +00002552void ISel::emitCastOperation(MachineBasicBlock *BB,
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002553 MachineBasicBlock::iterator IP,
Chris Lattner548f61d2003-04-23 17:22:12 +00002554 Value *Src, const Type *DestTy,
2555 unsigned DestReg) {
Chris Lattner3907d112003-04-23 17:57:48 +00002556 unsigned SrcReg = getReg(Src, BB, IP);
Chris Lattner3e130a22003-01-13 00:32:26 +00002557 const Type *SrcTy = Src->getType();
2558 unsigned SrcClass = getClassB(SrcTy);
Chris Lattner3e130a22003-01-13 00:32:26 +00002559 unsigned DestClass = getClassB(DestTy);
Chris Lattner7d255892002-12-13 11:31:59 +00002560
Chris Lattner3e130a22003-01-13 00:32:26 +00002561 // Implement casts to bool by using compare on the operand followed by set if
2562 // not zero on the result.
2563 if (DestTy == Type::BoolTy) {
Chris Lattner20772542003-06-01 03:38:24 +00002564 switch (SrcClass) {
2565 case cByte:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002566 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002567 break;
2568 case cShort:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002569 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002570 break;
2571 case cInt:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002572 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
Chris Lattner20772542003-06-01 03:38:24 +00002573 break;
2574 case cLong: {
2575 unsigned TmpReg = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002576 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
Chris Lattner20772542003-06-01 03:38:24 +00002577 break;
2578 }
2579 case cFP:
Chris Lattneree352852004-02-29 07:22:16 +00002580 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002581 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
Chris Lattneree352852004-02-29 07:22:16 +00002582 BuildMI(*BB, IP, X86::SAHF, 1);
Chris Lattner311ca2e2004-02-23 03:21:41 +00002583 break;
Chris Lattner20772542003-06-01 03:38:24 +00002584 }
2585
2586 // If the zero flag is not set, then the value is true, set the byte to
2587 // true.
Chris Lattneree352852004-02-29 07:22:16 +00002588 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
Chris Lattner94af4142002-12-25 05:13:53 +00002589 return;
2590 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002591
2592 static const unsigned RegRegMove[] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002593 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
Chris Lattner3e130a22003-01-13 00:32:26 +00002594 };
2595
2596 // Implement casts between values of the same type class (as determined by
2597 // getClass) by using a register-to-register move.
2598 if (SrcClass == DestClass) {
2599 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
Chris Lattneree352852004-02-29 07:22:16 +00002600 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002601 } else if (SrcClass == cFP) {
2602 if (SrcTy == Type::FloatTy) { // double -> float
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002603 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
Chris Lattneree352852004-02-29 07:22:16 +00002604 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002605 } else { // float -> double
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002606 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2607 "Unknown cFP member!");
2608 // Truncate from double to float by storing to memory as short, then
2609 // reading it back.
2610 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
Chris Lattner3e130a22003-01-13 00:32:26 +00002611 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002612 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
2613 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002614 }
2615 } else if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002616 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2617 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00002618 } else {
Chris Lattnerc53544a2003-05-12 20:16:58 +00002619 assert(0 && "Cannot handle this type of cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00002620 abort();
Brian Gaeked474e9c2002-12-06 10:49:33 +00002621 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002622 return;
2623 }
2624
2625 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2626 // or zero extension, depending on whether the source type was signed.
2627 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2628 SrcClass < DestClass) {
2629 bool isLong = DestClass == cLong;
2630 if (isLong) DestClass = cInt;
2631
2632 static const unsigned Opc[][4] = {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002633 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
2634 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
Chris Lattner3e130a22003-01-13 00:32:26 +00002635 };
2636
2637 bool isUnsigned = SrcTy->isUnsigned();
Chris Lattneree352852004-02-29 07:22:16 +00002638 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
Chris Lattner548f61d2003-04-23 17:22:12 +00002639 DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002640
2641 if (isLong) { // Handle upper 32 bits as appropriate...
2642 if (isUnsigned) // Zero out top bits...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002643 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
Chris Lattner3e130a22003-01-13 00:32:26 +00002644 else // Sign extend bottom half...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002645 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
Brian Gaeked474e9c2002-12-06 10:49:33 +00002646 }
Chris Lattner3e130a22003-01-13 00:32:26 +00002647 return;
2648 }
2649
2650 // Special case long -> int ...
2651 if (SrcClass == cLong && DestClass == cInt) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002652 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002653 return;
2654 }
2655
2656 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
2657 // move out of AX or AL.
2658 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2659 && SrcClass > DestClass) {
2660 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
Chris Lattneree352852004-02-29 07:22:16 +00002661 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
2662 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
Chris Lattner3e130a22003-01-13 00:32:26 +00002663 return;
2664 }
2665
2666 // Handle casts from integer to floating point now...
2667 if (DestClass == cFP) {
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002668 // Promote the integer to a type supported by FLD. We do this because there
2669 // are no unsigned FLD instructions, so we must promote an unsigned value to
2670 // a larger signed value, then use FLD on the larger value.
2671 //
2672 const Type *PromoteType = 0;
Chris Lattner85aa7092004-04-10 18:32:01 +00002673 unsigned PromoteOpcode = 0;
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002674 unsigned RealDestReg = DestReg;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002675 switch (SrcTy->getPrimitiveID()) {
2676 case Type::BoolTyID:
2677 case Type::SByteTyID:
2678 // We don't have the facilities for directly loading byte sized data from
2679 // memory (even signed). Promote it to 16 bits.
2680 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002681 PromoteOpcode = X86::MOVSX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002682 break;
2683 case Type::UByteTyID:
2684 PromoteType = Type::ShortTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002685 PromoteOpcode = X86::MOVZX16rr8;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002686 break;
2687 case Type::UShortTyID:
2688 PromoteType = Type::IntTy;
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002689 PromoteOpcode = X86::MOVZX32rr16;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002690 break;
2691 case Type::UIntTyID: {
2692 // Make a 64 bit temporary... and zero out the top of it...
2693 unsigned TmpReg = makeAnotherReg(Type::LongTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002694 BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
2695 BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002696 SrcTy = Type::LongTy;
2697 SrcClass = cLong;
2698 SrcReg = TmpReg;
2699 break;
2700 }
2701 case Type::ULongTyID:
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002702 // Don't fild into the read destination.
2703 DestReg = makeAnotherReg(Type::DoubleTy);
2704 break;
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002705 default: // No promotion needed...
2706 break;
2707 }
2708
2709 if (PromoteType) {
2710 unsigned TmpReg = makeAnotherReg(PromoteType);
Chris Lattner7b92de1e2004-04-06 19:29:36 +00002711 BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
Chris Lattner4d5a50a2003-05-12 20:36:13 +00002712 SrcTy = PromoteType;
2713 SrcClass = getClass(PromoteType);
Chris Lattner3e130a22003-01-13 00:32:26 +00002714 SrcReg = TmpReg;
2715 }
2716
2717 // Spill the integer to memory and reload it from there...
Chris Lattnerb6bac512004-02-25 06:13:04 +00002718 int FrameIdx =
2719 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
Chris Lattner3e130a22003-01-13 00:32:26 +00002720
2721 if (SrcClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002722 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002723 FrameIdx).addReg(SrcReg);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002724 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002725 FrameIdx, 4).addReg(SrcReg+1);
Chris Lattner3e130a22003-01-13 00:32:26 +00002726 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002727 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
Chris Lattneree352852004-02-29 07:22:16 +00002728 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
2729 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002730 }
2731
2732 static const unsigned Op2[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002733 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
Chris Lattneree352852004-02-29 07:22:16 +00002734 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002735
2736 // We need special handling for unsigned 64-bit integer sources. If the
2737 // input number has the "sign bit" set, then we loaded it incorrectly as a
2738 // negative 64-bit number. In this case, add an offset value.
2739 if (SrcTy == Type::ULongTy) {
2740 // Emit a test instruction to see if the dynamic input value was signed.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002741 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002742
Chris Lattnerb6bac512004-02-25 06:13:04 +00002743 // If the sign bit is set, get a pointer to an offset, otherwise get a
2744 // pointer to a zero.
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002745 MachineConstantPool *CP = F->getConstantPool();
2746 unsigned Zero = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002747 Constant *Null = Constant::getNullValue(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002748 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002749 CP->getConstantPoolIndex(Null));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002750 unsigned Offset = makeAnotherReg(Type::IntTy);
Chris Lattnerb6bac512004-02-25 06:13:04 +00002751 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
2752
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002753 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
Chris Lattnerb6bac512004-02-25 06:13:04 +00002754 CP->getConstantPoolIndex(OffsetCst));
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002755 unsigned Addr = makeAnotherReg(Type::IntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002756 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002757
2758 // Load the constant for an add. FIXME: this could make an 'fadd' that
2759 // reads directly from memory, but we don't support these yet.
2760 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002761 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002762
Chris Lattneree352852004-02-29 07:22:16 +00002763 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
2764 .addReg(ConstReg).addReg(DestReg);
Chris Lattnerbaa58a52004-02-23 03:10:10 +00002765 }
2766
Chris Lattner3e130a22003-01-13 00:32:26 +00002767 return;
2768 }
2769
2770 // Handle casts from floating point to integer now...
2771 if (SrcClass == cFP) {
2772 // Change the floating point control register to use "round towards zero"
2773 // mode when truncating to an integer value.
2774 //
2775 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002776 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002777
2778 // Load the old value of the high byte of the control word...
2779 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002780 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
Chris Lattneree352852004-02-29 07:22:16 +00002781 CWFrameIdx, 1);
Chris Lattner3e130a22003-01-13 00:32:26 +00002782
2783 // Set the high part to be round to zero...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002784 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
Chris Lattneree352852004-02-29 07:22:16 +00002785 CWFrameIdx, 1).addImm(12);
Chris Lattner3e130a22003-01-13 00:32:26 +00002786
2787 // Reload the modified control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002788 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002789
2790 // Restore the memory image of control word to original value
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002791 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
Misha Brukmanc8893fc2003-10-23 16:22:08 +00002792 CWFrameIdx, 1).addReg(HighPartOfCW);
Chris Lattner3e130a22003-01-13 00:32:26 +00002793
2794 // We don't have the facilities for directly storing byte sized data to
2795 // memory. Promote it to 16 bits. We also must promote unsigned values to
2796 // larger classes because we only have signed FP stores.
2797 unsigned StoreClass = DestClass;
2798 const Type *StoreTy = DestTy;
2799 if (StoreClass == cByte || DestTy->isUnsigned())
2800 switch (StoreClass) {
2801 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
2802 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
2803 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
Brian Gaeked4615052003-07-18 20:23:43 +00002804 // The following treatment of cLong may not be perfectly right,
2805 // but it survives chains of casts of the form
2806 // double->ulong->double.
2807 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
Chris Lattner3e130a22003-01-13 00:32:26 +00002808 default: assert(0 && "Unknown store class!");
2809 }
2810
2811 // Spill the integer to memory and reload it from there...
2812 int FrameIdx =
2813 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
2814
2815 static const unsigned Op1[] =
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002816 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
Chris Lattneree352852004-02-29 07:22:16 +00002817 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
2818 FrameIdx).addReg(SrcReg);
Chris Lattner3e130a22003-01-13 00:32:26 +00002819
2820 if (DestClass == cLong) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002821 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
2822 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
Chris Lattneree352852004-02-29 07:22:16 +00002823 FrameIdx, 4);
Chris Lattner3e130a22003-01-13 00:32:26 +00002824 } else {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002825 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
Chris Lattneree352852004-02-29 07:22:16 +00002826 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002827 }
2828
2829 // Reload the original control word now...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002830 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
Chris Lattner3e130a22003-01-13 00:32:26 +00002831 return;
2832 }
2833
Brian Gaeked474e9c2002-12-06 10:49:33 +00002834 // Anything we haven't handled already, we can't (yet) handle at all.
Chris Lattnerc53544a2003-05-12 20:16:58 +00002835 assert(0 && "Unhandled cast instruction!");
Chris Lattner548f61d2003-04-23 17:22:12 +00002836 abort();
Brian Gaekefa8d5712002-11-22 11:07:01 +00002837}
Brian Gaekea1719c92002-10-31 23:03:59 +00002838
Chris Lattner73815062003-10-18 05:56:40 +00002839/// visitVANextInst - Implement the va_next instruction...
Chris Lattnereca195e2003-05-08 19:44:13 +00002840///
Chris Lattner73815062003-10-18 05:56:40 +00002841void ISel::visitVANextInst(VANextInst &I) {
2842 unsigned VAList = getReg(I.getOperand(0));
Chris Lattnereca195e2003-05-08 19:44:13 +00002843 unsigned DestReg = getReg(I);
2844
Chris Lattnereca195e2003-05-08 19:44:13 +00002845 unsigned Size;
Chris Lattner73815062003-10-18 05:56:40 +00002846 switch (I.getArgType()->getPrimitiveID()) {
Chris Lattnereca195e2003-05-08 19:44:13 +00002847 default:
2848 std::cerr << I;
Chris Lattner73815062003-10-18 05:56:40 +00002849 assert(0 && "Error: bad type for va_next instruction!");
Chris Lattnereca195e2003-05-08 19:44:13 +00002850 return;
2851 case Type::PointerTyID:
2852 case Type::UIntTyID:
2853 case Type::IntTyID:
2854 Size = 4;
Chris Lattnereca195e2003-05-08 19:44:13 +00002855 break;
2856 case Type::ULongTyID:
2857 case Type::LongTyID:
Chris Lattnereca195e2003-05-08 19:44:13 +00002858 case Type::DoubleTyID:
2859 Size = 8;
Chris Lattnereca195e2003-05-08 19:44:13 +00002860 break;
2861 }
2862
2863 // Increment the VAList pointer...
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002864 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
Chris Lattner73815062003-10-18 05:56:40 +00002865}
Chris Lattnereca195e2003-05-08 19:44:13 +00002866
Chris Lattner73815062003-10-18 05:56:40 +00002867void ISel::visitVAArgInst(VAArgInst &I) {
2868 unsigned VAList = getReg(I.getOperand(0));
2869 unsigned DestReg = getReg(I);
2870
2871 switch (I.getType()->getPrimitiveID()) {
2872 default:
2873 std::cerr << I;
2874 assert(0 && "Error: bad type for va_next instruction!");
2875 return;
2876 case Type::PointerTyID:
2877 case Type::UIntTyID:
2878 case Type::IntTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002879 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00002880 break;
2881 case Type::ULongTyID:
2882 case Type::LongTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002883 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2884 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
Chris Lattner73815062003-10-18 05:56:40 +00002885 break;
2886 case Type::DoubleTyID:
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00002887 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
Chris Lattner73815062003-10-18 05:56:40 +00002888 break;
2889 }
Chris Lattnereca195e2003-05-08 19:44:13 +00002890}
2891
Misha Brukman538607f2004-03-01 23:53:11 +00002892/// visitGetElementPtrInst - instruction-select GEP instructions
2893///
Chris Lattner3e130a22003-01-13 00:32:26 +00002894void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb6bac512004-02-25 06:13:04 +00002895 // If this GEP instruction will be folded into all of its users, we don't need
2896 // to explicitly calculate it!
2897 unsigned A, B, C, D;
2898 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
2899 // Check all of the users of the instruction to see if they are loads and
2900 // stores.
2901 bool AllWillFold = true;
2902 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
2903 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
2904 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
2905 cast<Instruction>(*UI)->getOperand(0) == &I) {
2906 AllWillFold = false;
2907 break;
2908 }
2909
2910 // If the instruction is foldable, and will be folded into all users, don't
2911 // emit it!
2912 if (AllWillFold) return;
2913 }
2914
Chris Lattner3e130a22003-01-13 00:32:26 +00002915 unsigned outputReg = getReg(I);
Chris Lattner827832c2004-02-22 17:05:38 +00002916 emitGEPOperation(BB, BB->end(), I.getOperand(0),
Brian Gaeke68b1edc2002-12-16 04:23:29 +00002917 I.op_begin()+1, I.op_end(), outputReg);
Chris Lattnerc0812d82002-12-13 06:56:29 +00002918}
2919
Chris Lattner985fe3d2004-02-25 03:45:50 +00002920/// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
2921/// GEPTypes (the derived types being stepped through at each level). On return
2922/// from this function, if some indexes of the instruction are representable as
2923/// an X86 lea instruction, the machine operands are put into the Ops
2924/// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
2925/// lists. Otherwise, GEPOps.size() is returned. If this returns a an
2926/// addressing mode that only partially consumes the input, the BaseReg input of
2927/// the addressing mode must be left free.
2928///
2929/// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
2930///
Chris Lattnerb6bac512004-02-25 06:13:04 +00002931void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2932 std::vector<Value*> &GEPOps,
2933 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
2934 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2935 const TargetData &TD = TM.getTargetData();
2936
Chris Lattner985fe3d2004-02-25 03:45:50 +00002937 // Clear out the state we are working with...
Chris Lattnerb6bac512004-02-25 06:13:04 +00002938 BaseReg = 0; // No base register
2939 Scale = 1; // Unit scale
2940 IndexReg = 0; // No index register
2941 Disp = 0; // No displacement
2942
Chris Lattner985fe3d2004-02-25 03:45:50 +00002943 // While there are GEP indexes that can be folded into the current address,
2944 // keep processing them.
2945 while (!GEPTypes.empty()) {
2946 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2947 // It's a struct access. CUI is the index into the structure,
2948 // which names the field. This index must have unsigned type.
2949 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2950
2951 // Use the TargetData structure to pick out what the layout of the
2952 // structure is in memory. Since the structure index must be constant, we
2953 // can get its value and use it to find the right byte offset from the
2954 // StructLayout class's list of structure member offsets.
Chris Lattnerb6bac512004-02-25 06:13:04 +00002955 Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
Chris Lattner985fe3d2004-02-25 03:45:50 +00002956 GEPOps.pop_back(); // Consume a GEP operand
2957 GEPTypes.pop_back();
2958 } else {
2959 // It's an array or pointer access: [ArraySize x ElementType].
2960 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2961 Value *idx = GEPOps.back();
2962
2963 // idx is the index into the array. Unlike with structure
2964 // indices, we may not know its actual value at code-generation
2965 // time.
Chris Lattner985fe3d2004-02-25 03:45:50 +00002966
2967 // If idx is a constant, fold it into the offset.
Chris Lattner5f2c7b12004-02-25 07:00:55 +00002968 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
Chris Lattner985fe3d2004-02-25 03:45:50 +00002969 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00002970 Disp += TypeSize*CSI->getValue();
Chris Lattner28977af2004-04-05 01:30:19 +00002971 } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
2972 Disp += TypeSize*CUI->getValue();
Chris Lattner985fe3d2004-02-25 03:45:50 +00002973 } else {
Chris Lattner5f2c7b12004-02-25 07:00:55 +00002974 // If the index reg is already taken, we can't handle this index.
2975 if (IndexReg) return;
2976
2977 // If this is a size that we can handle, then add the index as
2978 switch (TypeSize) {
2979 case 1: case 2: case 4: case 8:
2980 // These are all acceptable scales on X86.
2981 Scale = TypeSize;
2982 break;
2983 default:
2984 // Otherwise, we can't handle this scale
2985 return;
2986 }
2987
2988 if (CastInst *CI = dyn_cast<CastInst>(idx))
2989 if (CI->getOperand(0)->getType() == Type::IntTy ||
2990 CI->getOperand(0)->getType() == Type::UIntTy)
2991 idx = CI->getOperand(0);
2992
2993 IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
Chris Lattner985fe3d2004-02-25 03:45:50 +00002994 }
2995
2996 GEPOps.pop_back(); // Consume a GEP operand
2997 GEPTypes.pop_back();
2998 }
2999 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003000
3001 // GEPTypes is empty, which means we have a single operand left. See if we
3002 // can set it as the base register.
3003 //
3004 // FIXME: When addressing modes are more powerful/correct, we could load
3005 // global addresses directly as 32-bit immediates.
3006 assert(BaseReg == 0);
Chris Lattner5f2c7b12004-02-25 07:00:55 +00003007 BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
Chris Lattnerb6bac512004-02-25 06:13:04 +00003008 GEPOps.pop_back(); // Consume the last GEP operand
Chris Lattner985fe3d2004-02-25 03:45:50 +00003009}
3010
3011
Chris Lattnerb6bac512004-02-25 06:13:04 +00003012/// isGEPFoldable - Return true if the specified GEP can be completely
3013/// folded into the addressing mode of a load/store or lea instruction.
3014bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
3015 Value *Src, User::op_iterator IdxBegin,
3016 User::op_iterator IdxEnd, unsigned &BaseReg,
3017 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
Chris Lattner7ca04092004-02-22 17:35:42 +00003018 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
3019 Src = CPR->getValue();
3020
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003021 std::vector<Value*> GEPOps;
3022 GEPOps.resize(IdxEnd-IdxBegin+1);
3023 GEPOps[0] = Src;
3024 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3025
3026 std::vector<const Type*> GEPTypes;
3027 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3028 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3029
Chris Lattnerb6bac512004-02-25 06:13:04 +00003030 MachineBasicBlock::iterator IP;
3031 if (MBB) IP = MBB->end();
3032 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
3033
3034 // We can fold it away iff the getGEPIndex call eliminated all operands.
3035 return GEPOps.empty();
3036}
3037
3038void ISel::emitGEPOperation(MachineBasicBlock *MBB,
3039 MachineBasicBlock::iterator IP,
3040 Value *Src, User::op_iterator IdxBegin,
3041 User::op_iterator IdxEnd, unsigned TargetReg) {
3042 const TargetData &TD = TM.getTargetData();
3043 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
3044 Src = CPR->getValue();
3045
3046 std::vector<Value*> GEPOps;
3047 GEPOps.resize(IdxEnd-IdxBegin+1);
3048 GEPOps[0] = Src;
3049 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3050
3051 std::vector<const Type*> GEPTypes;
3052 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3053 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
Chris Lattner985fe3d2004-02-25 03:45:50 +00003054
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003055 // Keep emitting instructions until we consume the entire GEP instruction.
3056 while (!GEPOps.empty()) {
3057 unsigned OldSize = GEPOps.size();
Chris Lattnerb6bac512004-02-25 06:13:04 +00003058 unsigned BaseReg, Scale, IndexReg, Disp;
3059 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003060
Chris Lattner985fe3d2004-02-25 03:45:50 +00003061 if (GEPOps.size() != OldSize) {
3062 // getGEPIndex consumed some of the input. Build an LEA instruction here.
Chris Lattnerb6bac512004-02-25 06:13:04 +00003063 unsigned NextTarget = 0;
3064 if (!GEPOps.empty()) {
3065 assert(BaseReg == 0 &&
3066 "getGEPIndex should have left the base register open for chaining!");
3067 NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
Chris Lattner985fe3d2004-02-25 03:45:50 +00003068 }
Chris Lattnerb6bac512004-02-25 06:13:04 +00003069
3070 if (IndexReg == 0 && Disp == 0)
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003071 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattnerb6bac512004-02-25 06:13:04 +00003072 else
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003073 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
Chris Lattnerb6bac512004-02-25 06:13:04 +00003074 BaseReg, Scale, IndexReg, Disp);
3075 --IP;
3076 TargetReg = NextTarget;
Chris Lattner985fe3d2004-02-25 03:45:50 +00003077 } else if (GEPTypes.empty()) {
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003078 // The getGEPIndex operation didn't want to build an LEA. Check to see if
3079 // all operands are consumed but the base pointer. If so, just load it
3080 // into the register.
Chris Lattner7ca04092004-02-22 17:35:42 +00003081 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003082 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
Chris Lattner7ca04092004-02-22 17:35:42 +00003083 } else {
3084 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003085 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
Chris Lattner7ca04092004-02-22 17:35:42 +00003086 }
3087 break; // we are now done
Chris Lattnerb6bac512004-02-25 06:13:04 +00003088
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003089 } else {
Brian Gaeke20244b72002-12-12 15:33:40 +00003090 // It's an array or pointer access: [ArraySize x ElementType].
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003091 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3092 Value *idx = GEPOps.back();
3093 GEPOps.pop_back(); // Consume a GEP operand
3094 GEPTypes.pop_back();
Chris Lattner8a307e82002-12-16 19:32:50 +00003095
Chris Lattner28977af2004-04-05 01:30:19 +00003096 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
Chris Lattnerf5854472003-06-21 16:01:24 +00003097 // operand on X86. Handle this case directly now...
3098 if (CastInst *CI = dyn_cast<CastInst>(idx))
3099 if (CI->getOperand(0)->getType() == Type::IntTy ||
3100 CI->getOperand(0)->getType() == Type::UIntTy)
3101 idx = CI->getOperand(0);
3102
Chris Lattner3e130a22003-01-13 00:32:26 +00003103 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
Chris Lattner8a307e82002-12-16 19:32:50 +00003104 // must find the size of the pointed-to type (Not coincidentally, the next
3105 // type is the type of the elements in the array).
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003106 const Type *ElTy = SqTy->getElementType();
3107 unsigned elementSize = TD.getTypeSize(ElTy);
Chris Lattner8a307e82002-12-16 19:32:50 +00003108
3109 // If idxReg is a constant, we don't need to perform the multiply!
Chris Lattner28977af2004-04-05 01:30:19 +00003110 if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
Chris Lattner3e130a22003-01-13 00:32:26 +00003111 if (!CSI->isNullValue()) {
Chris Lattner28977af2004-04-05 01:30:19 +00003112 unsigned Offset = elementSize*CSI->getRawValue();
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003113 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003114 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00003115 .addReg(Reg).addImm(Offset);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003116 --IP; // Insert the next instruction before this one.
3117 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003118 }
3119 } else if (elementSize == 1) {
3120 // If the element size is 1, we don't have to multiply, just add
3121 unsigned idxReg = getReg(idx, MBB, IP);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003122 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003123 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003124 --IP; // Insert the next instruction before this one.
3125 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003126 } else {
3127 unsigned idxReg = getReg(idx, MBB, IP);
3128 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00003129
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003130 // Make sure we can back the iterator up to point to the first
3131 // instruction emitted.
3132 MachineBasicBlock::iterator BeforeIt = IP;
3133 if (IP == MBB->begin())
3134 BeforeIt = MBB->end();
3135 else
3136 --BeforeIt;
Chris Lattnerb2acc512003-10-19 21:09:10 +00003137 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
3138
Chris Lattner8a307e82002-12-16 19:32:50 +00003139 // Emit an ADD to add OffsetReg to the basePtr.
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003140 unsigned Reg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003141 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
Chris Lattneree352852004-02-29 07:22:16 +00003142 .addReg(Reg).addReg(OffsetReg);
Chris Lattner3f1e8e72004-02-22 07:04:00 +00003143
3144 // Step to the first instruction of the multiply.
3145 if (BeforeIt == MBB->end())
3146 IP = MBB->begin();
3147 else
3148 IP = ++BeforeIt;
3149
3150 TargetReg = Reg; // Codegen the rest of the GEP into this
Chris Lattner8a307e82002-12-16 19:32:50 +00003151 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003152 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003153 }
Brian Gaeke20244b72002-12-12 15:33:40 +00003154}
3155
3156
Chris Lattner065faeb2002-12-28 20:24:02 +00003157/// visitAllocaInst - If this is a fixed size alloca, allocate space from the
3158/// frame manager, otherwise do it the hard way.
3159///
3160void ISel::visitAllocaInst(AllocaInst &I) {
Brian Gaekee48ec012002-12-13 06:46:31 +00003161 // Find the data size of the alloca inst's getAllocatedType.
Chris Lattner065faeb2002-12-28 20:24:02 +00003162 const Type *Ty = I.getAllocatedType();
3163 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
3164
3165 // If this is a fixed size alloca in the entry block for the function,
3166 // statically stack allocate the space.
3167 //
3168 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
3169 if (I.getParent() == I.getParent()->getParent()->begin()) {
3170 TySize *= CUI->getValue(); // Get total allocated size...
3171 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
3172
3173 // Create a new stack object using the frame manager...
3174 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003175 addFrameReference(BuildMI(BB, X86::LEA32r, 5, getReg(I)), FrameIdx);
Chris Lattner065faeb2002-12-28 20:24:02 +00003176 return;
3177 }
3178 }
3179
3180 // Create a register to hold the temporary result of multiplying the type size
3181 // constant by the variable amount.
3182 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
3183 unsigned SrcReg1 = getReg(I.getArraySize());
Chris Lattner065faeb2002-12-28 20:24:02 +00003184
3185 // TotalSizeReg = mul <numelements>, <TypeSize>
3186 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00003187 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
Chris Lattner065faeb2002-12-28 20:24:02 +00003188
3189 // AddedSize = add <TotalSizeReg>, 15
3190 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003191 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
Chris Lattner065faeb2002-12-28 20:24:02 +00003192
3193 // AlignedSize = and <AddedSize>, ~15
3194 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003195 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
Chris Lattner065faeb2002-12-28 20:24:02 +00003196
Brian Gaekee48ec012002-12-13 06:46:31 +00003197 // Subtract size from stack pointer, thereby allocating some space.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003198 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
Chris Lattner065faeb2002-12-28 20:24:02 +00003199
Brian Gaekee48ec012002-12-13 06:46:31 +00003200 // Put a pointer to the space into the result register, by copying
3201 // the stack pointer.
Alkis Evlogimenos8295f202004-02-29 08:50:03 +00003202 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
Chris Lattner065faeb2002-12-28 20:24:02 +00003203
Misha Brukman48196b32003-05-03 02:18:17 +00003204 // Inform the Frame Information that we have just allocated a variable-sized
Chris Lattner065faeb2002-12-28 20:24:02 +00003205 // object.
3206 F->getFrameInfo()->CreateVariableSizedObject();
Brian Gaeke20244b72002-12-12 15:33:40 +00003207}
Chris Lattner3e130a22003-01-13 00:32:26 +00003208
3209/// visitMallocInst - Malloc instructions are code generated into direct calls
3210/// to the library malloc.
3211///
3212void ISel::visitMallocInst(MallocInst &I) {
3213 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
3214 unsigned Arg;
3215
3216 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
3217 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
3218 } else {
3219 Arg = makeAnotherReg(Type::UIntTy);
Chris Lattnerb2acc512003-10-19 21:09:10 +00003220 unsigned Op0Reg = getReg(I.getOperand(0));
Chris Lattner3e130a22003-01-13 00:32:26 +00003221 MachineBasicBlock::iterator MBBI = BB->end();
Chris Lattnerb2acc512003-10-19 21:09:10 +00003222 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
Chris Lattner3e130a22003-01-13 00:32:26 +00003223 }
3224
3225 std::vector<ValueRecord> Args;
3226 Args.push_back(ValueRecord(Arg, Type::UIntTy));
3227 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003228 1).addExternalSymbol("malloc", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00003229 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
3230}
3231
3232
3233/// visitFreeInst - Free instructions are code gen'd to call the free libc
3234/// function.
3235///
3236void ISel::visitFreeInst(FreeInst &I) {
3237 std::vector<ValueRecord> Args;
Chris Lattner5e2cb8b2003-08-04 02:12:48 +00003238 Args.push_back(ValueRecord(I.getOperand(0)));
Chris Lattner3e130a22003-01-13 00:32:26 +00003239 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
Misha Brukmanc8893fc2003-10-23 16:22:08 +00003240 1).addExternalSymbol("free", true);
Chris Lattner3e130a22003-01-13 00:32:26 +00003241 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
3242}
3243
Chris Lattnerd281de22003-07-26 23:49:58 +00003244/// createX86SimpleInstructionSelector - This pass converts an LLVM function
Chris Lattnerb4f68ed2002-10-29 22:37:54 +00003245/// into a machine code representation is a very simple peep-hole fashion. The
Chris Lattner72614082002-10-25 22:55:53 +00003246/// generated code sucks but the implementation is nice and simple.
3247///
Chris Lattnerf70e0c22003-12-28 21:23:38 +00003248FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
3249 return new ISel(TM);
Chris Lattner72614082002-10-25 22:55:53 +00003250}