1 //===-- X86ISelSimple.cpp - A simple instruction selector for x86 ---------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file defines a simple peephole instruction selector for the x86 target
12 //===----------------------------------------------------------------------===//
15 #include "X86InstrBuilder.h"
16 #include "X86InstrInfo.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/CodeGen/IntrinsicLowering.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/InstVisitor.h"
31 #include "llvm/ADT/Statistic.h"
36 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
38 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
42 cByte, cShort, cInt, cFP, cLong
46 /// getClass - Turn a primitive type into a "class" number which is based on the
47 /// size of the type, and whether or not it is floating point.
49 static inline TypeClass getClass(const Type *Ty) {
50 switch (Ty->getTypeID()) {
52 case Type::UByteTyID: return cByte; // Byte operands are class #0
54 case Type::UShortTyID: return cShort; // Short operands are class #1
57 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
60 case Type::DoubleTyID: return cFP; // Floating Point is #3
63 case Type::ULongTyID: return cLong; // Longs are class #4
65 assert(0 && "Invalid type to getClass!");
66 return cByte; // not reached
70 // getClassB - Just like getClass, but treat boolean values as bytes.
71 static inline TypeClass getClassB(const Type *Ty) {
72 if (Ty == Type::BoolTy) return cByte;
77 struct X86ISel : public FunctionPass, InstVisitor<X86ISel> {
79 MachineFunction *F; // The function we are compiling into
80 MachineBasicBlock *BB; // The current MBB we are compiling
81 int VarArgsFrameIndex; // FrameIndex for start of varargs area
82 int ReturnAddressIndex; // FrameIndex for the return address
84 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
86 // MBBMap - Mapping between LLVM BB -> Machine BB
87 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
89 // AllocaMap - Mapping from fixed sized alloca instructions to the
90 // FrameIndex for the alloca.
91 std::map<AllocaInst*, unsigned> AllocaMap;
93 X86ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
95 /// runOnFunction - Top level implementation of instruction selection for
96 /// the entire function.
98 bool runOnFunction(Function &Fn) {
99 // First pass over the function, lower any unknown intrinsic functions
100 // with the IntrinsicLowering class.
101 LowerUnknownIntrinsicFunctionCalls(Fn);
103 F = &MachineFunction::construct(&Fn, TM);
105 // Create all of the machine basic blocks for the function...
106 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
107 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
111 // Set up a frame object for the return address. This is used by the
112 // llvm.returnaddress & llvm.frameaddress intrinisics.
113 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
115 // Copy incoming arguments off of the stack...
116 LoadArgumentsToVirtualRegs(Fn);
118 // If this is main, emit special code.
119 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
120 EmitSpecialCodeForMain();
122 // Instruction select everything except PHI nodes
125 // Select the PHI nodes
128 // Insert the FP_REG_KILL instructions into blocks that need them.
135 // We always build a machine code representation for the function
139 virtual const char *getPassName() const {
140 return "X86 Simple Instruction Selection";
143 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
144 /// the main function.
145 void EmitSpecialCodeForMain();
147 /// visitBasicBlock - This method is called when we are visiting a new basic
148 /// block. This simply creates a new MachineBasicBlock to emit code into
149 /// and adds it to the current MachineFunction. Subsequent visit* for
150 /// instructions will be invoked for all instructions in the basic block.
152 void visitBasicBlock(BasicBlock &LLVM_BB) {
153 BB = MBBMap[&LLVM_BB];
156 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
157 /// function, lowering any calls to unknown intrinsic functions into the
158 /// equivalent LLVM code.
160 void LowerUnknownIntrinsicFunctionCalls(Function &F);
162 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
163 /// from the stack into virtual registers.
165 void LoadArgumentsToVirtualRegs(Function &F);
167 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
168 /// because we have to generate our sources into the source basic blocks,
169 /// not the current one.
171 void SelectPHINodes();
173 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
174 /// that need them. This only occurs due to the floating point stackifier
175 /// not being aggressive enough to handle arbitrary global stackification.
177 void InsertFPRegKills();
179 // Visitation methods for various instructions. These methods simply emit
180 // fixed X86 code for each instruction.
183 // Control flow operators
184 void visitReturnInst(ReturnInst &RI);
185 void visitBranchInst(BranchInst &BI);
186 void visitUnreachableInst(UnreachableInst &UI) {}
192 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
193 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
195 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
196 const std::vector<ValueRecord> &Args);
197 void visitCallInst(CallInst &I);
198 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
200 // Arithmetic operators
201 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
202 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
203 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
204 void visitMul(BinaryOperator &B);
206 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
207 void visitRem(BinaryOperator &B) { visitDivRem(B); }
208 void visitDivRem(BinaryOperator &B);
211 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
212 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
213 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
215 // Comparison operators...
216 void visitSetCondInst(SetCondInst &I);
217 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
218 MachineBasicBlock *MBB,
219 MachineBasicBlock::iterator MBBI);
220 void visitSelectInst(SelectInst &SI);
223 // Memory Instructions
224 void visitLoadInst(LoadInst &I);
225 void visitStoreInst(StoreInst &I);
226 void visitGetElementPtrInst(GetElementPtrInst &I);
227 void visitAllocaInst(AllocaInst &I);
228 void visitMallocInst(MallocInst &I);
229 void visitFreeInst(FreeInst &I);
232 void visitShiftInst(ShiftInst &I);
233 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
234 void visitCastInst(CastInst &I);
235 void visitVANextInst(VANextInst &I);
236 void visitVAArgInst(VAArgInst &I);
238 void visitInstruction(Instruction &I) {
239 std::cerr << "Cannot instruction select: " << I;
243 /// promote32 - Make a value 32-bits wide, and put it somewhere.
245 void promote32(unsigned targetReg, const ValueRecord &VR);
247 /// getAddressingMode - Get the addressing mode to use to address the
248 /// specified value. The returned value should be used with addFullAddress.
249 void getAddressingMode(Value *Addr, X86AddressMode &AM);
252 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
254 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
255 std::vector<Value*> &GEPOps,
256 std::vector<const Type*> &GEPTypes,
259 /// isGEPFoldable - Return true if the specified GEP can be completely
260 /// folded into the addressing mode of a load/store or lea instruction.
261 bool isGEPFoldable(MachineBasicBlock *MBB,
262 Value *Src, User::op_iterator IdxBegin,
263 User::op_iterator IdxEnd, X86AddressMode &AM);
265 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
266 /// constant expression GEP support.
268 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
269 Value *Src, User::op_iterator IdxBegin,
270 User::op_iterator IdxEnd, unsigned TargetReg);
272 /// emitCastOperation - Common code shared between visitCastInst and
273 /// constant expression cast support.
275 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
276 Value *Src, const Type *DestTy, unsigned TargetReg);
278 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
279 /// and constant expression support.
281 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
282 MachineBasicBlock::iterator IP,
283 Value *Op0, Value *Op1,
284 unsigned OperatorClass, unsigned TargetReg);
286 /// emitBinaryFPOperation - This method handles emission of floating point
287 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
288 void emitBinaryFPOperation(MachineBasicBlock *BB,
289 MachineBasicBlock::iterator IP,
290 Value *Op0, Value *Op1,
291 unsigned OperatorClass, unsigned TargetReg);
293 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
294 Value *Op0, Value *Op1, unsigned TargetReg);
296 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
297 unsigned DestReg, const Type *DestTy,
298 unsigned Op0Reg, unsigned Op1Reg);
299 void doMultiplyConst(MachineBasicBlock *MBB,
300 MachineBasicBlock::iterator MBBI,
301 unsigned DestReg, const Type *DestTy,
302 unsigned Op0Reg, unsigned Op1Val);
304 void emitDivRemOperation(MachineBasicBlock *BB,
305 MachineBasicBlock::iterator IP,
306 Value *Op0, Value *Op1, bool isDiv,
309 /// emitSetCCOperation - Common code shared between visitSetCondInst and
310 /// constant expression support.
312 void emitSetCCOperation(MachineBasicBlock *BB,
313 MachineBasicBlock::iterator IP,
314 Value *Op0, Value *Op1, unsigned Opcode,
317 /// emitShiftOperation - Common code shared between visitShiftInst and
318 /// constant expression support.
320 void emitShiftOperation(MachineBasicBlock *MBB,
321 MachineBasicBlock::iterator IP,
322 Value *Op, Value *ShiftAmount, bool isLeftShift,
323 const Type *ResultTy, unsigned DestReg);
325 // Emit code for a 'SHLD DestReg, Op0, Op1, Amt' operation, where Amt is a
327 void doSHLDConst(MachineBasicBlock *MBB,
328 MachineBasicBlock::iterator MBBI,
329 unsigned DestReg, unsigned Op0Reg, unsigned Op1Reg,
332 /// emitSelectOperation - Common code shared between visitSelectInst and the
333 /// constant expression support.
334 void emitSelectOperation(MachineBasicBlock *MBB,
335 MachineBasicBlock::iterator IP,
336 Value *Cond, Value *TrueVal, Value *FalseVal,
339 /// copyConstantToRegister - Output the instructions required to put the
340 /// specified constant into the specified register.
342 void copyConstantToRegister(MachineBasicBlock *MBB,
343 MachineBasicBlock::iterator MBBI,
344 Constant *C, unsigned Reg);
346 void emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
347 unsigned LHS, unsigned RHS);
349 /// makeAnotherReg - This method returns the next register number we haven't
352 /// Long values are handled somewhat specially. They are always allocated
353 /// as pairs of 32 bit integer values. The register number returned is the
354 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
355 /// of the long value.
357 unsigned makeAnotherReg(const Type *Ty) {
358 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
359 "Current target doesn't have X86 reg info??");
360 const X86RegisterInfo *MRI =
361 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
362 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
363 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
364 // Create the lower part
365 F->getSSARegMap()->createVirtualRegister(RC);
366 // Create the upper part.
367 return F->getSSARegMap()->createVirtualRegister(RC)-1;
370 // Add the mapping of regnumber => reg class to MachineFunction
371 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
372 return F->getSSARegMap()->createVirtualRegister(RC);
375 /// getReg - This method turns an LLVM value into a register number.
377 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
378 unsigned getReg(Value *V) {
379 // Just append to the end of the current bb.
380 MachineBasicBlock::iterator It = BB->end();
381 return getReg(V, BB, It);
383 unsigned getReg(Value *V, MachineBasicBlock *MBB,
384 MachineBasicBlock::iterator IPt);
386 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
387 /// that is to be statically allocated with the initial stack frame
389 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
393 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
394 /// instruction in the entry block, return it. Otherwise, return a null
396 static AllocaInst *dyn_castFixedAlloca(Value *V) {
397 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
398 BasicBlock *BB = AI->getParent();
399 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
405 /// getReg - This method turns an LLVM value into a register number.
407 unsigned X86ISel::getReg(Value *V, MachineBasicBlock *MBB,
408 MachineBasicBlock::iterator IPt) {
409 // If this operand is a constant, emit the code to copy the constant into
410 // the register here...
411 if (Constant *C = dyn_cast<Constant>(V)) {
412 unsigned Reg = makeAnotherReg(V->getType());
413 copyConstantToRegister(MBB, IPt, C, Reg);
415 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
416 // Do not emit noop casts at all, unless it's a double -> float cast.
417 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()) &&
418 (CI->getType() != Type::FloatTy ||
419 CI->getOperand(0)->getType() != Type::DoubleTy))
420 return getReg(CI->getOperand(0), MBB, IPt);
421 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
422 // If the alloca address couldn't be folded into the instruction addressing,
423 // emit an explicit LEA as appropriate.
424 unsigned Reg = makeAnotherReg(V->getType());
425 unsigned FI = getFixedSizedAllocaFI(AI);
426 addFrameReference(BuildMI(*MBB, IPt, X86::LEA32r, 4, Reg), FI);
430 unsigned &Reg = RegMap[V];
432 Reg = makeAnotherReg(V->getType());
439 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
440 /// that is to be statically allocated with the initial stack frame
442 unsigned X86ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
443 // Already computed this?
444 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
445 if (I != AllocaMap.end() && I->first == AI) return I->second;
447 const Type *Ty = AI->getAllocatedType();
448 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
449 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
450 TySize *= CUI->getValue(); // Get total allocated size...
451 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
453 // Create a new stack object using the frame manager...
454 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
455 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
460 /// copyConstantToRegister - Output the instructions required to put the
461 /// specified constant into the specified register.
463 void X86ISel::copyConstantToRegister(MachineBasicBlock *MBB,
464 MachineBasicBlock::iterator IP,
465 Constant *C, unsigned R) {
466 if (isa<UndefValue>(C)) {
467 switch (getClassB(C->getType())) {
469 // FIXME: SHOULD TEACH STACKIFIER ABOUT UNDEF VALUES!
470 BuildMI(*MBB, IP, X86::FLD0, 0, R);
473 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, R+1);
476 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, R);
479 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
481 switch (CE->getOpcode()) {
482 case Instruction::GetElementPtr:
483 emitGEPOperation(MBB, IP, CE->getOperand(0),
484 CE->op_begin()+1, CE->op_end(), R);
486 case Instruction::Cast:
487 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
490 case Instruction::Xor: ++Class; // FALL THROUGH
491 case Instruction::Or: ++Class; // FALL THROUGH
492 case Instruction::And: ++Class; // FALL THROUGH
493 case Instruction::Sub: ++Class; // FALL THROUGH
494 case Instruction::Add:
495 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
499 case Instruction::Mul:
500 emitMultiply(MBB, IP, CE->getOperand(0), CE->getOperand(1), R);
503 case Instruction::Div:
504 case Instruction::Rem:
505 emitDivRemOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
506 CE->getOpcode() == Instruction::Div, R);
509 case Instruction::SetNE:
510 case Instruction::SetEQ:
511 case Instruction::SetLT:
512 case Instruction::SetGT:
513 case Instruction::SetLE:
514 case Instruction::SetGE:
515 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
519 case Instruction::Shl:
520 case Instruction::Shr:
521 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
522 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
525 case Instruction::Select:
526 emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
527 CE->getOperand(2), R);
531 std::cerr << "Offending expr: " << *C << "\n";
532 assert(0 && "Constant expression not yet handled!\n");
536 if (C->getType()->isIntegral()) {
537 unsigned Class = getClassB(C->getType());
539 if (Class == cLong) {
540 // Copy the value into the register pair.
541 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
542 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
543 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
547 assert(Class <= cInt && "Type not handled yet!");
549 static const unsigned IntegralOpcodeTab[] = {
550 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
553 if (C->getType() == Type::BoolTy) {
554 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
556 ConstantInt *CI = cast<ConstantInt>(C);
557 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
559 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
560 if (CFP->isExactlyValue(+0.0))
561 BuildMI(*MBB, IP, X86::FLD0, 0, R);
562 else if (CFP->isExactlyValue(+1.0))
563 BuildMI(*MBB, IP, X86::FLD1, 0, R);
565 // Otherwise we need to spill the constant to memory...
566 MachineConstantPool *CP = F->getConstantPool();
567 unsigned CPI = CP->getConstantPoolIndex(CFP);
568 const Type *Ty = CFP->getType();
570 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
571 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
572 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
575 } else if (isa<ConstantPointerNull>(C)) {
576 // Copy zero (null pointer) to the register.
577 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
578 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
579 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(GV);
581 std::cerr << "Offending constant: " << *C << "\n";
582 assert(0 && "Type not handled yet!");
586 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
587 /// the stack into virtual registers.
589 void X86ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
590 // Emit instructions to load the arguments... On entry to a function on the
591 // X86, the stack frame looks like this:
593 // [ESP] -- return address
594 // [ESP + 4] -- first argument (leftmost lexically)
595 // [ESP + 8] -- second argument, if first argument is four bytes in size
598 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
599 MachineFrameInfo *MFI = F->getFrameInfo();
601 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
602 bool ArgLive = !I->use_empty();
603 unsigned Reg = ArgLive ? getReg(*I) : 0;
604 int FI; // Frame object index
606 switch (getClassB(I->getType())) {
609 FI = MFI->CreateFixedObject(1, ArgOffset);
610 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
615 FI = MFI->CreateFixedObject(2, ArgOffset);
616 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
621 FI = MFI->CreateFixedObject(4, ArgOffset);
622 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
627 FI = MFI->CreateFixedObject(8, ArgOffset);
628 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
629 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
631 ArgOffset += 4; // longs require 4 additional bytes
636 if (I->getType() == Type::FloatTy) {
637 Opcode = X86::FLD32m;
638 FI = MFI->CreateFixedObject(4, ArgOffset);
640 Opcode = X86::FLD64m;
641 FI = MFI->CreateFixedObject(8, ArgOffset);
643 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
645 if (I->getType() == Type::DoubleTy)
646 ArgOffset += 4; // doubles require 4 additional bytes
649 assert(0 && "Unhandled argument type!");
651 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
654 // If the function takes variable number of arguments, add a frame offset for
655 // the start of the first vararg value... this is used to expand
657 if (Fn.getFunctionType()->isVarArg())
658 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
661 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
662 /// the main function.
663 void X86ISel::EmitSpecialCodeForMain() {
664 // Switch the FPU to 64-bit precision mode for better compatibility and speed.
665 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
666 addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
668 // Set the high part to be 64-bit precision.
669 addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
670 CWFrameIdx, 1).addImm(2);
672 // Reload the modified control word now.
673 addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
676 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
677 /// because we have to generate our sources into the source basic blocks, not
680 void X86ISel::SelectPHINodes() {
681 const TargetInstrInfo &TII = *TM.getInstrInfo();
682 const Function &LF = *F->getFunction(); // The LLVM function...
683 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
684 const BasicBlock *BB = I;
685 MachineBasicBlock &MBB = *MBBMap[I];
687 // Loop over all of the PHI nodes in the LLVM basic block...
688 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
689 for (BasicBlock::const_iterator I = BB->begin(); isa<PHINode>(I); ++I) {
690 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I));
692 // Create a new machine instr PHI node, and insert it.
693 unsigned PHIReg = getReg(*PN);
694 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
695 X86::PHI, PN->getNumOperands(), PHIReg);
697 MachineInstr *LongPhiMI = 0;
698 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
699 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
700 X86::PHI, PN->getNumOperands(), PHIReg+1);
702 // PHIValues - Map of blocks to incoming virtual registers. We use this
703 // so that we only initialize one incoming value for a particular block,
704 // even if the block has multiple entries in the PHI node.
706 std::map<MachineBasicBlock*, unsigned> PHIValues;
708 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
709 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
711 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
712 PHIValues.lower_bound(PredMBB);
714 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
715 // We already inserted an initialization of the register for this
716 // predecessor. Recycle it.
717 ValReg = EntryIt->second;
720 // Get the incoming value into a virtual register.
722 Value *Val = PN->getIncomingValue(i);
724 // If this is a constant or GlobalValue, we may have to insert code
725 // into the basic block to compute it into a virtual register.
726 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val))) {
727 // Simple constants get emitted at the end of the basic block,
728 // before any terminator instructions. We "know" that the code to
729 // move a constant into a register will never clobber any flags.
730 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
732 // Because we don't want to clobber any values which might be in
733 // physical registers with the computation of this constant (which
734 // might be arbitrarily complex if it is a constant expression),
735 // just insert the computation at the top of the basic block.
736 MachineBasicBlock::iterator PI = PredMBB->begin();
738 // Skip over any PHI nodes though!
739 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
742 ValReg = getReg(Val, PredMBB, PI);
745 // Remember that we inserted a value for this PHI for this predecessor
746 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
749 PhiMI->addRegOperand(ValReg);
750 PhiMI->addMachineBasicBlockOperand(PredMBB);
752 LongPhiMI->addRegOperand(ValReg+1);
753 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
757 // Now that we emitted all of the incoming values for the PHI node, make
758 // sure to reposition the InsertPoint after the PHI that we just added.
759 // This is needed because we might have inserted a constant into this
760 // block, right after the PHI's which is before the old insert point!
761 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
767 /// RequiresFPRegKill - The floating point stackifier pass cannot insert
768 /// compensation code on critical edges. As such, it requires that we kill all
769 /// FP registers on the exit from any blocks that either ARE critical edges, or
770 /// branch to a block that has incoming critical edges.
772 /// Note that this kill instruction will eventually be eliminated when
773 /// restrictions in the stackifier are relaxed.
775 static bool RequiresFPRegKill(const MachineBasicBlock *MBB) {
777 const BasicBlock *BB = MBB->getBasicBlock ();
778 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
779 const BasicBlock *Succ = *SI;
780 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
781 ++PI; // Block have at least one predecessory
782 if (PI != PE) { // If it has exactly one, this isn't crit edge
783 // If this block has more than one predecessor, check all of the
784 // predecessors to see if they have multiple successors. If so, then the
785 // block we are analyzing needs an FPRegKill.
786 for (PI = pred_begin(Succ); PI != PE; ++PI) {
787 const BasicBlock *Pred = *PI;
788 succ_const_iterator SI2 = succ_begin(Pred);
789 ++SI2; // There must be at least one successor of this block.
790 if (SI2 != succ_end(Pred))
791 return true; // Yes, we must insert the kill on this edge.
795 // If we got this far, there is no need to insert the kill instruction.
802 // InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
803 // need them. This only occurs due to the floating point stackifier not being
804 // aggressive enough to handle arbitrary global stackification.
806 // Currently we insert an FP_REG_KILL instruction into each block that uses or
807 // defines a floating point virtual register.
809 // When the global register allocators (like linear scan) finally update live
810 // variable analysis, we can keep floating point values in registers across
811 // portions of the CFG that do not involve critical edges. This will be a big
812 // win, but we are waiting on the global allocators before we can do this.
814 // With a bit of work, the floating point stackifier pass can be enhanced to
815 // break critical edges as needed (to make a place to put compensation code),
816 // but this will require some infrastructure improvements as well.
818 void X86ISel::InsertFPRegKills() {
819 SSARegMap &RegMap = *F->getSSARegMap();
821 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
822 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
823 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
824 MachineOperand& MO = I->getOperand(i);
825 if (MO.isRegister() && MO.getReg()) {
826 unsigned Reg = MO.getReg();
827 if (MRegisterInfo::isVirtualRegister(Reg)) {
828 unsigned RegSize = RegMap.getRegClass(Reg)->getSize();
829 if (RegSize == 10 || RegSize == 8)
834 // If we haven't found an FP register use or def in this basic block, check
835 // to see if any of our successors has an FP PHI node, which will cause a
836 // copy to be inserted into this block.
837 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
838 SE = BB->succ_end(); SI != SE; ++SI) {
839 MachineBasicBlock *SBB = *SI;
840 for (MachineBasicBlock::iterator I = SBB->begin();
841 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
842 const TargetRegisterClass *RC =
843 RegMap.getRegClass(I->getOperand(0).getReg());
844 if (RC->getSize() == 10 || RC->getSize() == 8)
850 // Okay, this block uses an FP register. If the block has successors (ie,
851 // it's not an unwind/return), insert the FP_REG_KILL instruction.
852 if (BB->succ_size () && RequiresFPRegKill(BB)) {
853 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
860 void X86ISel::getAddressingMode(Value *Addr, X86AddressMode &AM) {
861 AM.BaseType = X86AddressMode::RegBase;
862 AM.Base.Reg = 0; AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
863 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
864 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
867 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
868 if (CE->getOpcode() == Instruction::GetElementPtr)
869 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
872 } else if (AllocaInst *AI = dyn_castFixedAlloca(Addr)) {
873 AM.BaseType = X86AddressMode::FrameIndexBase;
874 AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
876 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
881 // If it's not foldable, reset addr mode.
882 AM.BaseType = X86AddressMode::RegBase;
883 AM.Base.Reg = getReg(Addr);
884 AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
887 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
888 // it into the conditional branch or select instruction which is the only user
889 // of the cc instruction. This is the case if the conditional branch is the
890 // only user of the setcc. We also don't handle long arguments below, so we
891 // reject them here as well.
893 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
894 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
895 if (SCI->hasOneUse()) {
896 Instruction *User = cast<Instruction>(SCI->use_back());
897 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
898 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
899 SCI->getOpcode() == Instruction::SetEQ ||
900 SCI->getOpcode() == Instruction::SetNE) &&
901 (isa<BranchInst>(User) || User->getOperand(0) == V))
907 // Return a fixed numbering for setcc instructions which does not depend on the
908 // order of the opcodes.
910 static unsigned getSetCCNumber(unsigned Opcode) {
912 default: assert(0 && "Unknown setcc instruction!");
913 case Instruction::SetEQ: return 0;
914 case Instruction::SetNE: return 1;
915 case Instruction::SetLT: return 2;
916 case Instruction::SetGE: return 3;
917 case Instruction::SetGT: return 4;
918 case Instruction::SetLE: return 5;
922 // LLVM -> X86 signed X86 unsigned
923 // ----- ---------- ------------
924 // seteq -> sete sete
925 // setne -> setne setne
926 // setlt -> setl setb
927 // setge -> setge setae
928 // setgt -> setg seta
929 // setle -> setle setbe
931 // sets // Used by comparison with 0 optimization
933 static const unsigned SetCCOpcodeTab[2][8] = {
934 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
936 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
937 X86::SETSr, X86::SETNSr },
940 /// emitUCOMr - In the future when we support processors before the P6, this
941 /// wraps the logic for emitting an FUCOMr vs FUCOMIr.
942 void X86ISel::emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
943 unsigned LHS, unsigned RHS) {
944 if (0) { // for processors prior to the P6
945 BuildMI(*MBB, IP, X86::FUCOMr, 2).addReg(LHS).addReg(RHS);
946 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
947 BuildMI(*MBB, IP, X86::SAHF, 1);
949 BuildMI(*MBB, IP, X86::FUCOMIr, 2).addReg(LHS).addReg(RHS);
953 // EmitComparison - This function emits a comparison of the two operands,
954 // returning the extended setcc code to use.
955 unsigned X86ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
956 MachineBasicBlock *MBB,
957 MachineBasicBlock::iterator IP) {
958 // The arguments are already supposed to be of the same type.
959 const Type *CompTy = Op0->getType();
960 unsigned Class = getClassB(CompTy);
962 // Special case handling of: cmp R, i
963 if (isa<ConstantPointerNull>(Op1)) {
964 unsigned Op0r = getReg(Op0, MBB, IP);
965 if (OpNum < 2) // seteq/setne -> test
966 BuildMI(*MBB, IP, X86::TEST32rr, 2).addReg(Op0r).addReg(Op0r);
968 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(0);
971 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
972 if (Class == cByte || Class == cShort || Class == cInt) {
973 unsigned Op1v = CI->getRawValue();
975 // Mask off any upper bits of the constant, if there are any...
976 Op1v &= (1ULL << (8 << Class)) - 1;
978 // If this is a comparison against zero, emit more efficient code. We
979 // can't handle unsigned comparisons against zero unless they are == or
980 // !=. These should have been strength reduced already anyway.
981 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
983 // If this is a comparison against zero and the LHS is an and of a
984 // register with a constant, use the test to do the and.
985 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
986 if (Op0I->getOpcode() == Instruction::And && Op0->hasOneUse() &&
987 isa<ConstantInt>(Op0I->getOperand(1))) {
988 static const unsigned TESTTab[] = {
989 X86::TEST8ri, X86::TEST16ri, X86::TEST32ri
993 unsigned LHS = getReg(Op0I->getOperand(0), MBB, IP);
995 cast<ConstantInt>(Op0I->getOperand(1))->getRawValue();
996 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(LHS).addImm(Imm);
998 if (OpNum == 2) return 6; // Map jl -> js
999 if (OpNum == 3) return 7; // Map jg -> jns
1003 unsigned Op0r = getReg(Op0, MBB, IP);
1004 static const unsigned TESTTab[] = {
1005 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
1007 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
1009 if (OpNum == 2) return 6; // Map jl -> js
1010 if (OpNum == 3) return 7; // Map jg -> jns
1014 static const unsigned CMPTab[] = {
1015 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
1018 unsigned Op0r = getReg(Op0, MBB, IP);
1019 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
1022 unsigned Op0r = getReg(Op0, MBB, IP);
1023 assert(Class == cLong && "Unknown integer class!");
1024 unsigned LowCst = CI->getRawValue();
1025 unsigned HiCst = CI->getRawValue() >> 32;
1026 if (OpNum < 2) { // seteq, setne
1027 unsigned LoTmp = Op0r;
1029 LoTmp = makeAnotherReg(Type::IntTy);
1030 BuildMI(*MBB, IP, X86::XOR32ri, 2, LoTmp).addReg(Op0r).addImm(LowCst);
1032 unsigned HiTmp = Op0r+1;
1034 HiTmp = makeAnotherReg(Type::IntTy);
1035 BuildMI(*MBB, IP, X86::XOR32ri, 2,HiTmp).addReg(Op0r+1).addImm(HiCst);
1037 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1038 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1041 // Emit a sequence of code which compares the high and low parts once
1042 // each, then uses a conditional move to handle the overflow case. For
1043 // example, a setlt for long would generate code like this:
1045 // AL = lo(op1) < lo(op2) // Always unsigned comparison
1046 // BL = hi(op1) < hi(op2) // Signedness depends on operands
1047 // dest = hi(op1) == hi(op2) ? BL : AL;
1050 // FIXME: This would be much better if we had hierarchical register
1051 // classes! Until then, hardcode registers so that we can deal with
1052 // their aliases (because we don't have conditional byte moves).
1054 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(LowCst);
1055 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
1056 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r+1).addImm(HiCst);
1057 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0,X86::BL);
1058 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1059 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
1060 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
1062 // NOTE: visitSetCondInst knows that the value is dumped into the BL
1063 // register at this point for long values...
1069 unsigned Op0r = getReg(Op0, MBB, IP);
1071 // Special case handling of comparison against +/- 0.0
1072 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
1073 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
1074 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
1075 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
1076 BuildMI(*MBB, IP, X86::SAHF, 1);
1080 unsigned Op1r = getReg(Op1, MBB, IP);
1082 default: assert(0 && "Unknown type class!");
1083 // Emit: cmp <var1>, <var2> (do the comparison). We can
1084 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
1087 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
1090 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
1093 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
1096 emitUCOMr(MBB, IP, Op0r, Op1r);
1100 if (OpNum < 2) { // seteq, setne
1101 unsigned LoTmp = makeAnotherReg(Type::IntTy);
1102 unsigned HiTmp = makeAnotherReg(Type::IntTy);
1103 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1104 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
1105 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
1106 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1107 break; // Allow the sete or setne to be generated from flags set by OR
1109 // Emit a sequence of code which compares the high and low parts once
1110 // each, then uses a conditional move to handle the overflow case. For
1111 // example, a setlt for long would generate code like this:
1113 // AL = lo(op1) < lo(op2) // Signedness depends on operands
1114 // BL = hi(op1) < hi(op2) // Always unsigned comparison
1115 // dest = hi(op1) == hi(op2) ? BL : AL;
1118 // FIXME: This would be much better if we had hierarchical register
1119 // classes! Until then, hardcode registers so that we can deal with their
1120 // aliases (because we don't have conditional byte moves).
1122 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
1123 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
1124 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
1125 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
1126 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
1127 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
1128 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
1130 // NOTE: visitSetCondInst knows that the value is dumped into the BL
1131 // register at this point for long values...
1138 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
1139 /// register, then move it to wherever the result should be.
1141 void X86ISel::visitSetCondInst(SetCondInst &I) {
1142 if (canFoldSetCCIntoBranchOrSelect(&I))
1143 return; // Fold this into a branch or select.
1145 unsigned DestReg = getReg(I);
1146 MachineBasicBlock::iterator MII = BB->end();
1147 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
1151 /// emitSetCCOperation - Common code shared between visitSetCondInst and
1152 /// constant expression support.
1154 void X86ISel::emitSetCCOperation(MachineBasicBlock *MBB,
1155 MachineBasicBlock::iterator IP,
1156 Value *Op0, Value *Op1, unsigned Opcode,
1157 unsigned TargetReg) {
1158 unsigned OpNum = getSetCCNumber(Opcode);
1159 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
1161 const Type *CompTy = Op0->getType();
1162 unsigned CompClass = getClassB(CompTy);
1163 bool isSigned = CompTy->isSigned() && CompClass != cFP;
1165 if (CompClass != cLong || OpNum < 2) {
1166 // Handle normal comparisons with a setcc instruction...
1167 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
1169 // Handle long comparisons by copying the value which is already in BL into
1170 // the register we want...
1171 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
1175 void X86ISel::visitSelectInst(SelectInst &SI) {
1176 unsigned DestReg = getReg(SI);
1177 MachineBasicBlock::iterator MII = BB->end();
1178 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1179 SI.getFalseValue(), DestReg);
1182 /// emitSelect - Common code shared between visitSelectInst and the constant
1183 /// expression support.
1184 void X86ISel::emitSelectOperation(MachineBasicBlock *MBB,
1185 MachineBasicBlock::iterator IP,
1186 Value *Cond, Value *TrueVal, Value *FalseVal,
1188 unsigned SelectClass = getClassB(TrueVal->getType());
1190 // We don't support 8-bit conditional moves. If we have incoming constants,
1191 // transform them into 16-bit constants to avoid having a run-time conversion.
1192 if (SelectClass == cByte) {
1193 if (Constant *T = dyn_cast<Constant>(TrueVal))
1194 TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
1195 if (Constant *F = dyn_cast<Constant>(FalseVal))
1196 FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
1199 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1200 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1201 if (TrueReg == FalseReg) {
1202 static const unsigned Opcode[] = {
1203 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
1205 BuildMI(*MBB, IP, Opcode[SelectClass], 1, DestReg).addReg(TrueReg);
1206 if (SelectClass == cLong)
1207 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(TrueReg+1);
1212 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1213 // We successfully folded the setcc into the select instruction.
1215 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1216 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1219 const Type *CompTy = SCI->getOperand(0)->getType();
1220 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1222 // LLVM -> X86 signed X86 unsigned
1223 // ----- ---------- ------------
1224 // seteq -> cmovNE cmovNE
1225 // setne -> cmovE cmovE
1226 // setlt -> cmovGE cmovAE
1227 // setge -> cmovL cmovB
1228 // setgt -> cmovLE cmovBE
1229 // setle -> cmovG cmovA
1231 // cmovNS // Used by comparison with 0 optimization
1234 switch (SelectClass) {
1235 default: assert(0 && "Unknown value class!");
1237 // Annoyingly, we don't have a full set of floating point conditional
1239 static const unsigned OpcodeTab[2][8] = {
1240 { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
1241 X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1242 { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1244 Opcode = OpcodeTab[isSigned][OpNum];
1246 // If opcode == 0, we hit a case that we don't support. Output a setcc
1247 // and compare the result against zero.
1249 unsigned CompClass = getClassB(CompTy);
1251 if (CompClass != cLong || OpNum < 2) {
1252 CondReg = makeAnotherReg(Type::BoolTy);
1253 // Handle normal comparisons with a setcc instruction...
1254 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1256 // Long comparisons end up in the BL register.
1260 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1261 Opcode = X86::FCMOVE;
1267 static const unsigned OpcodeTab[2][8] = {
1268 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1269 X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1270 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1271 X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1273 Opcode = OpcodeTab[isSigned][OpNum];
1278 static const unsigned OpcodeTab[2][8] = {
1279 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1280 X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1281 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1282 X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1284 Opcode = OpcodeTab[isSigned][OpNum];
1289 // Get the value being branched on, and use it to set the condition codes.
1290 unsigned CondReg = getReg(Cond, MBB, IP);
1291 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1292 switch (SelectClass) {
1293 default: assert(0 && "Unknown value class!");
1294 case cFP: Opcode = X86::FCMOVE; break;
1296 case cShort: Opcode = X86::CMOVE16rr; break;
1298 case cLong: Opcode = X86::CMOVE32rr; break;
1302 unsigned RealDestReg = DestReg;
1305 // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves. Because of
1306 // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1307 // cmove, then truncate the result.
1308 if (SelectClass == cByte) {
1309 DestReg = makeAnotherReg(Type::ShortTy);
1310 if (getClassB(TrueVal->getType()) == cByte) {
1311 // Promote the true value, by storing it into AL, and reading from AX.
1312 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1313 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1314 TrueReg = makeAnotherReg(Type::ShortTy);
1315 BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1317 if (getClassB(FalseVal->getType()) == cByte) {
1318 // Promote the true value, by storing it into CL, and reading from CX.
1319 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1320 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1321 FalseReg = makeAnotherReg(Type::ShortTy);
1322 BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1326 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1328 switch (SelectClass) {
1330 // We did the computation with 16-bit registers. Truncate back to our
1331 // result by copying into AX then copying out AL.
1332 BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1333 BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1336 // Move the upper half of the value as well.
1337 BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1344 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1345 /// operand, in the specified target register.
1347 void X86ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1348 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1350 Value *Val = VR.Val;
1351 const Type *Ty = VR.Ty;
1353 if (Constant *C = dyn_cast<Constant>(Val)) {
1354 Val = ConstantExpr::getCast(C, Type::IntTy);
1358 // If this is a simple constant, just emit a MOVri directly to avoid the
1360 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1361 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1362 BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
1367 // Make sure we have the register number for this value...
1368 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1370 switch (getClassB(Ty)) {
1372 // Extend value into target register (8->32)
1374 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
1376 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
1379 // Extend value into target register (16->32)
1381 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
1383 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
1386 // Move value into target register (32->32)
1387 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
1390 assert(0 && "Unpromotable operand class in promote32");
1394 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
1395 /// we have the following possibilities:
1397 /// ret void: No return value, simply emit a 'ret' instruction
1398 /// ret sbyte, ubyte : Extend value into EAX and return
1399 /// ret short, ushort: Extend value into EAX and return
1400 /// ret int, uint : Move value into EAX and return
1401 /// ret pointer : Move value into EAX and return
1402 /// ret long, ulong : Move value into EAX/EDX and return
1403 /// ret float/double : Top of FP stack
1405 void X86ISel::visitReturnInst(ReturnInst &I) {
1406 if (I.getNumOperands() == 0) {
1407 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1411 Value *RetVal = I.getOperand(0);
1412 switch (getClassB(RetVal->getType())) {
1413 case cByte: // integral return values: extend or move into EAX and return
1416 promote32(X86::EAX, ValueRecord(RetVal));
1417 // Declare that EAX is live on exit
1418 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
1420 case cFP: { // Floats & Doubles: Return in ST(0)
1421 unsigned RetReg = getReg(RetVal);
1422 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
1423 // Declare that top-of-stack is live on exit
1424 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
1428 unsigned RetReg = getReg(RetVal);
1429 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1430 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
1431 // Declare that EAX & EDX are live on exit
1432 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1437 visitInstruction(I);
1439 // Emit a 'ret' instruction
1440 BuildMI(BB, X86::RET, 0);
1443 // getBlockAfter - Return the basic block which occurs lexically after the
1445 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1446 Function::iterator I = BB; ++I; // Get iterator to next block
1447 return I != BB->getParent()->end() ? &*I : 0;
1450 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1451 /// that since code layout is frozen at this point, that if we are trying to
1452 /// jump to a block that is the immediate successor of the current block, we can
1453 /// just make a fall-through (but we don't currently).
1455 void X86ISel::visitBranchInst(BranchInst &BI) {
1456 // Update machine-CFG edges
1457 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1458 if (BI.isConditional())
1459 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1461 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1463 if (!BI.isConditional()) { // Unconditional branch?
1464 if (BI.getSuccessor(0) != NextBB)
1465 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1469 // See if we can fold the setcc into the branch itself...
1470 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1472 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1473 // computed some other way...
1474 unsigned condReg = getReg(BI.getCondition());
1475 BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
1476 if (BI.getSuccessor(1) == NextBB) {
1477 if (BI.getSuccessor(0) != NextBB)
1478 BuildMI(BB, X86::JNE, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1480 BuildMI(BB, X86::JE, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1482 if (BI.getSuccessor(0) != NextBB)
1483 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1488 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1489 MachineBasicBlock::iterator MII = BB->end();
1490 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1492 const Type *CompTy = SCI->getOperand(0)->getType();
1493 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1496 // LLVM -> X86 signed X86 unsigned
1497 // ----- ---------- ------------
1505 // js // Used by comparison with 0 optimization
1508 static const unsigned OpcodeTab[2][8] = {
1509 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1510 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1511 X86::JS, X86::JNS },
1514 if (BI.getSuccessor(0) != NextBB) {
1515 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1516 .addMBB(MBBMap[BI.getSuccessor(0)]);
1517 if (BI.getSuccessor(1) != NextBB)
1518 BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1520 // Change to the inverse condition...
1521 if (BI.getSuccessor(1) != NextBB) {
1523 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
1524 .addMBB(MBBMap[BI.getSuccessor(1)]);
1530 /// doCall - This emits an abstract call instruction, setting up the arguments
1531 /// and the return value as appropriate. For the actual function call itself,
1532 /// it inserts the specified CallMI instruction into the stream.
1534 void X86ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1535 const std::vector<ValueRecord> &Args) {
1536 // Count how many bytes are to be pushed on the stack...
1537 unsigned NumBytes = 0;
1539 if (!Args.empty()) {
1540 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1541 switch (getClassB(Args[i].Ty)) {
1542 case cByte: case cShort: case cInt:
1543 NumBytes += 4; break;
1545 NumBytes += 8; break;
1547 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1549 default: assert(0 && "Unknown class!");
1552 // Adjust the stack pointer for the new arguments...
1553 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1555 // Arguments go on the stack in reverse order, as specified by the ABI.
1556 unsigned ArgOffset = 0;
1557 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1559 switch (getClassB(Args[i].Ty)) {
1561 if (Args[i].Val && isa<ConstantBool>(Args[i].Val)) {
1562 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1563 .addImm(Args[i].Val == ConstantBool::True);
1568 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1569 // Zero/Sign extend constant, then stuff into memory.
1570 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1571 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1572 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1573 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1575 // Promote arg to 32 bits wide into a temporary register...
1576 ArgReg = makeAnotherReg(Type::UIntTy);
1577 promote32(ArgReg, Args[i]);
1578 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1579 X86::ESP, ArgOffset).addReg(ArgReg);
1583 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1584 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1585 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1586 X86::ESP, ArgOffset).addImm(Val);
1587 } else if (Args[i].Val && isa<ConstantPointerNull>(Args[i].Val)) {
1588 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1589 X86::ESP, ArgOffset).addImm(0);
1591 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1592 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1593 X86::ESP, ArgOffset).addReg(ArgReg);
1597 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1598 uint64_t Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1599 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1600 X86::ESP, ArgOffset).addImm(Val & ~0U);
1601 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1602 X86::ESP, ArgOffset+4).addImm(Val >> 32ULL);
1604 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1605 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1606 X86::ESP, ArgOffset).addReg(ArgReg);
1607 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1608 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1610 ArgOffset += 4; // 8 byte entry, not 4.
1614 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1615 if (Args[i].Ty == Type::FloatTy) {
1616 addRegOffset(BuildMI(BB, X86::FST32m, 5),
1617 X86::ESP, ArgOffset).addReg(ArgReg);
1619 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1620 addRegOffset(BuildMI(BB, X86::FST64m, 5),
1621 X86::ESP, ArgOffset).addReg(ArgReg);
1622 ArgOffset += 4; // 8 byte entry, not 4.
1626 default: assert(0 && "Unknown class!");
1631 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
1634 BB->push_back(CallMI);
1636 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
1638 // If there is a return value, scavenge the result from the location the call
1641 if (Ret.Ty != Type::VoidTy) {
1642 unsigned DestClass = getClassB(Ret.Ty);
1643 switch (DestClass) {
1647 // Integral results are in %eax, or the appropriate portion
1649 static const unsigned regRegMove[] = {
1650 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
1652 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1653 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1656 case cFP: // Floating-point return values live in %ST(0)
1657 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1659 case cLong: // Long values are left in EDX:EAX
1660 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1661 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
1663 default: assert(0 && "Unknown class!");
1669 /// visitCallInst - Push args on stack and do a procedure call instruction.
1670 void X86ISel::visitCallInst(CallInst &CI) {
1671 MachineInstr *TheCall;
1672 if (Function *F = CI.getCalledFunction()) {
1673 // Is it an intrinsic function call?
1674 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1675 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1679 // Emit a CALL instruction with PC-relative displacement.
1680 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1681 } else { // Emit an indirect call...
1682 unsigned Reg = getReg(CI.getCalledValue());
1683 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
1686 std::vector<ValueRecord> Args;
1687 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1688 Args.push_back(ValueRecord(CI.getOperand(i)));
1690 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1691 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1694 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1695 /// function, lowering any calls to unknown intrinsic functions into the
1696 /// equivalent LLVM code.
1698 void X86ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1699 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1700 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1701 if (CallInst *CI = dyn_cast<CallInst>(I++))
1702 if (Function *F = CI->getCalledFunction())
1703 switch (F->getIntrinsicID()) {
1704 case Intrinsic::not_intrinsic:
1705 case Intrinsic::vastart:
1706 case Intrinsic::vacopy:
1707 case Intrinsic::vaend:
1708 case Intrinsic::returnaddress:
1709 case Intrinsic::frameaddress:
1710 case Intrinsic::memcpy:
1711 case Intrinsic::memset:
1712 case Intrinsic::isunordered:
1713 case Intrinsic::readport:
1714 case Intrinsic::writeport:
1715 // We directly implement these intrinsics
1717 case Intrinsic::readio: {
1718 // On X86, memory operations are in-order. Lower this intrinsic
1719 // into a volatile load.
1720 Instruction *Before = CI->getPrev();
1721 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1722 CI->replaceAllUsesWith(LI);
1723 BB->getInstList().erase(CI);
1726 case Intrinsic::writeio: {
1727 // On X86, memory operations are in-order. Lower this intrinsic
1728 // into a volatile store.
1729 Instruction *Before = CI->getPrev();
1730 StoreInst *LI = new StoreInst(CI->getOperand(1),
1731 CI->getOperand(2), true, CI);
1732 CI->replaceAllUsesWith(LI);
1733 BB->getInstList().erase(CI);
1737 // All other intrinsic calls we must lower.
1738 Instruction *Before = CI->getPrev();
1739 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1740 if (Before) { // Move iterator to instruction after call
1748 void X86ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1749 unsigned TmpReg1, TmpReg2;
1751 case Intrinsic::vastart:
1752 // Get the address of the first vararg value...
1753 TmpReg1 = getReg(CI);
1754 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
1757 case Intrinsic::vacopy:
1758 TmpReg1 = getReg(CI);
1759 TmpReg2 = getReg(CI.getOperand(1));
1760 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
1762 case Intrinsic::vaend: return; // Noop on X86
1764 case Intrinsic::returnaddress:
1765 case Intrinsic::frameaddress:
1766 TmpReg1 = getReg(CI);
1767 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1768 if (ID == Intrinsic::returnaddress) {
1769 // Just load the return address
1770 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
1771 ReturnAddressIndex);
1773 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
1774 ReturnAddressIndex, -4);
1777 // Values other than zero are not implemented yet.
1778 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
1782 case Intrinsic::isunordered:
1783 TmpReg1 = getReg(CI.getOperand(1));
1784 TmpReg2 = getReg(CI.getOperand(2));
1785 emitUCOMr(BB, BB->end(), TmpReg2, TmpReg1);
1786 TmpReg2 = getReg(CI);
1787 BuildMI(BB, X86::SETPr, 0, TmpReg2);
1790 case Intrinsic::memcpy: {
1791 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1793 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1794 Align = AlignC->getRawValue();
1795 if (Align == 0) Align = 1;
1798 // Turn the byte code into # iterations
1801 switch (Align & 3) {
1802 case 2: // WORD aligned
1803 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1804 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1806 CountReg = makeAnotherReg(Type::IntTy);
1807 unsigned ByteReg = getReg(CI.getOperand(3));
1808 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1810 Opcode = X86::REP_MOVSW;
1812 case 0: // DWORD aligned
1813 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1814 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1816 CountReg = makeAnotherReg(Type::IntTy);
1817 unsigned ByteReg = getReg(CI.getOperand(3));
1818 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1820 Opcode = X86::REP_MOVSD;
1822 default: // BYTE aligned
1823 CountReg = getReg(CI.getOperand(3));
1824 Opcode = X86::REP_MOVSB;
1828 // No matter what the alignment is, we put the source in ESI, the
1829 // destination in EDI, and the count in ECX.
1830 TmpReg1 = getReg(CI.getOperand(1));
1831 TmpReg2 = getReg(CI.getOperand(2));
1832 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1833 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1834 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
1835 BuildMI(BB, Opcode, 0);
1838 case Intrinsic::memset: {
1839 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1841 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1842 Align = AlignC->getRawValue();
1843 if (Align == 0) Align = 1;
1846 // Turn the byte code into # iterations
1849 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1850 unsigned Val = ValC->getRawValue() & 255;
1852 // If the value is a constant, then we can potentially use larger copies.
1853 switch (Align & 3) {
1854 case 2: // WORD aligned
1855 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1856 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1858 CountReg = makeAnotherReg(Type::IntTy);
1859 unsigned ByteReg = getReg(CI.getOperand(3));
1860 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1862 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
1863 Opcode = X86::REP_STOSW;
1865 case 0: // DWORD aligned
1866 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1867 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1869 CountReg = makeAnotherReg(Type::IntTy);
1870 unsigned ByteReg = getReg(CI.getOperand(3));
1871 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1873 Val = (Val << 8) | Val;
1874 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
1875 Opcode = X86::REP_STOSD;
1877 default: // BYTE aligned
1878 CountReg = getReg(CI.getOperand(3));
1879 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
1880 Opcode = X86::REP_STOSB;
1884 // If it's not a constant value we are storing, just fall back. We could
1885 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1886 unsigned ValReg = getReg(CI.getOperand(2));
1887 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1888 CountReg = getReg(CI.getOperand(3));
1889 Opcode = X86::REP_STOSB;
1892 // No matter what the alignment is, we put the source in ESI, the
1893 // destination in EDI, and the count in ECX.
1894 TmpReg1 = getReg(CI.getOperand(1));
1895 //TmpReg2 = getReg(CI.getOperand(2));
1896 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1897 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1898 BuildMI(BB, Opcode, 0);
1902 case Intrinsic::readport: {
1903 // First, determine that the size of the operand falls within the acceptable
1904 // range for this architecture.
1906 if (getClassB(CI.getOperand(1)->getType()) != cShort) {
1907 std::cerr << "llvm.readport: Address size is not 16 bits\n";
1911 // Now, move the I/O port address into the DX register and use the IN
1912 // instruction to get the input data.
1914 unsigned Class = getClass(CI.getCalledFunction()->getReturnType());
1915 unsigned DestReg = getReg(CI);
1917 // If the port is a single-byte constant, use the immediate form.
1918 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(1)))
1919 if ((C->getRawValue() & 255) == C->getRawValue()) {
1922 BuildMI(BB, X86::IN8ri, 1).addImm((unsigned char)C->getRawValue());
1923 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1926 BuildMI(BB, X86::IN16ri, 1).addImm((unsigned char)C->getRawValue());
1927 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1930 BuildMI(BB, X86::IN32ri, 1).addImm((unsigned char)C->getRawValue());
1931 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1936 unsigned Reg = getReg(CI.getOperand(1));
1937 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1940 BuildMI(BB, X86::IN8rr, 0);
1941 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1944 BuildMI(BB, X86::IN16rr, 0);
1945 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1948 BuildMI(BB, X86::IN32rr, 0);
1949 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1952 std::cerr << "Cannot do input on this data type";
1958 case Intrinsic::writeport: {
1959 // First, determine that the size of the operand falls within the
1960 // acceptable range for this architecture.
1961 if (getClass(CI.getOperand(2)->getType()) != cShort) {
1962 std::cerr << "llvm.writeport: Address size is not 16 bits\n";
1966 unsigned Class = getClassB(CI.getOperand(1)->getType());
1967 unsigned ValReg = getReg(CI.getOperand(1));
1970 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1973 BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(ValReg);
1976 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(ValReg);
1979 std::cerr << "llvm.writeport: invalid data type for X86 target";
1984 // If the port is a single-byte constant, use the immediate form.
1985 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(2)))
1986 if ((C->getRawValue() & 255) == C->getRawValue()) {
1987 static const unsigned O[] = { X86::OUT8ir, X86::OUT16ir, X86::OUT32ir };
1988 BuildMI(BB, O[Class], 1).addImm((unsigned char)C->getRawValue());
1992 // Otherwise, move the I/O port address into the DX register and the value
1993 // to write into the AL/AX/EAX register.
1994 static const unsigned Opc[] = { X86::OUT8rr, X86::OUT16rr, X86::OUT32rr };
1995 unsigned Reg = getReg(CI.getOperand(2));
1996 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1997 BuildMI(BB, Opc[Class], 0);
2001 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
2005 static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
2006 if (LI.getParent() != User.getParent())
2008 BasicBlock::iterator It = &LI;
2009 // Check all of the instructions between the load and the user. We should
2010 // really use alias analysis here, but for now we just do something simple.
2011 for (++It; It != BasicBlock::iterator(&User); ++It) {
2012 switch (It->getOpcode()) {
2013 case Instruction::Free:
2014 case Instruction::Store:
2015 case Instruction::Call:
2016 case Instruction::Invoke:
2018 case Instruction::Load:
2019 if (cast<LoadInst>(It)->isVolatile() && LI.isVolatile())
2027 /// visitSimpleBinary - Implement simple binary operators for integral types...
2028 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
2031 void X86ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
2032 unsigned DestReg = getReg(B);
2033 MachineBasicBlock::iterator MI = BB->end();
2034 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
2035 unsigned Class = getClassB(B.getType());
2037 // If this is AND X, C, and it is only used by a setcc instruction, it will
2038 // be folded. There is no need to emit this instruction.
2039 if (B.hasOneUse() && OperatorClass == 2 && isa<ConstantInt>(Op1))
2040 if (Class == cByte || Class == cShort || Class == cInt) {
2041 Instruction *Use = cast<Instruction>(B.use_back());
2042 if (isa<SetCondInst>(Use) &&
2043 Use->getOperand(1) == Constant::getNullValue(B.getType())) {
2044 switch (getSetCCNumber(Use->getOpcode())) {
2049 if (B.getType()->isSigned()) return;
2054 // Special case: op Reg, load [mem]
2055 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1) && Class != cLong &&
2057 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B))
2058 if (!B.swapOperands())
2059 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
2061 if (isa<LoadInst>(Op1) && Class != cLong && Op1->hasOneUse() &&
2062 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
2066 static const unsigned OpcodeTab[][3] = {
2067 // Arithmetic operators
2068 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
2069 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
2071 // Bitwise operators
2072 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
2073 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
2074 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
2076 Opcode = OpcodeTab[OperatorClass][Class];
2078 static const unsigned OpcodeTab[][2] = {
2079 { X86::FADD32m, X86::FADD64m }, // ADD
2080 { X86::FSUB32m, X86::FSUB64m }, // SUB
2082 const Type *Ty = Op0->getType();
2083 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2084 Opcode = OpcodeTab[OperatorClass][Ty == Type::DoubleTy];
2087 unsigned Op0r = getReg(Op0);
2088 if (AllocaInst *AI =
2089 dyn_castFixedAlloca(cast<LoadInst>(Op1)->getOperand(0))) {
2090 unsigned FI = getFixedSizedAllocaFI(AI);
2091 addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), FI);
2095 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), AM);
2097 addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), AM);
2102 // If this is a floating point subtract, check to see if we can fold the first
2104 if (Class == cFP && OperatorClass == 1 &&
2105 isa<LoadInst>(Op0) &&
2106 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B)) {
2107 const Type *Ty = Op0->getType();
2108 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2109 unsigned Opcode = Ty == Type::FloatTy ? X86::FSUBR32m : X86::FSUBR64m;
2111 unsigned Op1r = getReg(Op1);
2112 if (AllocaInst *AI =
2113 dyn_castFixedAlloca(cast<LoadInst>(Op0)->getOperand(0))) {
2114 unsigned FI = getFixedSizedAllocaFI(AI);
2115 addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), FI);
2118 getAddressingMode(cast<LoadInst>(Op0)->getOperand(0), AM);
2120 addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), AM);
2125 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
2129 /// emitBinaryFPOperation - This method handles emission of floating point
2130 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
2131 void X86ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
2132 MachineBasicBlock::iterator IP,
2133 Value *Op0, Value *Op1,
2134 unsigned OperatorClass, unsigned DestReg) {
2135 // Special case: op Reg, <const fp>
2136 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1))
2137 if (!Op1C->isExactlyValue(+0.0) && !Op1C->isExactlyValue(+1.0)) {
2138 // Create a constant pool entry for this constant.
2139 MachineConstantPool *CP = F->getConstantPool();
2140 unsigned CPI = CP->getConstantPoolIndex(Op1C);
2141 const Type *Ty = Op1->getType();
2143 static const unsigned OpcodeTab[][4] = {
2144 { X86::FADD32m, X86::FSUB32m, X86::FMUL32m, X86::FDIV32m }, // Float
2145 { X86::FADD64m, X86::FSUB64m, X86::FMUL64m, X86::FDIV64m }, // Double
2148 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
2149 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2150 unsigned Op0r = getReg(Op0, BB, IP);
2151 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2152 DestReg).addReg(Op0r), CPI);
2156 // Special case: R1 = op <const fp>, R2
2157 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
2158 if (CFP->isExactlyValue(-0.0) && OperatorClass == 1) {
2160 unsigned op1Reg = getReg(Op1, BB, IP);
2161 BuildMI(*BB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
2163 } else if (!CFP->isExactlyValue(+0.0) && !CFP->isExactlyValue(+1.0)) {
2164 // R1 = op CST, R2 --> R1 = opr R2, CST
2166 // Create a constant pool entry for this constant.
2167 MachineConstantPool *CP = F->getConstantPool();
2168 unsigned CPI = CP->getConstantPoolIndex(CFP);
2169 const Type *Ty = CFP->getType();
2171 static const unsigned OpcodeTab[][4] = {
2172 { X86::FADD32m, X86::FSUBR32m, X86::FMUL32m, X86::FDIVR32m }, // Float
2173 { X86::FADD64m, X86::FSUBR64m, X86::FMUL64m, X86::FDIVR64m }, // Double
2176 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2177 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
2178 unsigned Op1r = getReg(Op1, BB, IP);
2179 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
2180 DestReg).addReg(Op1r), CPI);
2185 static const unsigned OpcodeTab[4] = {
2186 X86::FpADD, X86::FpSUB, X86::FpMUL, X86::FpDIV
2189 unsigned Opcode = OpcodeTab[OperatorClass];
2190 unsigned Op0r = getReg(Op0, BB, IP);
2191 unsigned Op1r = getReg(Op1, BB, IP);
2192 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2195 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
2196 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
2199 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
2200 /// and constant expression support.
2202 void X86ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
2203 MachineBasicBlock::iterator IP,
2204 Value *Op0, Value *Op1,
2205 unsigned OperatorClass,
2207 unsigned Class = getClassB(Op0->getType());
2210 assert(OperatorClass < 2 && "No logical ops for FP!");
2211 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
2215 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
2216 if (OperatorClass == 1) {
2217 static unsigned const NEGTab[] = {
2218 X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
2221 // sub 0, X -> neg X
2222 if (CI->isNullValue()) {
2223 unsigned op1Reg = getReg(Op1, MBB, IP);
2224 BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
2226 if (Class == cLong) {
2227 // We just emitted: Dl = neg Sl
2228 // Now emit : T = addc Sh, 0
2230 unsigned T = makeAnotherReg(Type::IntTy);
2231 BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
2232 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
2235 } else if (Op1->hasOneUse() && Class != cLong) {
2236 // sub C, X -> tmp = neg X; DestReg = add tmp, C. This is better
2237 // than copying C into a temporary register, because of register
2238 // pressure (tmp and destreg can share a register.
2239 static unsigned const ADDRITab[] = {
2240 X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri
2242 unsigned op1Reg = getReg(Op1, MBB, IP);
2243 unsigned Tmp = makeAnotherReg(Op0->getType());
2244 BuildMI(*MBB, IP, NEGTab[Class], 1, Tmp).addReg(op1Reg);
2245 BuildMI(*MBB, IP, ADDRITab[Class], 2,
2246 DestReg).addReg(Tmp).addImm(CI->getRawValue());
2251 // Special case: op Reg, <const int>
2252 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
2253 unsigned Op0r = getReg(Op0, MBB, IP);
2255 // xor X, -1 -> not X
2256 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
2257 static unsigned const NOTTab[] = {
2258 X86::NOT8r, X86::NOT16r, X86::NOT32r, 0, X86::NOT32r
2260 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
2261 if (Class == cLong) // Invert the top part too
2262 BuildMI(*MBB, IP, X86::NOT32r, 1, DestReg+1).addReg(Op0r+1);
2266 // add X, -1 -> dec X
2267 if (OperatorClass == 0 && Op1C->isAllOnesValue() && Class != cLong) {
2268 // Note that we can't use dec for 64-bit decrements, because it does not
2269 // set the carry flag!
2270 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
2271 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
2275 // add X, 1 -> inc X
2276 if (OperatorClass == 0 && Op1C->equalsInt(1) && Class != cLong) {
2277 // Note that we can't use inc for 64-bit increments, because it does not
2278 // set the carry flag!
2279 static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
2280 BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
2284 static const unsigned OpcodeTab[][5] = {
2285 // Arithmetic operators
2286 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri }, // ADD
2287 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri }, // SUB
2289 // Bitwise operators
2290 { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri }, // AND
2291 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri }, // OR
2292 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri }, // XOR
2295 unsigned Opcode = OpcodeTab[OperatorClass][Class];
2296 unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
2298 if (Class != cLong) {
2299 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2303 // If this is a long value and the high or low bits have a special
2304 // property, emit some special cases.
2305 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
2307 // If the constant is zero in the low 32-bits, just copy the low part
2308 // across and apply the normal 32-bit operation to the high parts. There
2309 // will be no carry or borrow into the top.
2311 if (OperatorClass != 2) // All but and...
2312 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0r);
2314 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2315 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg+1)
2316 .addReg(Op0r+1).addImm(Op1h);
2320 // If this is a logical operation and the top 32-bits are zero, just
2321 // operate on the lower 32.
2322 if (Op1h == 0 && OperatorClass > 1) {
2323 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg)
2324 .addReg(Op0r).addImm(Op1l);
2325 if (OperatorClass != 2) // All but and
2326 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(Op0r+1);
2328 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2332 // TODO: We could handle lots of other special cases here, such as AND'ing
2333 // with 0xFFFFFFFF00000000 -> noop, etc.
2335 // Otherwise, code generate the full operation with a constant.
2336 static const unsigned TopTab[] = {
2337 X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
2340 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2341 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
2342 .addReg(Op0r+1).addImm(Op1h);
2346 // Finally, handle the general case now.
2347 static const unsigned OpcodeTab[][5] = {
2348 // Arithmetic operators
2349 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, 0, X86::ADD32rr }, // ADD
2350 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, 0, X86::SUB32rr }, // SUB
2352 // Bitwise operators
2353 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr }, // AND
2354 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr }, // OR
2355 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr }, // XOR
2358 unsigned Opcode = OpcodeTab[OperatorClass][Class];
2359 unsigned Op0r = getReg(Op0, MBB, IP);
2360 unsigned Op1r = getReg(Op1, MBB, IP);
2361 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2363 if (Class == cLong) { // Handle the upper 32 bits of long values...
2364 static const unsigned TopTab[] = {
2365 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
2367 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
2368 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2372 /// doMultiply - Emit appropriate instructions to multiply together the
2373 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
2374 /// result should be given as DestTy.
2376 void X86ISel::doMultiply(MachineBasicBlock *MBB,
2377 MachineBasicBlock::iterator MBBI,
2378 unsigned DestReg, const Type *DestTy,
2379 unsigned op0Reg, unsigned op1Reg) {
2380 unsigned Class = getClass(DestTy);
2384 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
2385 .addReg(op0Reg).addReg(op1Reg);
2388 // Must use the MUL instruction, which forces use of AL...
2389 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
2390 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
2391 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
2394 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
2398 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
2399 // returns zero when the input is not exactly a power of two.
2400 static unsigned ExactLog2(unsigned Val) {
2401 if (Val == 0 || (Val & (Val-1))) return 0;
2411 /// doMultiplyConst - This function is specialized to efficiently codegen an 8,
2412 /// 16, or 32-bit integer multiply by a constant.
2413 void X86ISel::doMultiplyConst(MachineBasicBlock *MBB,
2414 MachineBasicBlock::iterator IP,
2415 unsigned DestReg, const Type *DestTy,
2416 unsigned op0Reg, unsigned ConstRHS) {
2417 static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
2418 static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
2419 static const unsigned ADDrrTab[] = {X86::ADD8rr, X86::ADD16rr, X86::ADD32rr};
2420 static const unsigned NEGrTab[] = {X86::NEG8r , X86::NEG16r , X86::NEG32r };
2422 unsigned Class = getClass(DestTy);
2425 // Handle special cases here.
2428 TmpReg = makeAnotherReg(DestTy);
2429 BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
2430 BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(TmpReg).addReg(TmpReg);
2433 BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(op0Reg);
2436 BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
2439 BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
2442 BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(op0Reg).addReg(op0Reg);
2447 if (Class == cInt) {
2449 AM.BaseType = X86AddressMode::RegBase;
2450 AM.Base.Reg = op0Reg;
2451 AM.Scale = ConstRHS-1;
2452 AM.IndexReg = op0Reg;
2454 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, DestReg), AM);
2460 if (Class == cInt) {
2461 TmpReg = makeAnotherReg(DestTy);
2463 AM.BaseType = X86AddressMode::RegBase;
2464 AM.Base.Reg = op0Reg;
2465 AM.Scale = -ConstRHS-1;
2466 AM.IndexReg = op0Reg;
2468 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TmpReg), AM);
2469 BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(TmpReg);
2474 // If the element size is exactly a power of 2, use a shift to get it.
2475 if (unsigned Shift = ExactLog2(ConstRHS)) {
2477 default: assert(0 && "Unknown class for this function!");
2479 BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2482 BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2485 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2490 // If the element size is a negative power of 2, use a shift/neg to get it.
2491 if (unsigned Shift = ExactLog2(-ConstRHS)) {
2492 TmpReg = makeAnotherReg(DestTy);
2493 BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
2495 default: assert(0 && "Unknown class for this function!");
2497 BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2500 BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2503 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
2508 if (Class == cShort) {
2509 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
2511 } else if (Class == cInt) {
2512 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
2516 // Most general case, emit a normal multiply...
2517 TmpReg = makeAnotherReg(DestTy);
2518 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
2520 // Emit a MUL to multiply the register holding the index by
2521 // elementSize, putting the result in OffsetReg.
2522 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
2525 /// visitMul - Multiplies are not simple binary operators because they must deal
2526 /// with the EAX register explicitly.
2528 void X86ISel::visitMul(BinaryOperator &I) {
2529 unsigned ResultReg = getReg(I);
2531 Value *Op0 = I.getOperand(0);
2532 Value *Op1 = I.getOperand(1);
2534 // Fold loads into floating point multiplies.
2535 if (getClass(Op0->getType()) == cFP) {
2536 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
2537 if (!I.swapOperands())
2538 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
2539 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2540 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2541 const Type *Ty = Op0->getType();
2542 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2543 unsigned Opcode = Ty == Type::FloatTy ? X86::FMUL32m : X86::FMUL64m;
2545 unsigned Op0r = getReg(Op0);
2546 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2547 unsigned FI = getFixedSizedAllocaFI(AI);
2548 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2551 getAddressingMode(LI->getOperand(0), AM);
2553 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
2559 MachineBasicBlock::iterator IP = BB->end();
2560 emitMultiply(BB, IP, Op0, Op1, ResultReg);
2563 void X86ISel::emitMultiply(MachineBasicBlock *MBB,
2564 MachineBasicBlock::iterator IP,
2565 Value *Op0, Value *Op1, unsigned DestReg) {
2566 MachineBasicBlock &BB = *MBB;
2567 TypeClass Class = getClass(Op0->getType());
2569 // Simple scalar multiply?
2570 unsigned Op0Reg = getReg(Op0, &BB, IP);
2575 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2576 unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
2577 doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
2579 unsigned Op1Reg = getReg(Op1, &BB, IP);
2580 doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
2584 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2590 // Long value. We have to do things the hard way...
2591 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2592 unsigned CLow = CI->getRawValue();
2593 unsigned CHi = CI->getRawValue() >> 32;
2596 // If the low part of the constant is all zeros, things are simple.
2597 BuildMI(BB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2598 doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
2602 // Multiply the two low parts... capturing carry into EDX
2603 unsigned OverflowReg = 0;
2605 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
2607 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2608 OverflowReg = makeAnotherReg(Type::UIntTy);
2609 BuildMI(BB, IP, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
2610 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2611 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1RegL); // AL*BL
2613 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2614 BuildMI(BB, IP, X86::MOV32rr, 1,
2615 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2618 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2619 doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
2621 unsigned AHBLplusOverflowReg;
2623 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2624 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2625 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2627 AHBLplusOverflowReg = AHBLReg;
2631 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
2633 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2634 doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
2636 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2637 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2642 // General 64x64 multiply
2644 unsigned Op1Reg = getReg(Op1, &BB, IP);
2645 // Multiply the two low parts... capturing carry into EDX
2646 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2647 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
2649 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2650 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2651 BuildMI(BB, IP, X86::MOV32rr, 1,
2652 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2654 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2655 BuildMI(BB, IP, X86::IMUL32rr, 2,
2656 AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2658 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2659 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2660 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2662 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2663 BuildMI(BB, IP, X86::IMUL32rr, 2,
2664 ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2666 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2667 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2671 /// visitDivRem - Handle division and remainder instructions... these
2672 /// instruction both require the same instructions to be generated, they just
2673 /// select the result from a different register. Note that both of these
2674 /// instructions work differently for signed and unsigned operands.
2676 void X86ISel::visitDivRem(BinaryOperator &I) {
2677 unsigned ResultReg = getReg(I);
2678 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2680 // Fold loads into floating point divides.
2681 if (getClass(Op0->getType()) == cFP) {
2682 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2683 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2684 const Type *Ty = Op0->getType();
2685 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2686 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIV32m : X86::FDIV64m;
2688 unsigned Op0r = getReg(Op0);
2689 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2690 unsigned FI = getFixedSizedAllocaFI(AI);
2691 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
2694 getAddressingMode(LI->getOperand(0), AM);
2696 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
2701 if (LoadInst *LI = dyn_cast<LoadInst>(Op0))
2702 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2703 const Type *Ty = Op0->getType();
2704 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2705 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIVR32m : X86::FDIVR64m;
2707 unsigned Op1r = getReg(Op1);
2708 if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
2709 unsigned FI = getFixedSizedAllocaFI(AI);
2710 addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), FI);
2713 getAddressingMode(LI->getOperand(0), AM);
2714 addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), AM);
2721 MachineBasicBlock::iterator IP = BB->end();
2722 emitDivRemOperation(BB, IP, Op0, Op1,
2723 I.getOpcode() == Instruction::Div, ResultReg);
2726 void X86ISel::emitDivRemOperation(MachineBasicBlock *BB,
2727 MachineBasicBlock::iterator IP,
2728 Value *Op0, Value *Op1, bool isDiv,
2729 unsigned ResultReg) {
2730 const Type *Ty = Op0->getType();
2731 unsigned Class = getClass(Ty);
2733 case cFP: // Floating point divide
2735 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2737 } else { // Floating point remainder...
2738 unsigned Op0Reg = getReg(Op0, BB, IP);
2739 unsigned Op1Reg = getReg(Op1, BB, IP);
2740 MachineInstr *TheCall =
2741 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
2742 std::vector<ValueRecord> Args;
2743 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2744 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2745 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
2749 static const char *FnName[] =
2750 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
2751 unsigned Op0Reg = getReg(Op0, BB, IP);
2752 unsigned Op1Reg = getReg(Op1, BB, IP);
2753 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2754 MachineInstr *TheCall =
2755 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
2757 std::vector<ValueRecord> Args;
2758 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2759 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2760 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
2763 case cByte: case cShort: case cInt:
2764 break; // Small integrals, handled below...
2765 default: assert(0 && "Unknown class!");
2768 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
2769 static const unsigned NEGOpcode[]={ X86::NEG8r, X86::NEG16r, X86::NEG32r };
2770 static const unsigned SAROpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
2771 static const unsigned SHROpcode[]={ X86::SHR8ri, X86::SHR16ri, X86::SHR32ri };
2772 static const unsigned ADDOpcode[]={ X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
2774 // Special case signed division by power of 2.
2775 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1))
2777 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2778 int V = CI->getValue();
2780 if (V == 1) { // X /s 1 => X
2781 unsigned Op0Reg = getReg(Op0, BB, IP);
2782 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2786 if (V == -1) { // X /s -1 => -X
2787 unsigned Op0Reg = getReg(Op0, BB, IP);
2788 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2792 if (V == 2 || V == -2) { // X /s 2
2793 static const unsigned CMPOpcode[] = {
2794 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
2796 static const unsigned SBBOpcode[] = {
2797 X86::SBB8ri, X86::SBB16ri, X86::SBB32ri
2799 unsigned Op0Reg = getReg(Op0, BB, IP);
2800 unsigned SignBit = 1 << (CI->getType()->getPrimitiveSize()*8-1);
2801 BuildMI(*BB, IP, CMPOpcode[Class], 2).addReg(Op0Reg).addImm(SignBit);
2803 unsigned TmpReg = makeAnotherReg(Op0->getType());
2804 BuildMI(*BB, IP, SBBOpcode[Class], 2, TmpReg).addReg(Op0Reg).addImm(-1);
2806 unsigned TmpReg2 = V == 2 ? ResultReg : makeAnotherReg(Op0->getType());
2807 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg2).addReg(TmpReg).addImm(1);
2809 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg2);
2815 if (V < 0) { // Not a positive power of 2?
2817 isNeg = true; // Maybe it's a negative power of 2.
2819 if (unsigned Log = ExactLog2(V)) {
2821 unsigned Op0Reg = getReg(Op0, BB, IP);
2822 unsigned TmpReg = makeAnotherReg(Op0->getType());
2823 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg)
2824 .addReg(Op0Reg).addImm(Log-1);
2825 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2826 BuildMI(*BB, IP, SHROpcode[Class], 2, TmpReg2)
2827 .addReg(TmpReg).addImm(32-Log);
2828 unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2829 BuildMI(*BB, IP, ADDOpcode[Class], 2, TmpReg3)
2830 .addReg(Op0Reg).addReg(TmpReg2);
2832 unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2833 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg4)
2834 .addReg(TmpReg3).addImm(Log);
2836 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg4);
2840 assert(Class != cLong && "This doesn't handle 64-bit remainder!");
2841 int V = CI->getValue();
2843 if (V == 2 || V == -2) { // X % 2, X % -2
2844 static const unsigned SExtOpcode[] = { X86::CBW, X86::CWD, X86::CDQ };
2845 static const unsigned BaseReg[] = { X86::AL , X86::AX , X86::EAX };
2846 static const unsigned SExtReg[] = { X86::AH , X86::DX , X86::EDX };
2847 static const unsigned ANDOpcode[] = {
2848 X86::AND8ri, X86::AND16ri, X86::AND32ri
2850 static const unsigned XOROpcode[] = {
2851 X86::XOR8rr, X86::XOR16rr, X86::XOR32rr
2853 static const unsigned SUBOpcode[] = {
2854 X86::SUB8rr, X86::SUB16rr, X86::SUB32rr
2857 // Sign extend result into reg of -1 or 0.
2858 unsigned Op0Reg = getReg(Op0, BB, IP);
2859 BuildMI(*BB, IP, MovOpcode[Class], 1, BaseReg[Class]).addReg(Op0Reg);
2860 BuildMI(*BB, IP, SExtOpcode[Class], 0);
2861 unsigned TmpReg0 = makeAnotherReg(Op0->getType());
2862 BuildMI(*BB, IP, MovOpcode[Class], 1, TmpReg0).addReg(SExtReg[Class]);
2864 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2865 BuildMI(*BB, IP, ANDOpcode[Class], 2, TmpReg1).addReg(Op0Reg).addImm(1);
2867 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2868 BuildMI(*BB, IP, XOROpcode[Class], 2,
2869 TmpReg2).addReg(TmpReg1).addReg(TmpReg0);
2870 BuildMI(*BB, IP, SUBOpcode[Class], 2,
2871 ResultReg).addReg(TmpReg2).addReg(TmpReg0);
2876 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
2877 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
2878 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
2880 static const unsigned DivOpcode[][4] = {
2881 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
2882 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
2885 unsigned Reg = Regs[Class];
2886 unsigned ExtReg = ExtRegs[Class];
2888 // Put the first operand into one of the A registers...
2889 unsigned Op0Reg = getReg(Op0, BB, IP);
2890 unsigned Op1Reg = getReg(Op1, BB, IP);
2891 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
2893 if (Ty->isSigned()) {
2894 // Emit a sign extension instruction...
2895 unsigned ShiftResult = makeAnotherReg(Op0->getType());
2896 BuildMI(*BB, IP, SAROpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
2897 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
2899 // Emit the appropriate divide or remainder instruction...
2900 BuildMI(*BB, IP, DivOpcode[1][Class], 1).addReg(Op1Reg);
2902 // If unsigned, emit a zeroing instruction... (reg = 0)
2903 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
2905 // Emit the appropriate divide or remainder instruction...
2906 BuildMI(*BB, IP, DivOpcode[0][Class], 1).addReg(Op1Reg);
2909 // Figure out which register we want to pick the result out of...
2910 unsigned DestReg = isDiv ? Reg : ExtReg;
2912 // Put the result into the destination register...
2913 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
2917 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2918 /// for constant immediate shift values, and for constant immediate
2919 /// shift values equal to 1. Even the general case is sort of special,
2920 /// because the shift amount has to be in CL, not just any old register.
2922 void X86ISel::visitShiftInst(ShiftInst &I) {
2923 MachineBasicBlock::iterator IP = BB->end ();
2924 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2925 I.getOpcode () == Instruction::Shl, I.getType (),
2929 /// Emit code for a 'SHLD DestReg, Op0, Op1, Amt' operation, where Amt is a
2931 void X86ISel::doSHLDConst(MachineBasicBlock *MBB,
2932 MachineBasicBlock::iterator IP,
2933 unsigned DestReg, unsigned Op0Reg, unsigned Op1Reg,
2935 // SHLD is a very inefficient operation on every processor, try to do
2936 // somethign simpler for common values of 'Amt'.
2938 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
2939 } else if (Amt == 1) {
2940 unsigned Tmp = makeAnotherReg(Type::UIntTy);
2941 BuildMI(*MBB, IP, X86::ADD32rr, 2, Tmp).addReg(Op1Reg).addReg(Op1Reg);
2942 BuildMI(*MBB, IP, X86::ADC32rr, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
2943 } else if (Amt == 2 || Amt == 3) {
2944 // On the P4 and Athlon it is cheaper to replace shld ..., 2|3 with a
2945 // shift/lea pair. NOTE: This should not be done on the P6 family!
2946 unsigned Tmp = makeAnotherReg(Type::UIntTy);
2947 BuildMI(*MBB, IP, X86::SHR32ri, 2, Tmp).addReg(Op1Reg).addImm(32-Amt);
2949 AM.BaseType = X86AddressMode::RegBase;
2951 AM.Scale = 1 << Amt;
2952 AM.IndexReg = Op0Reg;
2954 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 4, DestReg), AM);
2956 // NOTE: It is always cheaper on the P4 to emit SHLD as two shifts and an OR
2957 // than it is to emit a real SHLD.
2959 BuildMI(*MBB, IP, X86::SHLD32rri8, 3,
2960 DestReg).addReg(Op0Reg).addReg(Op1Reg).addImm(Amt);
2964 /// emitShiftOperation - Common code shared between visitShiftInst and
2965 /// constant expression support.
2966 void X86ISel::emitShiftOperation(MachineBasicBlock *MBB,
2967 MachineBasicBlock::iterator IP,
2968 Value *Op, Value *ShiftAmount,
2969 bool isLeftShift, const Type *ResultTy,
2971 unsigned SrcReg = getReg (Op, MBB, IP);
2972 bool isSigned = ResultTy->isSigned ();
2973 unsigned Class = getClass (ResultTy);
2975 static const unsigned ConstantOperand[][3] = {
2976 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri }, // SHR
2977 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri }, // SAR
2978 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri }, // SHL
2979 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri }, // SAL = SHL
2982 static const unsigned NonConstantOperand[][3] = {
2983 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
2984 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
2985 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
2986 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
2989 // Longs, as usual, are handled specially.
2990 if (Class == cLong) {
2991 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2992 unsigned Amount = CUI->getValue();
2993 if (Amount == 1 && isLeftShift) { // X << 1 == X+X
2994 BuildMI(*MBB, IP, X86::ADD32rr, 2,
2995 DestReg).addReg(SrcReg).addReg(SrcReg);
2996 BuildMI(*MBB, IP, X86::ADC32rr, 2,
2997 DestReg+1).addReg(SrcReg+1).addReg(SrcReg+1);
2998 } else if (Amount < 32) {
2999 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
3001 doSHLDConst(MBB, IP, DestReg+1, SrcReg+1, SrcReg, Amount);
3002 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
3004 BuildMI(*MBB, IP, X86::SHRD32rri8, 3,
3005 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
3006 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
3008 } else if (Amount == 32) {
3010 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
3011 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
3013 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
3015 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
3017 BuildMI(*MBB, IP, X86::SAR32ri, 2,
3018 DestReg+1).addReg(SrcReg).addImm(31);
3021 } else { // Shifting more than 32 bits
3024 BuildMI(*MBB, IP, X86::SHL32ri, 2,
3025 DestReg + 1).addReg(SrcReg).addImm(Amount);
3026 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
3028 BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
3029 DestReg).addReg(SrcReg+1).addImm(Amount);
3030 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
3034 unsigned TmpReg = makeAnotherReg(Type::IntTy);
3035 if (!isLeftShift && isSigned) {
3036 // If this is a SHR of a Long, then we need to do funny sign extension
3037 // stuff. TmpReg gets the value to use as the high-part if we are
3038 // shifting more than 32 bits.
3039 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
3041 // Other shifts use a fixed zero value if the shift is more than 32
3043 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
3046 // Initialize CL with the shift amount...
3047 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
3048 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
3050 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
3051 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
3053 // TmpReg2 = shld inHi, inLo
3054 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
3056 // TmpReg3 = shl inLo, CL
3057 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
3059 // Set the flags to indicate whether the shift was by more than 32 bits.
3060 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
3062 // DestHi = (>32) ? TmpReg3 : TmpReg2;
3063 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
3064 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
3065 // DestLo = (>32) ? TmpReg : TmpReg3;
3066 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
3067 DestReg).addReg(TmpReg3).addReg(TmpReg);
3069 // TmpReg2 = shrd inLo, inHi
3070 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
3072 // TmpReg3 = s[ah]r inHi, CL
3073 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
3076 // Set the flags to indicate whether the shift was by more than 32 bits.
3077 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
3079 // DestLo = (>32) ? TmpReg3 : TmpReg2;
3080 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
3081 DestReg).addReg(TmpReg2).addReg(TmpReg3);
3083 // DestHi = (>32) ? TmpReg : TmpReg3;
3084 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
3085 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
3091 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
3092 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
3093 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
3095 if (CUI->getValue() == 1 && isLeftShift) { // X << 1 -> X+X
3096 static const int AddOpC[] = { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
3097 BuildMI(*MBB, IP, AddOpC[Class], 2,DestReg).addReg(SrcReg).addReg(SrcReg);
3099 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
3100 BuildMI(*MBB, IP, Opc[Class], 2,
3101 DestReg).addReg(SrcReg).addImm(CUI->getValue());
3103 } else { // The shift amount is non-constant.
3104 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
3105 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
3107 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
3108 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
3113 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
3114 /// instruction. The load and store instructions are the only place where we
3115 /// need to worry about the memory layout of the target machine.
3117 void X86ISel::visitLoadInst(LoadInst &I) {
3118 // Check to see if this load instruction is going to be folded into a binary
3119 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
3120 // pattern matching instruction selector be nice?
3121 unsigned Class = getClassB(I.getType());
3122 if (I.hasOneUse()) {
3123 Instruction *User = cast<Instruction>(I.use_back());
3124 switch (User->getOpcode()) {
3125 case Instruction::Cast:
3126 // If this is a cast from a signed-integer type to a floating point type,
3127 // fold the cast here.
3128 if (getClassB(User->getType()) == cFP &&
3129 (I.getType() == Type::ShortTy || I.getType() == Type::IntTy ||
3130 I.getType() == Type::LongTy)) {
3131 unsigned DestReg = getReg(User);
3132 static const unsigned Opcode[] = {
3133 0/*BYTE*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m
3136 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
3137 unsigned FI = getFixedSizedAllocaFI(AI);
3138 addFrameReference(BuildMI(BB, Opcode[Class], 4, DestReg), FI);
3141 getAddressingMode(I.getOperand(0), AM);
3142 addFullAddress(BuildMI(BB, Opcode[Class], 4, DestReg), AM);
3150 case Instruction::Add:
3151 case Instruction::Sub:
3152 case Instruction::And:
3153 case Instruction::Or:
3154 case Instruction::Xor:
3155 if (Class == cLong) User = 0;
3157 case Instruction::Mul:
3158 case Instruction::Div:
3159 if (Class != cFP) User = 0;
3160 break; // Folding only implemented for floating point.
3161 default: User = 0; break;
3165 // Okay, we found a user. If the load is the first operand and there is
3166 // no second operand load, reverse the operand ordering. Note that this
3167 // can fail for a subtract (ie, no change will be made).
3168 bool Swapped = false;
3169 if (!isa<LoadInst>(User->getOperand(1)))
3170 Swapped = !cast<BinaryOperator>(User)->swapOperands();
3172 // Okay, now that everything is set up, if this load is used by the second
3173 // operand, and if there are no instructions that invalidate the load
3174 // before the binary operator, eliminate the load.
3175 if (User->getOperand(1) == &I &&
3176 isSafeToFoldLoadIntoInstruction(I, *User))
3177 return; // Eliminate the load!
3179 // If this is a floating point sub or div, we won't be able to swap the
3180 // operands, but we will still be able to eliminate the load.
3181 if (Class == cFP && User->getOperand(0) == &I &&
3182 !isa<LoadInst>(User->getOperand(1)) &&
3183 (User->getOpcode() == Instruction::Sub ||
3184 User->getOpcode() == Instruction::Div) &&
3185 isSafeToFoldLoadIntoInstruction(I, *User))
3186 return; // Eliminate the load!
3188 // If we swapped the operands to the instruction, but couldn't fold the
3189 // load anyway, swap them back. We don't want to break add X, int
3191 if (Swapped) cast<BinaryOperator>(User)->swapOperands();
3195 static const unsigned Opcodes[] = {
3196 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m, X86::MOV32rm
3198 unsigned Opcode = Opcodes[Class];
3199 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
3201 unsigned DestReg = getReg(I);
3203 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
3204 unsigned FI = getFixedSizedAllocaFI(AI);
3205 if (Class == cLong) {
3206 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg), FI);
3207 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), FI, 4);
3209 addFrameReference(BuildMI(BB, Opcode, 4, DestReg), FI);
3213 getAddressingMode(I.getOperand(0), AM);
3215 if (Class == cLong) {
3216 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg), AM);
3218 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), AM);
3220 addFullAddress(BuildMI(BB, Opcode, 4, DestReg), AM);
3225 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
3228 void X86ISel::visitStoreInst(StoreInst &I) {
3230 getAddressingMode(I.getOperand(1), AM);
3232 const Type *ValTy = I.getOperand(0)->getType();
3233 unsigned Class = getClassB(ValTy);
3235 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
3236 uint64_t Val = CI->getRawValue();
3237 if (Class == cLong) {
3238 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val & ~0U);
3240 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val>>32);
3242 static const unsigned Opcodes[] = {
3243 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
3245 unsigned Opcode = Opcodes[Class];
3246 addFullAddress(BuildMI(BB, Opcode, 5), AM).addImm(Val);
3248 } else if (isa<ConstantPointerNull>(I.getOperand(0))) {
3249 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(0);
3250 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
3251 addFullAddress(BuildMI(BB, X86::MOV8mi, 5), AM).addImm(CB->getValue());
3252 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) {
3253 // Store constant FP values with integer instructions to avoid having to
3254 // load the constants from the constant pool then do a store.
3255 if (CFP->getType() == Type::FloatTy) {
3260 V.F = CFP->getValue();
3261 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(V.I);
3267 V.F = CFP->getValue();
3268 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm((unsigned)V.I);
3270 addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(
3271 unsigned(V.I >> 32));
3274 } else if (Class == cLong) {
3275 unsigned ValReg = getReg(I.getOperand(0));
3276 addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg);
3278 addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg+1);
3280 // FIXME: stop emitting these two instructions:
3281 // movl $global,%eax
3283 // when one instruction will suffice. That includes when the global
3284 // has an offset applied to it.
3285 unsigned ValReg = getReg(I.getOperand(0));
3286 static const unsigned Opcodes[] = {
3287 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
3289 unsigned Opcode = Opcodes[Class];
3290 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
3292 addFullAddress(BuildMI(BB, Opcode, 1+4), AM).addReg(ValReg);
3297 /// visitCastInst - Here we have various kinds of copying with or without sign
3298 /// extension going on.
3300 void X86ISel::visitCastInst(CastInst &CI) {
3301 Value *Op = CI.getOperand(0);
3303 unsigned SrcClass = getClassB(Op->getType());
3304 unsigned DestClass = getClassB(CI.getType());
3305 // Noop casts are not emitted: getReg will return the source operand as the
3306 // register to use for any uses of the noop cast.
3307 if (DestClass == SrcClass) {
3308 // The only detail in this plan is that casts from double -> float are
3309 // truncating operations that we have to codegen through memory (despite
3310 // the fact that the source/dest registers are the same class).
3311 if (CI.getType() != Type::FloatTy || Op->getType() != Type::DoubleTy)
3315 // If this is a cast from a 32-bit integer to a Long type, and the only uses
3316 // of the case are GEP instructions, then the cast does not need to be
3317 // generated explicitly, it will be folded into the GEP.
3318 if (DestClass == cLong && SrcClass == cInt) {
3319 bool AllUsesAreGEPs = true;
3320 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
3321 if (!isa<GetElementPtrInst>(*I)) {
3322 AllUsesAreGEPs = false;
3326 // No need to codegen this cast if all users are getelementptr instrs...
3327 if (AllUsesAreGEPs) return;
3330 // If this cast converts a load from a short,int, or long integer to a FP
3331 // value, we will have folded this cast away.
3332 if (DestClass == cFP && isa<LoadInst>(Op) && Op->hasOneUse() &&
3333 (Op->getType() == Type::ShortTy || Op->getType() == Type::IntTy ||
3334 Op->getType() == Type::LongTy))
3338 unsigned DestReg = getReg(CI);
3339 MachineBasicBlock::iterator MI = BB->end();
3340 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
3343 /// emitCastOperation - Common code shared between visitCastInst and constant
3344 /// expression cast support.
3346 void X86ISel::emitCastOperation(MachineBasicBlock *BB,
3347 MachineBasicBlock::iterator IP,
3348 Value *Src, const Type *DestTy,
3350 const Type *SrcTy = Src->getType();
3351 unsigned SrcClass = getClassB(SrcTy);
3352 unsigned DestClass = getClassB(DestTy);
3353 unsigned SrcReg = getReg(Src, BB, IP);
3355 // Implement casts to bool by using compare on the operand followed by set if
3356 // not zero on the result.
3357 if (DestTy == Type::BoolTy) {
3360 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
3363 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
3366 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
3369 unsigned TmpReg = makeAnotherReg(Type::IntTy);
3370 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
3374 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
3375 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
3376 BuildMI(*BB, IP, X86::SAHF, 1);
3380 // If the zero flag is not set, then the value is true, set the byte to
3382 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
3386 static const unsigned RegRegMove[] = {
3387 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
3390 // Implement casts between values of the same type class (as determined by
3391 // getClass) by using a register-to-register move.
3392 if (SrcClass == DestClass) {
3393 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
3394 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
3395 } else if (SrcClass == cFP) {
3396 if (SrcTy == Type::FloatTy) { // double -> float
3397 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
3398 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
3399 } else { // float -> double
3400 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
3401 "Unknown cFP member!");
3402 // Truncate from double to float by storing to memory as short, then
3404 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
3405 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
3406 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
3407 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
3409 } else if (SrcClass == cLong) {
3410 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3411 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
3413 assert(0 && "Cannot handle this type of cast instruction!");
3419 // Handle cast of SMALLER int to LARGER int using a move with sign extension
3420 // or zero extension, depending on whether the source type was signed.
3421 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
3422 SrcClass < DestClass) {
3423 bool isLong = DestClass == cLong;
3424 if (isLong) DestClass = cInt;
3426 static const unsigned Opc[][4] = {
3427 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
3428 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
3431 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
3432 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
3433 DestReg).addReg(SrcReg);
3435 if (isLong) { // Handle upper 32 bits as appropriate...
3436 if (isUnsigned) // Zero out top bits...
3437 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
3438 else // Sign extend bottom half...
3439 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
3444 // Special case long -> int ...
3445 if (SrcClass == cLong && DestClass == cInt) {
3446 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3450 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
3451 // move out of AX or AL.
3452 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
3453 && SrcClass > DestClass) {
3454 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
3455 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
3456 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
3460 // Handle casts from integer to floating point now...
3461 if (DestClass == cFP) {
3462 // Promote the integer to a type supported by FLD. We do this because there
3463 // are no unsigned FLD instructions, so we must promote an unsigned value to
3464 // a larger signed value, then use FLD on the larger value.
3466 const Type *PromoteType = 0;
3467 unsigned PromoteOpcode = 0;
3468 unsigned RealDestReg = DestReg;
3469 switch (SrcTy->getTypeID()) {
3470 case Type::BoolTyID:
3471 case Type::SByteTyID:
3472 // We don't have the facilities for directly loading byte sized data from
3473 // memory (even signed). Promote it to 16 bits.
3474 PromoteType = Type::ShortTy;
3475 PromoteOpcode = X86::MOVSX16rr8;
3477 case Type::UByteTyID:
3478 PromoteType = Type::ShortTy;
3479 PromoteOpcode = X86::MOVZX16rr8;
3481 case Type::UShortTyID:
3482 PromoteType = Type::IntTy;
3483 PromoteOpcode = X86::MOVZX32rr16;
3485 case Type::ULongTyID:
3486 case Type::UIntTyID:
3487 // Don't fild into the read destination.
3488 DestReg = makeAnotherReg(Type::DoubleTy);
3490 default: // No promotion needed...
3495 unsigned TmpReg = makeAnotherReg(PromoteType);
3496 BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
3497 SrcTy = PromoteType;
3498 SrcClass = getClass(PromoteType);
3502 // Spill the integer to memory and reload it from there...
3504 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
3506 if (SrcClass == cLong) {
3507 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
3508 FrameIdx).addReg(SrcReg);
3509 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
3510 FrameIdx, 4).addReg(SrcReg+1);
3512 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
3513 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
3514 FrameIdx).addReg(SrcReg);
3517 static const unsigned Op2[] =
3518 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
3519 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
3521 if (SrcTy == Type::UIntTy) {
3522 // If this is a cast from uint -> double, we need to be careful about if
3523 // the "sign" bit is set. If so, we don't want to make a negative number,
3524 // we want to make a positive number. Emit code to add an offset if the
3527 // Compute whether the sign bit is set by shifting the reg right 31 bits.
3528 unsigned IsNeg = makeAnotherReg(Type::IntTy);
3529 BuildMI(BB, X86::SHR32ri, 2, IsNeg).addReg(SrcReg).addImm(31);
3531 // Create a CP value that has the offset in one word and 0 in the other.
3532 static ConstantInt *TheOffset = ConstantUInt::get(Type::ULongTy,
3533 0x4f80000000000000ULL);
3534 unsigned CPI = F->getConstantPool()->getConstantPoolIndex(TheOffset);
3535 BuildMI(BB, X86::FADD32m, 5, RealDestReg).addReg(DestReg)
3536 .addConstantPoolIndex(CPI).addZImm(4).addReg(IsNeg).addSImm(0);
3538 } else if (SrcTy == Type::ULongTy) {
3539 // We need special handling for unsigned 64-bit integer sources. If the
3540 // input number has the "sign bit" set, then we loaded it incorrectly as a
3541 // negative 64-bit number. In this case, add an offset value.
3543 // Emit a test instruction to see if the dynamic input value was signed.
3544 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
3546 // If the sign bit is set, get a pointer to an offset, otherwise get a
3547 // pointer to a zero.
3548 MachineConstantPool *CP = F->getConstantPool();
3549 unsigned Zero = makeAnotherReg(Type::IntTy);
3550 Constant *Null = Constant::getNullValue(Type::UIntTy);
3551 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
3552 CP->getConstantPoolIndex(Null));
3553 unsigned Offset = makeAnotherReg(Type::IntTy);
3554 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
3556 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
3557 CP->getConstantPoolIndex(OffsetCst));
3558 unsigned Addr = makeAnotherReg(Type::IntTy);
3559 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
3561 // Load the constant for an add. FIXME: this could make an 'fadd' that
3562 // reads directly from memory, but we don't support these yet.
3563 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
3564 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
3566 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
3567 .addReg(ConstReg).addReg(DestReg);
3573 // Handle casts from floating point to integer now...
3574 if (SrcClass == cFP) {
3575 // Change the floating point control register to use "round towards zero"
3576 // mode when truncating to an integer value.
3578 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
3579 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
3581 // Load the old value of the high byte of the control word...
3582 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
3583 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
3586 // Set the high part to be round to zero...
3587 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
3588 CWFrameIdx, 1).addImm(12);
3590 // Reload the modified control word now...
3591 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
3593 // Restore the memory image of control word to original value
3594 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
3595 CWFrameIdx, 1).addReg(HighPartOfCW);
3597 // We don't have the facilities for directly storing byte sized data to
3598 // memory. Promote it to 16 bits. We also must promote unsigned values to
3599 // larger classes because we only have signed FP stores.
3600 unsigned StoreClass = DestClass;
3601 const Type *StoreTy = DestTy;
3602 if (StoreClass == cByte || DestTy->isUnsigned())
3603 switch (StoreClass) {
3604 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
3605 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
3606 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
3607 // The following treatment of cLong may not be perfectly right,
3608 // but it survives chains of casts of the form
3609 // double->ulong->double.
3610 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
3611 default: assert(0 && "Unknown store class!");
3614 // Spill the integer to memory and reload it from there...
3616 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
3618 static const unsigned Op1[] =
3619 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
3620 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
3621 FrameIdx).addReg(SrcReg);
3623 if (DestClass == cLong) {
3624 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
3625 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
3628 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
3629 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
3632 // Reload the original control word now...
3633 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
3637 // Anything we haven't handled already, we can't (yet) handle at all.
3638 assert(0 && "Unhandled cast instruction!");
3642 /// visitVANextInst - Implement the va_next instruction...
3644 void X86ISel::visitVANextInst(VANextInst &I) {
3645 unsigned VAList = getReg(I.getOperand(0));
3646 unsigned DestReg = getReg(I);
3649 switch (I.getArgType()->getTypeID()) {
3652 assert(0 && "Error: bad type for va_next instruction!");
3654 case Type::PointerTyID:
3655 case Type::UIntTyID:
3659 case Type::ULongTyID:
3660 case Type::LongTyID:
3661 case Type::DoubleTyID:
3666 // Increment the VAList pointer...
3667 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
3670 void X86ISel::visitVAArgInst(VAArgInst &I) {
3671 unsigned VAList = getReg(I.getOperand(0));
3672 unsigned DestReg = getReg(I);
3674 switch (I.getType()->getTypeID()) {
3677 assert(0 && "Error: bad type for va_next instruction!");
3679 case Type::PointerTyID:
3680 case Type::UIntTyID:
3682 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3684 case Type::ULongTyID:
3685 case Type::LongTyID:
3686 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3687 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
3689 case Type::DoubleTyID:
3690 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
3695 /// visitGetElementPtrInst - instruction-select GEP instructions
3697 void X86ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
3698 // If this GEP instruction will be folded into all of its users, we don't need
3699 // to explicitly calculate it!
3701 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), AM)) {
3702 // Check all of the users of the instruction to see if they are loads and
3704 bool AllWillFold = true;
3705 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
3706 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
3707 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
3708 cast<Instruction>(*UI)->getOperand(0) == &I) {
3709 AllWillFold = false;
3713 // If the instruction is foldable, and will be folded into all users, don't
3715 if (AllWillFold) return;
3718 unsigned outputReg = getReg(I);
3719 emitGEPOperation(BB, BB->end(), I.getOperand(0),
3720 I.op_begin()+1, I.op_end(), outputReg);
3723 /// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
3724 /// GEPTypes (the derived types being stepped through at each level). On return
3725 /// from this function, if some indexes of the instruction are representable as
3726 /// an X86 lea instruction, the machine operands are put into the Ops
3727 /// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
3728 /// lists. Otherwise, GEPOps.size() is returned. If this returns a an
3729 /// addressing mode that only partially consumes the input, the BaseReg input of
3730 /// the addressing mode must be left free.
3732 /// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
3734 void X86ISel::getGEPIndex(MachineBasicBlock *MBB,
3735 MachineBasicBlock::iterator IP,
3736 std::vector<Value*> &GEPOps,
3737 std::vector<const Type*> &GEPTypes,
3738 X86AddressMode &AM) {
3739 const TargetData &TD = TM.getTargetData();
3741 // Clear out the state we are working with...
3742 AM.BaseType = X86AddressMode::RegBase;
3743 AM.Base.Reg = 0; // No base register
3744 AM.Scale = 1; // Unit scale
3745 AM.IndexReg = 0; // No index register
3746 AM.Disp = 0; // No displacement
3748 // While there are GEP indexes that can be folded into the current address,
3749 // keep processing them.
3750 while (!GEPTypes.empty()) {
3751 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
3752 // It's a struct access. CUI is the index into the structure,
3753 // which names the field. This index must have unsigned type.
3754 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
3756 // Use the TargetData structure to pick out what the layout of the
3757 // structure is in memory. Since the structure index must be constant, we
3758 // can get its value and use it to find the right byte offset from the
3759 // StructLayout class's list of structure member offsets.
3760 AM.Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
3761 GEPOps.pop_back(); // Consume a GEP operand
3762 GEPTypes.pop_back();
3764 // It's an array or pointer access: [ArraySize x ElementType].
3765 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3766 Value *idx = GEPOps.back();
3768 // idx is the index into the array. Unlike with structure
3769 // indices, we may not know its actual value at code-generation
3772 // If idx is a constant, fold it into the offset.
3773 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
3774 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
3775 AM.Disp += TypeSize*CSI->getValue();
3776 } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
3777 AM.Disp += TypeSize*CUI->getValue();
3779 // If the index reg is already taken, we can't handle this index.
3780 if (AM.IndexReg) return;
3782 // If this is a size that we can handle, then add the index as
3784 case 1: case 2: case 4: case 8:
3785 // These are all acceptable scales on X86.
3786 AM.Scale = TypeSize;
3789 // Otherwise, we can't handle this scale
3793 if (CastInst *CI = dyn_cast<CastInst>(idx))
3794 if (CI->getOperand(0)->getType() == Type::IntTy ||
3795 CI->getOperand(0)->getType() == Type::UIntTy)
3796 idx = CI->getOperand(0);
3798 AM.IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
3801 GEPOps.pop_back(); // Consume a GEP operand
3802 GEPTypes.pop_back();
3806 // GEPTypes is empty, which means we have a single operand left. Set it as
3807 // the base register.
3809 assert(AM.Base.Reg == 0);
3811 if (AllocaInst *AI = dyn_castFixedAlloca(GEPOps.back())) {
3812 AM.BaseType = X86AddressMode::FrameIndexBase;
3813 AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
3818 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps.back())) {
3824 AM.Base.Reg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
3825 GEPOps.pop_back(); // Consume the last GEP operand
3829 /// isGEPFoldable - Return true if the specified GEP can be completely
3830 /// folded into the addressing mode of a load/store or lea instruction.
3831 bool X86ISel::isGEPFoldable(MachineBasicBlock *MBB,
3832 Value *Src, User::op_iterator IdxBegin,
3833 User::op_iterator IdxEnd, X86AddressMode &AM) {
3835 std::vector<Value*> GEPOps;
3836 GEPOps.resize(IdxEnd-IdxBegin+1);
3838 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3840 std::vector<const Type*>
3841 GEPTypes(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3842 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3844 MachineBasicBlock::iterator IP;
3845 if (MBB) IP = MBB->end();
3846 getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
3848 // We can fold it away iff the getGEPIndex call eliminated all operands.
3849 return GEPOps.empty();
3852 void X86ISel::emitGEPOperation(MachineBasicBlock *MBB,
3853 MachineBasicBlock::iterator IP,
3854 Value *Src, User::op_iterator IdxBegin,
3855 User::op_iterator IdxEnd, unsigned TargetReg) {
3856 const TargetData &TD = TM.getTargetData();
3858 // If this is a getelementptr null, with all constant integer indices, just
3859 // replace it with TargetReg = 42.
3860 if (isa<ConstantPointerNull>(Src)) {
3861 User::op_iterator I = IdxBegin;
3862 for (; I != IdxEnd; ++I)
3863 if (!isa<ConstantInt>(*I))
3865 if (I == IdxEnd) { // All constant indices
3866 unsigned Offset = TD.getIndexedOffset(Src->getType(),
3867 std::vector<Value*>(IdxBegin, IdxEnd));
3868 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addImm(Offset);
3873 std::vector<Value*> GEPOps;
3874 GEPOps.resize(IdxEnd-IdxBegin+1);
3876 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3878 std::vector<const Type*> GEPTypes;
3879 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3880 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3882 // Keep emitting instructions until we consume the entire GEP instruction.
3883 while (!GEPOps.empty()) {
3884 unsigned OldSize = GEPOps.size();
3886 getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
3888 if (GEPOps.size() != OldSize) {
3889 // getGEPIndex consumed some of the input. Build an LEA instruction here.
3890 unsigned NextTarget = 0;
3891 if (!GEPOps.empty()) {
3892 assert(AM.Base.Reg == 0 &&
3893 "getGEPIndex should have left the base register open for chaining!");
3894 NextTarget = AM.Base.Reg = makeAnotherReg(Type::UIntTy);
3897 if (AM.BaseType == X86AddressMode::RegBase &&
3898 AM.IndexReg == 0 && AM.Disp == 0 && !AM.GV)
3899 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(AM.Base.Reg);
3900 else if (AM.BaseType == X86AddressMode::RegBase && AM.Base.Reg == 0 &&
3901 AM.IndexReg == 0 && AM.Disp == 0)
3902 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(AM.GV);
3904 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg), AM);
3906 TargetReg = NextTarget;
3907 } else if (GEPTypes.empty()) {
3908 // The getGEPIndex operation didn't want to build an LEA. Check to see if
3909 // all operands are consumed but the base pointer. If so, just load it
3910 // into the register.
3911 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
3912 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
3914 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
3915 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
3917 break; // we are now done
3920 // It's an array or pointer access: [ArraySize x ElementType].
3921 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3922 Value *idx = GEPOps.back();
3923 GEPOps.pop_back(); // Consume a GEP operand
3924 GEPTypes.pop_back();
3926 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
3927 // operand on X86. Handle this case directly now...
3928 if (CastInst *CI = dyn_cast<CastInst>(idx))
3929 if (CI->getOperand(0)->getType() == Type::IntTy ||
3930 CI->getOperand(0)->getType() == Type::UIntTy)
3931 idx = CI->getOperand(0);
3933 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
3934 // must find the size of the pointed-to type (Not coincidentally, the next
3935 // type is the type of the elements in the array).
3936 const Type *ElTy = SqTy->getElementType();
3937 unsigned elementSize = TD.getTypeSize(ElTy);
3939 // If idxReg is a constant, we don't need to perform the multiply!
3940 if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
3941 if (!CSI->isNullValue()) {
3942 unsigned Offset = elementSize*CSI->getRawValue();
3943 unsigned Reg = makeAnotherReg(Type::UIntTy);
3944 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
3945 .addReg(Reg).addImm(Offset);
3946 --IP; // Insert the next instruction before this one.
3947 TargetReg = Reg; // Codegen the rest of the GEP into this
3949 } else if (elementSize == 1) {
3950 // If the element size is 1, we don't have to multiply, just add
3951 unsigned idxReg = getReg(idx, MBB, IP);
3952 unsigned Reg = makeAnotherReg(Type::UIntTy);
3953 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
3954 --IP; // Insert the next instruction before this one.
3955 TargetReg = Reg; // Codegen the rest of the GEP into this
3957 unsigned idxReg = getReg(idx, MBB, IP);
3958 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
3960 // Make sure we can back the iterator up to point to the first
3961 // instruction emitted.
3962 MachineBasicBlock::iterator BeforeIt = IP;
3963 if (IP == MBB->begin())
3964 BeforeIt = MBB->end();
3967 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
3969 // Emit an ADD to add OffsetReg to the basePtr.
3970 unsigned Reg = makeAnotherReg(Type::UIntTy);
3971 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
3972 .addReg(Reg).addReg(OffsetReg);
3974 // Step to the first instruction of the multiply.
3975 if (BeforeIt == MBB->end())
3980 TargetReg = Reg; // Codegen the rest of the GEP into this
3986 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
3987 /// frame manager, otherwise do it the hard way.
3989 void X86ISel::visitAllocaInst(AllocaInst &I) {
3990 // If this is a fixed size alloca in the entry block for the function, we
3991 // statically stack allocate the space, so we don't need to do anything here.
3993 if (dyn_castFixedAlloca(&I)) return;
3995 // Find the data size of the alloca inst's getAllocatedType.
3996 const Type *Ty = I.getAllocatedType();
3997 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
3999 // Create a register to hold the temporary result of multiplying the type size
4000 // constant by the variable amount.
4001 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
4002 unsigned SrcReg1 = getReg(I.getArraySize());
4004 // TotalSizeReg = mul <numelements>, <TypeSize>
4005 MachineBasicBlock::iterator MBBI = BB->end();
4006 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
4008 // AddedSize = add <TotalSizeReg>, 15
4009 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
4010 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
4012 // AlignedSize = and <AddedSize>, ~15
4013 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
4014 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
4016 // Subtract size from stack pointer, thereby allocating some space.
4017 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
4019 // Put a pointer to the space into the result register, by copying
4020 // the stack pointer.
4021 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
4023 // Inform the Frame Information that we have just allocated a variable-sized
4025 F->getFrameInfo()->CreateVariableSizedObject();
4028 /// visitMallocInst - Malloc instructions are code generated into direct calls
4029 /// to the library malloc.
4031 void X86ISel::visitMallocInst(MallocInst &I) {
4032 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
4035 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
4036 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
4038 Arg = makeAnotherReg(Type::UIntTy);
4039 unsigned Op0Reg = getReg(I.getOperand(0));
4040 MachineBasicBlock::iterator MBBI = BB->end();
4041 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
4044 std::vector<ValueRecord> Args;
4045 Args.push_back(ValueRecord(Arg, Type::UIntTy));
4046 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
4047 1).addExternalSymbol("malloc", true);
4048 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
4052 /// visitFreeInst - Free instructions are code gen'd to call the free libc
4055 void X86ISel::visitFreeInst(FreeInst &I) {
4056 std::vector<ValueRecord> Args;
4057 Args.push_back(ValueRecord(I.getOperand(0)));
4058 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
4059 1).addExternalSymbol("free", true);
4060 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
4063 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
4064 /// into a machine code representation is a very simple peep-hole fashion. The
4065 /// generated code sucks but the implementation is nice and simple.
4067 FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
4068 return new X86ISel(TM);