1 //===-- InstSelectSimple.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 "X86InstrInfo.h"
16 #include "X86InstrBuilder.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/MRegisterInfo.h"
30 #include "llvm/Support/InstVisitor.h"
32 /// BMI - A special BuildMI variant that takes an iterator to insert the
33 /// instruction at as well as a basic block. This is the version for when you
34 /// have a destination register in mind.
35 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
36 MachineBasicBlock::iterator &I,
37 int Opcode, unsigned NumOperands,
39 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
40 MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
41 I = MBB->insert(I, MI)+1;
42 return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
45 /// BMI - A special BuildMI variant that takes an iterator to insert the
46 /// instruction at as well as a basic block.
47 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
48 MachineBasicBlock::iterator &I,
49 int Opcode, unsigned NumOperands) {
50 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
51 MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
52 I = MBB->insert(I, MI)+1;
53 return MachineInstrBuilder(MI);
58 struct ISel : public FunctionPass, InstVisitor<ISel> {
60 MachineFunction *F; // The function we are compiling into
61 MachineBasicBlock *BB; // The current MBB we are compiling
62 int VarArgsFrameIndex; // FrameIndex for start of varargs area
64 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
66 // MBBMap - Mapping between LLVM BB -> Machine BB
67 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
69 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
71 /// runOnFunction - Top level implementation of instruction selection for
72 /// the entire function.
74 bool runOnFunction(Function &Fn) {
75 F = &MachineFunction::construct(&Fn, TM);
77 // Create all of the machine basic blocks for the function...
78 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
79 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
83 // Copy incoming arguments off of the stack...
84 LoadArgumentsToVirtualRegs(Fn);
86 // Instruction select everything except PHI nodes
89 // Select the PHI nodes
95 // We always build a machine code representation for the function
99 virtual const char *getPassName() const {
100 return "X86 Simple Instruction Selection";
103 /// visitBasicBlock - This method is called when we are visiting a new basic
104 /// block. This simply creates a new MachineBasicBlock to emit code into
105 /// and adds it to the current MachineFunction. Subsequent visit* for
106 /// instructions will be invoked for all instructions in the basic block.
108 void visitBasicBlock(BasicBlock &LLVM_BB) {
109 BB = MBBMap[&LLVM_BB];
112 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
113 /// from the stack into virtual registers.
115 void LoadArgumentsToVirtualRegs(Function &F);
117 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
118 /// because we have to generate our sources into the source basic blocks,
119 /// not the current one.
121 void SelectPHINodes();
123 // Visitation methods for various instructions. These methods simply emit
124 // fixed X86 code for each instruction.
127 // Control flow operators
128 void visitReturnInst(ReturnInst &RI);
129 void visitBranchInst(BranchInst &BI);
135 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
136 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
138 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
139 const std::vector<ValueRecord> &Args);
140 void visitCallInst(CallInst &I);
141 void visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &I);
143 // Arithmetic operators
144 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
145 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
146 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
147 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
148 unsigned DestReg, const Type *DestTy,
149 unsigned Op0Reg, unsigned Op1Reg);
150 void doMultiplyConst(MachineBasicBlock *MBB,
151 MachineBasicBlock::iterator &MBBI,
152 unsigned DestReg, const Type *DestTy,
153 unsigned Op0Reg, unsigned Op1Val);
154 void visitMul(BinaryOperator &B);
156 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
157 void visitRem(BinaryOperator &B) { visitDivRem(B); }
158 void visitDivRem(BinaryOperator &B);
161 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
162 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
163 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
165 // Comparison operators...
166 void visitSetCondInst(SetCondInst &I);
167 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
168 MachineBasicBlock *MBB,
169 MachineBasicBlock::iterator &MBBI);
171 // Memory Instructions
172 void visitLoadInst(LoadInst &I);
173 void visitStoreInst(StoreInst &I);
174 void visitGetElementPtrInst(GetElementPtrInst &I);
175 void visitAllocaInst(AllocaInst &I);
176 void visitMallocInst(MallocInst &I);
177 void visitFreeInst(FreeInst &I);
180 void visitShiftInst(ShiftInst &I);
181 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
182 void visitCastInst(CastInst &I);
183 void visitVANextInst(VANextInst &I);
184 void visitVAArgInst(VAArgInst &I);
186 void visitInstruction(Instruction &I) {
187 std::cerr << "Cannot instruction select: " << I;
191 /// promote32 - Make a value 32-bits wide, and put it somewhere.
193 void promote32(unsigned targetReg, const ValueRecord &VR);
195 /// EmitByteSwap - Byteswap SrcReg into DestReg.
197 void EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class);
199 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
200 /// constant expression GEP support.
202 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
203 Value *Src, User::op_iterator IdxBegin,
204 User::op_iterator IdxEnd, unsigned TargetReg);
206 /// emitCastOperation - Common code shared between visitCastInst and
207 /// constant expression cast support.
208 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator&IP,
209 Value *Src, const Type *DestTy, unsigned TargetReg);
211 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
212 /// and constant expression support.
213 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
214 MachineBasicBlock::iterator &IP,
215 Value *Op0, Value *Op1,
216 unsigned OperatorClass, unsigned TargetReg);
218 /// emitSetCCOperation - Common code shared between visitSetCondInst and
219 /// constant expression support.
220 void emitSetCCOperation(MachineBasicBlock *BB,
221 MachineBasicBlock::iterator &IP,
222 Value *Op0, Value *Op1, unsigned Opcode,
226 /// copyConstantToRegister - Output the instructions required to put the
227 /// specified constant into the specified register.
229 void copyConstantToRegister(MachineBasicBlock *MBB,
230 MachineBasicBlock::iterator &MBBI,
231 Constant *C, unsigned Reg);
233 /// makeAnotherReg - This method returns the next register number we haven't
236 /// Long values are handled somewhat specially. They are always allocated
237 /// as pairs of 32 bit integer values. The register number returned is the
238 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
239 /// of the long value.
241 unsigned makeAnotherReg(const Type *Ty) {
242 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
243 "Current target doesn't have X86 reg info??");
244 const X86RegisterInfo *MRI =
245 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
246 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
247 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
248 // Create the lower part
249 F->getSSARegMap()->createVirtualRegister(RC);
250 // Create the upper part.
251 return F->getSSARegMap()->createVirtualRegister(RC)-1;
254 // Add the mapping of regnumber => reg class to MachineFunction
255 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
256 return F->getSSARegMap()->createVirtualRegister(RC);
259 /// getReg - This method turns an LLVM value into a register number. This
260 /// is guaranteed to produce the same register number for a particular value
261 /// every time it is queried.
263 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
264 unsigned getReg(Value *V) {
265 // Just append to the end of the current bb.
266 MachineBasicBlock::iterator It = BB->end();
267 return getReg(V, BB, It);
269 unsigned getReg(Value *V, MachineBasicBlock *MBB,
270 MachineBasicBlock::iterator &IPt) {
271 unsigned &Reg = RegMap[V];
273 Reg = makeAnotherReg(V->getType());
277 // If this operand is a constant, emit the code to copy the constant into
278 // the register here...
280 if (Constant *C = dyn_cast<Constant>(V)) {
281 copyConstantToRegister(MBB, IPt, C, Reg);
282 RegMap.erase(V); // Assign a new name to this constant if ref'd again
283 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
284 // Move the address of the global into the register
285 BMI(MBB, IPt, X86::MOVir32, 1, Reg).addGlobalAddress(GV);
286 RegMap.erase(V); // Assign a new name to this address if ref'd again
294 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
298 cByte, cShort, cInt, cFP, cLong
301 /// getClass - Turn a primitive type into a "class" number which is based on the
302 /// size of the type, and whether or not it is floating point.
304 static inline TypeClass getClass(const Type *Ty) {
305 switch (Ty->getPrimitiveID()) {
306 case Type::SByteTyID:
307 case Type::UByteTyID: return cByte; // Byte operands are class #0
308 case Type::ShortTyID:
309 case Type::UShortTyID: return cShort; // Short operands are class #1
312 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
314 case Type::FloatTyID:
315 case Type::DoubleTyID: return cFP; // Floating Point is #3
318 case Type::ULongTyID: return cLong; // Longs are class #4
320 assert(0 && "Invalid type to getClass!");
321 return cByte; // not reached
325 // getClassB - Just like getClass, but treat boolean values as bytes.
326 static inline TypeClass getClassB(const Type *Ty) {
327 if (Ty == Type::BoolTy) return cByte;
332 /// copyConstantToRegister - Output the instructions required to put the
333 /// specified constant into the specified register.
335 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
336 MachineBasicBlock::iterator &IP,
337 Constant *C, unsigned R) {
338 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
340 switch (CE->getOpcode()) {
341 case Instruction::GetElementPtr:
342 emitGEPOperation(MBB, IP, CE->getOperand(0),
343 CE->op_begin()+1, CE->op_end(), R);
345 case Instruction::Cast:
346 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
349 case Instruction::Xor: ++Class; // FALL THROUGH
350 case Instruction::Or: ++Class; // FALL THROUGH
351 case Instruction::And: ++Class; // FALL THROUGH
352 case Instruction::Sub: ++Class; // FALL THROUGH
353 case Instruction::Add:
354 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
358 case Instruction::SetNE:
359 case Instruction::SetEQ:
360 case Instruction::SetLT:
361 case Instruction::SetGT:
362 case Instruction::SetLE:
363 case Instruction::SetGE:
364 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
369 std::cerr << "Offending expr: " << C << "\n";
370 assert(0 && "Constant expression not yet handled!\n");
374 if (C->getType()->isIntegral()) {
375 unsigned Class = getClassB(C->getType());
377 if (Class == cLong) {
378 // Copy the value into the register pair.
379 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
380 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(Val & 0xFFFFFFFF);
381 BMI(MBB, IP, X86::MOVir32, 1, R+1).addZImm(Val >> 32);
385 assert(Class <= cInt && "Type not handled yet!");
387 static const unsigned IntegralOpcodeTab[] = {
388 X86::MOVir8, X86::MOVir16, X86::MOVir32
391 if (C->getType() == Type::BoolTy) {
392 BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
394 ConstantInt *CI = cast<ConstantInt>(C);
395 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CI->getRawValue());
397 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
398 double Value = CFP->getValue();
400 BMI(MBB, IP, X86::FLD0, 0, R);
401 else if (Value == +1.0)
402 BMI(MBB, IP, X86::FLD1, 0, R);
404 // Otherwise we need to spill the constant to memory...
405 MachineConstantPool *CP = F->getConstantPool();
406 unsigned CPI = CP->getConstantPoolIndex(CFP);
407 const Type *Ty = CFP->getType();
409 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
410 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
411 addConstantPoolReference(BMI(MBB, IP, LoadOpcode, 4, R), CPI);
414 } else if (isa<ConstantPointerNull>(C)) {
415 // Copy zero (null pointer) to the register.
416 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
417 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
418 unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
419 BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
421 std::cerr << "Offending constant: " << C << "\n";
422 assert(0 && "Type not handled yet!");
426 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
427 /// the stack into virtual registers.
429 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
430 // Emit instructions to load the arguments... On entry to a function on the
431 // X86, the stack frame looks like this:
433 // [ESP] -- return address
434 // [ESP + 4] -- first argument (leftmost lexically)
435 // [ESP + 8] -- second argument, if first argument is four bytes in size
438 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
439 MachineFrameInfo *MFI = F->getFrameInfo();
441 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
442 unsigned Reg = getReg(*I);
444 int FI; // Frame object index
445 switch (getClassB(I->getType())) {
447 FI = MFI->CreateFixedObject(1, ArgOffset);
448 addFrameReference(BuildMI(BB, X86::MOVmr8, 4, Reg), FI);
451 FI = MFI->CreateFixedObject(2, ArgOffset);
452 addFrameReference(BuildMI(BB, X86::MOVmr16, 4, Reg), FI);
455 FI = MFI->CreateFixedObject(4, ArgOffset);
456 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
459 FI = MFI->CreateFixedObject(8, ArgOffset);
460 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
461 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg+1), FI, 4);
462 ArgOffset += 4; // longs require 4 additional bytes
466 if (I->getType() == Type::FloatTy) {
467 Opcode = X86::FLDr32;
468 FI = MFI->CreateFixedObject(4, ArgOffset);
470 Opcode = X86::FLDr64;
471 FI = MFI->CreateFixedObject(8, ArgOffset);
472 ArgOffset += 4; // doubles require 4 additional bytes
474 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
477 assert(0 && "Unhandled argument type!");
479 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
482 // If the function takes variable number of arguments, add a frame offset for
483 // the start of the first vararg value... this is used to expand
485 if (Fn.getFunctionType()->isVarArg())
486 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
490 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
491 /// because we have to generate our sources into the source basic blocks, not
494 void ISel::SelectPHINodes() {
495 const TargetInstrInfo &TII = TM.getInstrInfo();
496 const Function &LF = *F->getFunction(); // The LLVM function...
497 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
498 const BasicBlock *BB = I;
499 MachineBasicBlock *MBB = MBBMap[I];
501 // Loop over all of the PHI nodes in the LLVM basic block...
502 unsigned NumPHIs = 0;
503 for (BasicBlock::const_iterator I = BB->begin();
504 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
506 // Create a new machine instr PHI node, and insert it.
507 unsigned PHIReg = getReg(*PN);
508 MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
509 MBB->insert(MBB->begin()+NumPHIs++, PhiMI);
511 MachineInstr *LongPhiMI = 0;
512 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
513 LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
514 MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
517 // PHIValues - Map of blocks to incoming virtual registers. We use this
518 // so that we only initialize one incoming value for a particular block,
519 // even if the block has multiple entries in the PHI node.
521 std::map<MachineBasicBlock*, unsigned> PHIValues;
523 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
524 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
526 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
527 PHIValues.lower_bound(PredMBB);
529 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
530 // We already inserted an initialization of the register for this
531 // predecessor. Recycle it.
532 ValReg = EntryIt->second;
535 // Get the incoming value into a virtual register.
537 Value *Val = PN->getIncomingValue(i);
539 // If this is a constant or GlobalValue, we may have to insert code
540 // into the basic block to compute it into a virtual register.
541 if (isa<Constant>(Val) || isa<GlobalValue>(Val)) {
542 // Because we don't want to clobber any values which might be in
543 // physical registers with the computation of this constant (which
544 // might be arbitrarily complex if it is a constant expression),
545 // just insert the computation at the top of the basic block.
546 MachineBasicBlock::iterator PI = PredMBB->begin();
548 // Skip over any PHI nodes though!
549 while (PI != PredMBB->end() && (*PI)->getOpcode() == X86::PHI)
552 ValReg = getReg(Val, PredMBB, PI);
554 ValReg = getReg(Val);
557 // Remember that we inserted a value for this PHI for this predecessor
558 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
561 PhiMI->addRegOperand(ValReg);
562 PhiMI->addMachineBasicBlockOperand(PredMBB);
564 LongPhiMI->addRegOperand(ValReg+1);
565 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
572 // canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
573 // the conditional branch instruction which is the only user of the cc
574 // instruction. This is the case if the conditional branch is the only user of
575 // the setcc, and if the setcc is in the same basic block as the conditional
576 // branch. We also don't handle long arguments below, so we reject them here as
579 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
580 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
581 if (SCI->hasOneUse() && isa<BranchInst>(SCI->use_back()) &&
582 SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
583 const Type *Ty = SCI->getOperand(0)->getType();
584 if (Ty != Type::LongTy && Ty != Type::ULongTy)
590 // Return a fixed numbering for setcc instructions which does not depend on the
591 // order of the opcodes.
593 static unsigned getSetCCNumber(unsigned Opcode) {
595 default: assert(0 && "Unknown setcc instruction!");
596 case Instruction::SetEQ: return 0;
597 case Instruction::SetNE: return 1;
598 case Instruction::SetLT: return 2;
599 case Instruction::SetGE: return 3;
600 case Instruction::SetGT: return 4;
601 case Instruction::SetLE: return 5;
605 // LLVM -> X86 signed X86 unsigned
606 // ----- ---------- ------------
607 // seteq -> sete sete
608 // setne -> setne setne
609 // setlt -> setl setb
610 // setge -> setge setae
611 // setgt -> setg seta
612 // setle -> setle setbe
614 // sets // Used by comparison with 0 optimization
616 static const unsigned SetCCOpcodeTab[2][8] = {
617 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
619 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
620 X86::SETSr, X86::SETNSr },
623 // EmitComparison - This function emits a comparison of the two operands,
624 // returning the extended setcc code to use.
625 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
626 MachineBasicBlock *MBB,
627 MachineBasicBlock::iterator &IP) {
628 // The arguments are already supposed to be of the same type.
629 const Type *CompTy = Op0->getType();
630 unsigned Class = getClassB(CompTy);
631 unsigned Op0r = getReg(Op0, MBB, IP);
633 // Special case handling of: cmp R, i
634 if (Class == cByte || Class == cShort || Class == cInt)
635 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
636 uint64_t Op1v = cast<ConstantInt>(CI)->getRawValue();
638 // Mask off any upper bits of the constant, if there are any...
639 Op1v &= (1ULL << (8 << Class)) - 1;
641 // If this is a comparison against zero, emit more efficient code. We
642 // can't handle unsigned comparisons against zero unless they are == or
643 // !=. These should have been strength reduced already anyway.
644 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
645 static const unsigned TESTTab[] = {
646 X86::TESTrr8, X86::TESTrr16, X86::TESTrr32
648 BMI(MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
650 if (OpNum == 2) return 6; // Map jl -> js
651 if (OpNum == 3) return 7; // Map jg -> jns
655 static const unsigned CMPTab[] = {
656 X86::CMPri8, X86::CMPri16, X86::CMPri32
659 BMI(MBB, IP, CMPTab[Class], 2).addReg(Op0r).addZImm(Op1v);
663 unsigned Op1r = getReg(Op1, MBB, IP);
665 default: assert(0 && "Unknown type class!");
666 // Emit: cmp <var1>, <var2> (do the comparison). We can
667 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
670 BMI(MBB, IP, X86::CMPrr8, 2).addReg(Op0r).addReg(Op1r);
673 BMI(MBB, IP, X86::CMPrr16, 2).addReg(Op0r).addReg(Op1r);
676 BMI(MBB, IP, X86::CMPrr32, 2).addReg(Op0r).addReg(Op1r);
679 BMI(MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
680 BMI(MBB, IP, X86::FNSTSWr8, 0);
681 BMI(MBB, IP, X86::SAHF, 1);
685 if (OpNum < 2) { // seteq, setne
686 unsigned LoTmp = makeAnotherReg(Type::IntTy);
687 unsigned HiTmp = makeAnotherReg(Type::IntTy);
688 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
689 BMI(MBB, IP, X86::XORrr32, 2, LoTmp).addReg(Op0r).addReg(Op1r);
690 BMI(MBB, IP, X86::XORrr32, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
691 BMI(MBB, IP, X86::ORrr32, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
692 break; // Allow the sete or setne to be generated from flags set by OR
694 // Emit a sequence of code which compares the high and low parts once
695 // each, then uses a conditional move to handle the overflow case. For
696 // example, a setlt for long would generate code like this:
698 // AL = lo(op1) < lo(op2) // Signedness depends on operands
699 // BL = hi(op1) < hi(op2) // Always unsigned comparison
700 // dest = hi(op1) == hi(op2) ? AL : BL;
703 // FIXME: This would be much better if we had hierarchical register
704 // classes! Until then, hardcode registers so that we can deal with their
705 // aliases (because we don't have conditional byte moves).
707 BMI(MBB, IP, X86::CMPrr32, 2).addReg(Op0r).addReg(Op1r);
708 BMI(MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
709 BMI(MBB, IP, X86::CMPrr32, 2).addReg(Op0r+1).addReg(Op1r+1);
710 BMI(MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
711 BMI(MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
712 BMI(MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
713 BMI(MBB, IP, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
714 // NOTE: visitSetCondInst knows that the value is dumped into the BL
715 // register at this point for long values...
723 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
724 /// register, then move it to wherever the result should be.
726 void ISel::visitSetCondInst(SetCondInst &I) {
727 if (canFoldSetCCIntoBranch(&I)) return; // Fold this into a branch...
729 unsigned DestReg = getReg(I);
730 MachineBasicBlock::iterator MII = BB->end();
731 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
735 /// emitSetCCOperation - Common code shared between visitSetCondInst and
736 /// constant expression support.
737 void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
738 MachineBasicBlock::iterator &IP,
739 Value *Op0, Value *Op1, unsigned Opcode,
740 unsigned TargetReg) {
741 unsigned OpNum = getSetCCNumber(Opcode);
742 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
744 const Type *CompTy = Op0->getType();
745 unsigned CompClass = getClassB(CompTy);
746 bool isSigned = CompTy->isSigned() && CompClass != cFP;
748 if (CompClass != cLong || OpNum < 2) {
749 // Handle normal comparisons with a setcc instruction...
750 BMI(MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
752 // Handle long comparisons by copying the value which is already in BL into
753 // the register we want...
754 BMI(MBB, IP, X86::MOVrr8, 1, TargetReg).addReg(X86::BL);
761 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
762 /// operand, in the specified target register.
763 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
764 bool isUnsigned = VR.Ty->isUnsigned();
766 // Make sure we have the register number for this value...
767 unsigned Reg = VR.Val ? getReg(VR.Val) : VR.Reg;
769 switch (getClassB(VR.Ty)) {
771 // Extend value into target register (8->32)
773 BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(Reg);
775 BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(Reg);
778 // Extend value into target register (16->32)
780 BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(Reg);
782 BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(Reg);
785 // Move value into target register (32->32)
786 BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(Reg);
789 assert(0 && "Unpromotable operand class in promote32");
793 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
794 /// we have the following possibilities:
796 /// ret void: No return value, simply emit a 'ret' instruction
797 /// ret sbyte, ubyte : Extend value into EAX and return
798 /// ret short, ushort: Extend value into EAX and return
799 /// ret int, uint : Move value into EAX and return
800 /// ret pointer : Move value into EAX and return
801 /// ret long, ulong : Move value into EAX/EDX and return
802 /// ret float/double : Top of FP stack
804 void ISel::visitReturnInst(ReturnInst &I) {
805 if (I.getNumOperands() == 0) {
806 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
810 Value *RetVal = I.getOperand(0);
811 unsigned RetReg = getReg(RetVal);
812 switch (getClassB(RetVal->getType())) {
813 case cByte: // integral return values: extend or move into EAX and return
816 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
817 // Declare that EAX is live on exit
818 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
820 case cFP: // Floats & Doubles: Return in ST(0)
821 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
822 // Declare that top-of-stack is live on exit
823 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
826 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
827 BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
828 // Declare that EAX & EDX are live on exit
829 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX).addReg(X86::ESP);
834 // Emit a 'ret' instruction
835 BuildMI(BB, X86::RET, 0);
838 // getBlockAfter - Return the basic block which occurs lexically after the
840 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
841 Function::iterator I = BB; ++I; // Get iterator to next block
842 return I != BB->getParent()->end() ? &*I : 0;
845 /// visitBranchInst - Handle conditional and unconditional branches here. Note
846 /// that since code layout is frozen at this point, that if we are trying to
847 /// jump to a block that is the immediate successor of the current block, we can
848 /// just make a fall-through (but we don't currently).
850 void ISel::visitBranchInst(BranchInst &BI) {
851 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
853 if (!BI.isConditional()) { // Unconditional branch?
854 if (BI.getSuccessor(0) != NextBB)
855 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
859 // See if we can fold the setcc into the branch itself...
860 SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
862 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
863 // computed some other way...
864 unsigned condReg = getReg(BI.getCondition());
865 BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
866 if (BI.getSuccessor(1) == NextBB) {
867 if (BI.getSuccessor(0) != NextBB)
868 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
870 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
872 if (BI.getSuccessor(0) != NextBB)
873 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
878 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
879 MachineBasicBlock::iterator MII = BB->end();
880 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB, MII);
882 const Type *CompTy = SCI->getOperand(0)->getType();
883 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
886 // LLVM -> X86 signed X86 unsigned
887 // ----- ---------- ------------
895 // js // Used by comparison with 0 optimization
898 static const unsigned OpcodeTab[2][8] = {
899 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
900 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
904 if (BI.getSuccessor(0) != NextBB) {
905 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
906 if (BI.getSuccessor(1) != NextBB)
907 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
909 // Change to the inverse condition...
910 if (BI.getSuccessor(1) != NextBB) {
912 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
918 /// doCall - This emits an abstract call instruction, setting up the arguments
919 /// and the return value as appropriate. For the actual function call itself,
920 /// it inserts the specified CallMI instruction into the stream.
922 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
923 const std::vector<ValueRecord> &Args) {
925 // Count how many bytes are to be pushed on the stack...
926 unsigned NumBytes = 0;
929 for (unsigned i = 0, e = Args.size(); i != e; ++i)
930 switch (getClassB(Args[i].Ty)) {
931 case cByte: case cShort: case cInt:
932 NumBytes += 4; break;
934 NumBytes += 8; break;
936 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
938 default: assert(0 && "Unknown class!");
941 // Adjust the stack pointer for the new arguments...
942 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
944 // Arguments go on the stack in reverse order, as specified by the ABI.
945 unsigned ArgOffset = 0;
946 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
947 unsigned ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
948 switch (getClassB(Args[i].Ty)) {
951 // Promote arg to 32 bits wide into a temporary register...
952 unsigned R = makeAnotherReg(Type::UIntTy);
953 promote32(R, Args[i]);
954 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
955 X86::ESP, ArgOffset).addReg(R);
959 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
960 X86::ESP, ArgOffset).addReg(ArgReg);
963 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
964 X86::ESP, ArgOffset).addReg(ArgReg);
965 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
966 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
967 ArgOffset += 4; // 8 byte entry, not 4.
971 if (Args[i].Ty == Type::FloatTy) {
972 addRegOffset(BuildMI(BB, X86::FSTr32, 5),
973 X86::ESP, ArgOffset).addReg(ArgReg);
975 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
976 addRegOffset(BuildMI(BB, X86::FSTr64, 5),
977 X86::ESP, ArgOffset).addReg(ArgReg);
978 ArgOffset += 4; // 8 byte entry, not 4.
982 default: assert(0 && "Unknown class!");
987 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
990 BB->push_back(CallMI);
992 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
994 // If there is a return value, scavenge the result from the location the call
997 if (Ret.Ty != Type::VoidTy) {
998 unsigned DestClass = getClassB(Ret.Ty);
1003 // Integral results are in %eax, or the appropriate portion
1005 static const unsigned regRegMove[] = {
1006 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
1008 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1009 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1012 case cFP: // Floating-point return values live in %ST(0)
1013 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1015 case cLong: // Long values are left in EDX:EAX
1016 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
1017 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
1019 default: assert(0 && "Unknown class!");
1025 /// visitCallInst - Push args on stack and do a procedure call instruction.
1026 void ISel::visitCallInst(CallInst &CI) {
1027 MachineInstr *TheCall;
1028 if (Function *F = CI.getCalledFunction()) {
1029 // Is it an intrinsic function call?
1030 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
1031 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1035 // Emit a CALL instruction with PC-relative displacement.
1036 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1037 } else { // Emit an indirect call...
1038 unsigned Reg = getReg(CI.getCalledValue());
1039 TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
1042 std::vector<ValueRecord> Args;
1043 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1044 Args.push_back(ValueRecord(CI.getOperand(i)));
1046 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1047 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1051 void ISel::visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &CI) {
1052 unsigned TmpReg1, TmpReg2;
1054 case LLVMIntrinsic::va_start:
1055 // Get the address of the first vararg value...
1056 TmpReg1 = getReg(CI);
1057 addFrameReference(BuildMI(BB, X86::LEAr32, 5, TmpReg1), VarArgsFrameIndex);
1060 case LLVMIntrinsic::va_copy:
1061 TmpReg1 = getReg(CI);
1062 TmpReg2 = getReg(CI.getOperand(1));
1063 BuildMI(BB, X86::MOVrr32, 1, TmpReg1).addReg(TmpReg2);
1065 case LLVMIntrinsic::va_end: return; // Noop on X86
1067 case LLVMIntrinsic::longjmp:
1068 case LLVMIntrinsic::siglongjmp:
1069 BuildMI(BB, X86::CALLpcrel32, 1).addExternalSymbol("abort", true);
1072 case LLVMIntrinsic::setjmp:
1073 case LLVMIntrinsic::sigsetjmp:
1074 // Setjmp always returns zero...
1075 BuildMI(BB, X86::MOVir32, 1, getReg(CI)).addZImm(0);
1077 default: assert(0 && "Unknown intrinsic for X86!");
1082 /// visitSimpleBinary - Implement simple binary operators for integral types...
1083 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1085 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1086 unsigned DestReg = getReg(B);
1087 MachineBasicBlock::iterator MI = BB->end();
1088 emitSimpleBinaryOperation(BB, MI, B.getOperand(0), B.getOperand(1),
1089 OperatorClass, DestReg);
1092 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1093 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1096 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1097 /// and constant expression support.
1099 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1100 MachineBasicBlock::iterator &IP,
1101 Value *Op0, Value *Op1,
1102 unsigned OperatorClass, unsigned DestReg) {
1103 unsigned Class = getClassB(Op0->getType());
1105 // sub 0, X -> neg X
1106 if (OperatorClass == 1 && Class != cLong)
1107 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
1108 if (CI->isNullValue()) {
1109 unsigned op1Reg = getReg(Op1, MBB, IP);
1111 default: assert(0 && "Unknown class for this function!");
1113 BMI(MBB, IP, X86::NEGr8, 1, DestReg).addReg(op1Reg);
1116 BMI(MBB, IP, X86::NEGr16, 1, DestReg).addReg(op1Reg);
1119 BMI(MBB, IP, X86::NEGr32, 1, DestReg).addReg(op1Reg);
1124 if (!isa<ConstantInt>(Op1) || Class == cLong) {
1125 static const unsigned OpcodeTab[][4] = {
1126 // Arithmetic operators
1127 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD }, // ADD
1128 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB }, // SUB
1130 // Bitwise operators
1131 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
1132 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
1133 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
1136 bool isLong = false;
1137 if (Class == cLong) {
1139 Class = cInt; // Bottom 32 bits are handled just like ints
1142 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1143 assert(Opcode && "Floating point arguments to logical inst?");
1144 unsigned Op0r = getReg(Op0, MBB, IP);
1145 unsigned Op1r = getReg(Op1, MBB, IP);
1146 BMI(MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1148 if (isLong) { // Handle the upper 32 bits of long values...
1149 static const unsigned TopTab[] = {
1150 X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
1152 BMI(MBB, IP, TopTab[OperatorClass], 2,
1153 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1158 // Special case: op Reg, <const>
1159 ConstantInt *Op1C = cast<ConstantInt>(Op1);
1160 unsigned Op0r = getReg(Op0, MBB, IP);
1162 // xor X, -1 -> not X
1163 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1164 static unsigned const NOTTab[] = { X86::NOTr8, X86::NOTr16, X86::NOTr32 };
1165 BMI(MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
1169 // add X, -1 -> dec X
1170 if (OperatorClass == 0 && Op1C->isAllOnesValue()) {
1171 static unsigned const DECTab[] = { X86::DECr8, X86::DECr16, X86::DECr32 };
1172 BMI(MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1176 // add X, 1 -> inc X
1177 if (OperatorClass == 0 && Op1C->equalsInt(1)) {
1178 static unsigned const DECTab[] = { X86::INCr8, X86::INCr16, X86::INCr32 };
1179 BMI(MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1183 static const unsigned OpcodeTab[][3] = {
1184 // Arithmetic operators
1185 { X86::ADDri8, X86::ADDri16, X86::ADDri32 }, // ADD
1186 { X86::SUBri8, X86::SUBri16, X86::SUBri32 }, // SUB
1188 // Bitwise operators
1189 { X86::ANDri8, X86::ANDri16, X86::ANDri32 }, // AND
1190 { X86:: ORri8, X86:: ORri16, X86:: ORri32 }, // OR
1191 { X86::XORri8, X86::XORri16, X86::XORri32 }, // XOR
1194 assert(Class < 3 && "General code handles 64-bit integer types!");
1195 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1196 uint64_t Op1v = cast<ConstantInt>(Op1C)->getRawValue();
1198 // Mask off any upper bits of the constant, if there are any...
1199 Op1v &= (1ULL << (8 << Class)) - 1;
1200 BMI(MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addZImm(Op1v);
1203 /// doMultiply - Emit appropriate instructions to multiply together the
1204 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1205 /// result should be given as DestTy.
1207 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
1208 unsigned DestReg, const Type *DestTy,
1209 unsigned op0Reg, unsigned op1Reg) {
1210 unsigned Class = getClass(DestTy);
1212 case cFP: // Floating point multiply
1213 BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1217 BMI(BB, MBBI, Class == cInt ? X86::IMULrr32 : X86::IMULrr16, 2, DestReg)
1218 .addReg(op0Reg).addReg(op1Reg);
1221 // Must use the MUL instruction, which forces use of AL...
1222 BMI(MBB, MBBI, X86::MOVrr8, 1, X86::AL).addReg(op0Reg);
1223 BMI(MBB, MBBI, X86::MULr8, 1).addReg(op1Reg);
1224 BMI(MBB, MBBI, X86::MOVrr8, 1, DestReg).addReg(X86::AL);
1227 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
1231 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1232 // returns zero when the input is not exactly a power of two.
1233 static unsigned ExactLog2(unsigned Val) {
1234 if (Val == 0) return 0;
1237 if (Val & 1) return 0;
1244 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1245 MachineBasicBlock::iterator &IP,
1246 unsigned DestReg, const Type *DestTy,
1247 unsigned op0Reg, unsigned ConstRHS) {
1248 unsigned Class = getClass(DestTy);
1250 // If the element size is exactly a power of 2, use a shift to get it.
1251 if (unsigned Shift = ExactLog2(ConstRHS)) {
1253 default: assert(0 && "Unknown class for this function!");
1255 BMI(MBB, IP, X86::SHLir32, 2, DestReg).addReg(op0Reg).addZImm(Shift-1);
1258 BMI(MBB, IP, X86::SHLir32, 2, DestReg).addReg(op0Reg).addZImm(Shift-1);
1261 BMI(MBB, IP, X86::SHLir32, 2, DestReg).addReg(op0Reg).addZImm(Shift-1);
1266 if (Class == cShort) {
1267 BMI(MBB, IP, X86::IMULri16, 2, DestReg).addReg(op0Reg).addZImm(ConstRHS);
1269 } else if (Class == cInt) {
1270 BMI(MBB, IP, X86::IMULri32, 2, DestReg).addReg(op0Reg).addZImm(ConstRHS);
1274 // Most general case, emit a normal multiply...
1275 static const unsigned MOVirTab[] = {
1276 X86::MOVir8, X86::MOVir16, X86::MOVir32
1279 unsigned TmpReg = makeAnotherReg(DestTy);
1280 BMI(MBB, IP, MOVirTab[Class], 1, TmpReg).addZImm(ConstRHS);
1282 // Emit a MUL to multiply the register holding the index by
1283 // elementSize, putting the result in OffsetReg.
1284 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
1287 /// visitMul - Multiplies are not simple binary operators because they must deal
1288 /// with the EAX register explicitly.
1290 void ISel::visitMul(BinaryOperator &I) {
1291 unsigned Op0Reg = getReg(I.getOperand(0));
1292 unsigned DestReg = getReg(I);
1294 // Simple scalar multiply?
1295 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1296 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1297 unsigned Val = (unsigned)CI->getRawValue(); // Cannot be 64-bit constant
1298 MachineBasicBlock::iterator MBBI = BB->end();
1299 doMultiplyConst(BB, MBBI, DestReg, I.getType(), Op0Reg, Val);
1301 unsigned Op1Reg = getReg(I.getOperand(1));
1302 MachineBasicBlock::iterator MBBI = BB->end();
1303 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1306 unsigned Op1Reg = getReg(I.getOperand(1));
1308 // Long value. We have to do things the hard way...
1309 // Multiply the two low parts... capturing carry into EDX
1310 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
1311 BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg); // AL*BL
1313 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1314 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX); // AL*BL
1315 BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1317 MachineBasicBlock::iterator MBBI = BB->end();
1318 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
1319 BMI(BB, MBBI, X86::IMULrr32, 2, AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1321 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1322 BuildMI(BB, X86::ADDrr32, 2, // AH*BL+(AL*BL >> 32)
1323 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1326 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1327 BMI(BB, MBBI, X86::IMULrr32, 2, ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1329 BuildMI(BB, X86::ADDrr32, 2, // AL*BH + AH*BL + (AL*BL >> 32)
1330 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1335 /// visitDivRem - Handle division and remainder instructions... these
1336 /// instruction both require the same instructions to be generated, they just
1337 /// select the result from a different register. Note that both of these
1338 /// instructions work differently for signed and unsigned operands.
1340 void ISel::visitDivRem(BinaryOperator &I) {
1341 unsigned Class = getClass(I.getType());
1342 unsigned Op0Reg, Op1Reg, ResultReg = getReg(I);
1345 case cFP: // Floating point divide
1346 if (I.getOpcode() == Instruction::Div) {
1347 Op0Reg = getReg(I.getOperand(0));
1348 Op1Reg = getReg(I.getOperand(1));
1349 BuildMI(BB, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1350 } else { // Floating point remainder...
1351 MachineInstr *TheCall =
1352 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1353 std::vector<ValueRecord> Args;
1354 Args.push_back(ValueRecord(I.getOperand(0)));
1355 Args.push_back(ValueRecord(I.getOperand(1)));
1356 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1360 static const char *FnName[] =
1361 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1363 unsigned NameIdx = I.getType()->isUnsigned()*2;
1364 NameIdx += I.getOpcode() == Instruction::Div;
1365 MachineInstr *TheCall =
1366 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1368 std::vector<ValueRecord> Args;
1369 Args.push_back(ValueRecord(I.getOperand(0)));
1370 Args.push_back(ValueRecord(I.getOperand(1)));
1371 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1374 case cByte: case cShort: case cInt:
1375 break; // Small integrals, handled below...
1376 default: assert(0 && "Unknown class!");
1379 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
1380 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1381 static const unsigned SarOpcode[]={ X86::SARir8, X86::SARir16, X86::SARir32 };
1382 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
1383 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1385 static const unsigned DivOpcode[][4] = {
1386 { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 }, // Unsigned division
1387 { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 }, // Signed division
1390 bool isSigned = I.getType()->isSigned();
1391 unsigned Reg = Regs[Class];
1392 unsigned ExtReg = ExtRegs[Class];
1394 // Put the first operand into one of the A registers...
1395 Op0Reg = getReg(I.getOperand(0));
1396 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1399 // Emit a sign extension instruction...
1400 unsigned ShiftResult = makeAnotherReg(I.getType());
1401 BuildMI(BB, SarOpcode[Class], 2, ShiftResult).addReg(Op0Reg).addZImm(31);
1402 BuildMI(BB, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
1404 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
1405 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
1408 // Emit the appropriate divide or remainder instruction...
1409 Op1Reg = getReg(I.getOperand(1));
1410 BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1412 // Figure out which register we want to pick the result out of...
1413 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
1415 // Put the result into the destination register...
1416 BuildMI(BB, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1420 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1421 /// for constant immediate shift values, and for constant immediate
1422 /// shift values equal to 1. Even the general case is sort of special,
1423 /// because the shift amount has to be in CL, not just any old register.
1425 void ISel::visitShiftInst(ShiftInst &I) {
1426 unsigned SrcReg = getReg(I.getOperand(0));
1427 unsigned DestReg = getReg(I);
1428 bool isLeftShift = I.getOpcode() == Instruction::Shl;
1429 bool isSigned = I.getType()->isSigned();
1430 unsigned Class = getClass(I.getType());
1432 static const unsigned ConstantOperand[][4] = {
1433 { X86::SHRir8, X86::SHRir16, X86::SHRir32, X86::SHRDir32 }, // SHR
1434 { X86::SARir8, X86::SARir16, X86::SARir32, X86::SHRDir32 }, // SAR
1435 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SHL
1436 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SAL = SHL
1439 static const unsigned NonConstantOperand[][4] = {
1440 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32 }, // SHR
1441 { X86::SARrr8, X86::SARrr16, X86::SARrr32 }, // SAR
1442 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SHL
1443 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SAL = SHL
1446 // Longs, as usual, are handled specially...
1447 if (Class == cLong) {
1448 // If we have a constant shift, we can generate much more efficient code
1449 // than otherwise...
1451 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1452 unsigned Amount = CUI->getValue();
1454 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1456 BuildMI(BB, Opc[3], 3,
1457 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1458 BuildMI(BB, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1460 BuildMI(BB, Opc[3], 3,
1461 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addZImm(Amount);
1462 BuildMI(BB, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1464 } else { // Shifting more than 32 bits
1467 BuildMI(BB, X86::SHLir32, 2,DestReg+1).addReg(SrcReg).addZImm(Amount);
1468 BuildMI(BB, X86::MOVir32, 1,DestReg ).addZImm(0);
1470 unsigned Opcode = isSigned ? X86::SARir32 : X86::SHRir32;
1471 BuildMI(BB, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1472 BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1476 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1478 if (!isLeftShift && isSigned) {
1479 // If this is a SHR of a Long, then we need to do funny sign extension
1480 // stuff. TmpReg gets the value to use as the high-part if we are
1481 // shifting more than 32 bits.
1482 BuildMI(BB, X86::SARir32, 2, TmpReg).addReg(SrcReg).addZImm(31);
1484 // Other shifts use a fixed zero value if the shift is more than 32
1486 BuildMI(BB, X86::MOVir32, 1, TmpReg).addZImm(0);
1489 // Initialize CL with the shift amount...
1490 unsigned ShiftAmount = getReg(I.getOperand(1));
1491 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(ShiftAmount);
1493 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1494 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
1496 // TmpReg2 = shld inHi, inLo
1497 BuildMI(BB, X86::SHLDrr32, 2, TmpReg2).addReg(SrcReg+1).addReg(SrcReg);
1498 // TmpReg3 = shl inLo, CL
1499 BuildMI(BB, X86::SHLrr32, 1, TmpReg3).addReg(SrcReg);
1501 // Set the flags to indicate whether the shift was by more than 32 bits.
1502 BuildMI(BB, X86::TESTri8, 2).addReg(X86::CL).addZImm(32);
1504 // DestHi = (>32) ? TmpReg3 : TmpReg2;
1505 BuildMI(BB, X86::CMOVNErr32, 2,
1506 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
1507 // DestLo = (>32) ? TmpReg : TmpReg3;
1508 BuildMI(BB, X86::CMOVNErr32, 2, DestReg).addReg(TmpReg3).addReg(TmpReg);
1510 // TmpReg2 = shrd inLo, inHi
1511 BuildMI(BB, X86::SHRDrr32, 2, TmpReg2).addReg(SrcReg).addReg(SrcReg+1);
1512 // TmpReg3 = s[ah]r inHi, CL
1513 BuildMI(BB, isSigned ? X86::SARrr32 : X86::SHRrr32, 1, TmpReg3)
1516 // Set the flags to indicate whether the shift was by more than 32 bits.
1517 BuildMI(BB, X86::TESTri8, 2).addReg(X86::CL).addZImm(32);
1519 // DestLo = (>32) ? TmpReg3 : TmpReg2;
1520 BuildMI(BB, X86::CMOVNErr32, 2,
1521 DestReg).addReg(TmpReg2).addReg(TmpReg3);
1523 // DestHi = (>32) ? TmpReg : TmpReg3;
1524 BuildMI(BB, X86::CMOVNErr32, 2,
1525 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
1531 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1532 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1533 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
1535 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1536 BuildMI(BB, Opc[Class], 2, DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1537 } else { // The shift amount is non-constant.
1538 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
1540 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1541 BuildMI(BB, Opc[Class], 1, DestReg).addReg(SrcReg);
1546 /// EmitByteSwap - Byteswap SrcReg into DestReg.
1548 void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
1549 // Emit the byte swap instruction...
1552 // No byteswap necessary for 8 bit value...
1553 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(SrcReg);
1556 // Use the 32 bit bswap instruction to do a 32 bit swap...
1557 BuildMI(BB, X86::BSWAPr32, 1, DestReg).addReg(SrcReg);
1561 // For 16 bit we have to use an xchg instruction, because there is no
1562 // 16-bit bswap. XCHG is necessarily not in SSA form, so we force things
1563 // into AX to do the xchg.
1565 BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(SrcReg);
1566 BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
1567 .addReg(X86::AH, MOTy::UseAndDef);
1568 BuildMI(BB, X86::MOVrr16, 1, DestReg).addReg(X86::AX);
1570 default: assert(0 && "Cannot byteswap this class!");
1575 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
1576 /// instruction. The load and store instructions are the only place where we
1577 /// need to worry about the memory layout of the target machine.
1579 void ISel::visitLoadInst(LoadInst &I) {
1580 unsigned SrcAddrReg = getReg(I.getOperand(0));
1581 unsigned DestReg = getReg(I);
1583 unsigned Class = getClassB(I.getType());
1585 if (Class == cLong) {
1586 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), SrcAddrReg);
1587 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), SrcAddrReg, 4);
1591 static const unsigned Opcodes[] = {
1592 X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, X86::FLDr32
1594 unsigned Opcode = Opcodes[Class];
1595 if (I.getType() == Type::DoubleTy) Opcode = X86::FLDr64;
1596 addDirectMem(BuildMI(BB, Opcode, 4, DestReg), SrcAddrReg);
1599 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1602 void ISel::visitStoreInst(StoreInst &I) {
1603 unsigned ValReg = getReg(I.getOperand(0));
1604 unsigned AddressReg = getReg(I.getOperand(1));
1606 const Type *ValTy = I.getOperand(0)->getType();
1607 unsigned Class = getClassB(ValTy);
1609 if (Class == cLong) {
1610 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(ValReg);
1611 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg,4).addReg(ValReg+1);
1615 static const unsigned Opcodes[] = {
1616 X86::MOVrm8, X86::MOVrm16, X86::MOVrm32, X86::FSTr32
1618 unsigned Opcode = Opcodes[Class];
1619 if (ValTy == Type::DoubleTy) Opcode = X86::FSTr64;
1620 addDirectMem(BuildMI(BB, Opcode, 1+4), AddressReg).addReg(ValReg);
1624 /// visitCastInst - Here we have various kinds of copying with or without
1625 /// sign extension going on.
1626 void ISel::visitCastInst(CastInst &CI) {
1627 Value *Op = CI.getOperand(0);
1628 // If this is a cast from a 32-bit integer to a Long type, and the only uses
1629 // of the case are GEP instructions, then the cast does not need to be
1630 // generated explicitly, it will be folded into the GEP.
1631 if (CI.getType() == Type::LongTy &&
1632 (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
1633 bool AllUsesAreGEPs = true;
1634 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
1635 if (!isa<GetElementPtrInst>(*I)) {
1636 AllUsesAreGEPs = false;
1640 // No need to codegen this cast if all users are getelementptr instrs...
1641 if (AllUsesAreGEPs) return;
1644 unsigned DestReg = getReg(CI);
1645 MachineBasicBlock::iterator MI = BB->end();
1646 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
1649 /// emitCastOperation - Common code shared between visitCastInst and
1650 /// constant expression cast support.
1651 void ISel::emitCastOperation(MachineBasicBlock *BB,
1652 MachineBasicBlock::iterator &IP,
1653 Value *Src, const Type *DestTy,
1655 unsigned SrcReg = getReg(Src, BB, IP);
1656 const Type *SrcTy = Src->getType();
1657 unsigned SrcClass = getClassB(SrcTy);
1658 unsigned DestClass = getClassB(DestTy);
1660 // Implement casts to bool by using compare on the operand followed by set if
1661 // not zero on the result.
1662 if (DestTy == Type::BoolTy) {
1665 BMI(BB, IP, X86::TESTrr8, 2).addReg(SrcReg).addReg(SrcReg);
1668 BMI(BB, IP, X86::TESTrr16, 2).addReg(SrcReg).addReg(SrcReg);
1671 BMI(BB, IP, X86::TESTrr32, 2).addReg(SrcReg).addReg(SrcReg);
1674 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1675 BMI(BB, IP, X86::ORrr32, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
1679 assert(0 && "FIXME: implement cast FP to bool");
1683 // If the zero flag is not set, then the value is true, set the byte to
1685 BMI(BB, IP, X86::SETNEr, 1, DestReg);
1689 static const unsigned RegRegMove[] = {
1690 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
1693 // Implement casts between values of the same type class (as determined by
1694 // getClass) by using a register-to-register move.
1695 if (SrcClass == DestClass) {
1696 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
1697 BMI(BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
1698 } else if (SrcClass == cFP) {
1699 if (SrcTy == Type::FloatTy) { // double -> float
1700 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
1701 BMI(BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
1702 } else { // float -> double
1703 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
1704 "Unknown cFP member!");
1705 // Truncate from double to float by storing to memory as short, then
1707 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
1708 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
1709 addFrameReference(BMI(BB, IP, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
1710 addFrameReference(BMI(BB, IP, X86::FLDr32, 5, DestReg), FrameIdx);
1712 } else if (SrcClass == cLong) {
1713 BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1714 BMI(BB, IP, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
1716 assert(0 && "Cannot handle this type of cast instruction!");
1722 // Handle cast of SMALLER int to LARGER int using a move with sign extension
1723 // or zero extension, depending on whether the source type was signed.
1724 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
1725 SrcClass < DestClass) {
1726 bool isLong = DestClass == cLong;
1727 if (isLong) DestClass = cInt;
1729 static const unsigned Opc[][4] = {
1730 { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
1731 { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 } // u
1734 bool isUnsigned = SrcTy->isUnsigned();
1735 BMI(BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
1736 DestReg).addReg(SrcReg);
1738 if (isLong) { // Handle upper 32 bits as appropriate...
1739 if (isUnsigned) // Zero out top bits...
1740 BMI(BB, IP, X86::MOVir32, 1, DestReg+1).addZImm(0);
1741 else // Sign extend bottom half...
1742 BMI(BB, IP, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
1747 // Special case long -> int ...
1748 if (SrcClass == cLong && DestClass == cInt) {
1749 BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1753 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
1754 // move out of AX or AL.
1755 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
1756 && SrcClass > DestClass) {
1757 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
1758 BMI(BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
1759 BMI(BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
1763 // Handle casts from integer to floating point now...
1764 if (DestClass == cFP) {
1765 // Promote the integer to a type supported by FLD. We do this because there
1766 // are no unsigned FLD instructions, so we must promote an unsigned value to
1767 // a larger signed value, then use FLD on the larger value.
1769 const Type *PromoteType = 0;
1770 unsigned PromoteOpcode;
1771 switch (SrcTy->getPrimitiveID()) {
1772 case Type::BoolTyID:
1773 case Type::SByteTyID:
1774 // We don't have the facilities for directly loading byte sized data from
1775 // memory (even signed). Promote it to 16 bits.
1776 PromoteType = Type::ShortTy;
1777 PromoteOpcode = X86::MOVSXr16r8;
1779 case Type::UByteTyID:
1780 PromoteType = Type::ShortTy;
1781 PromoteOpcode = X86::MOVZXr16r8;
1783 case Type::UShortTyID:
1784 PromoteType = Type::IntTy;
1785 PromoteOpcode = X86::MOVZXr32r16;
1787 case Type::UIntTyID: {
1788 // Make a 64 bit temporary... and zero out the top of it...
1789 unsigned TmpReg = makeAnotherReg(Type::LongTy);
1790 BMI(BB, IP, X86::MOVrr32, 1, TmpReg).addReg(SrcReg);
1791 BMI(BB, IP, X86::MOVir32, 1, TmpReg+1).addZImm(0);
1792 SrcTy = Type::LongTy;
1797 case Type::ULongTyID:
1798 assert("FIXME: not implemented: cast ulong X to fp type!");
1799 default: // No promotion needed...
1804 unsigned TmpReg = makeAnotherReg(PromoteType);
1805 BMI(BB, IP, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
1806 1, TmpReg).addReg(SrcReg);
1807 SrcTy = PromoteType;
1808 SrcClass = getClass(PromoteType);
1812 // Spill the integer to memory and reload it from there...
1814 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
1816 if (SrcClass == cLong) {
1817 addFrameReference(BMI(BB, IP, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
1818 addFrameReference(BMI(BB, IP, X86::MOVrm32, 5),
1819 FrameIdx, 4).addReg(SrcReg+1);
1821 static const unsigned Op1[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1822 addFrameReference(BMI(BB, IP, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
1825 static const unsigned Op2[] =
1826 { 0/*byte*/, X86::FILDr16, X86::FILDr32, 0/*FP*/, X86::FILDr64 };
1827 addFrameReference(BMI(BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
1831 // Handle casts from floating point to integer now...
1832 if (SrcClass == cFP) {
1833 // Change the floating point control register to use "round towards zero"
1834 // mode when truncating to an integer value.
1836 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
1837 addFrameReference(BMI(BB, IP, X86::FNSTCWm16, 4), CWFrameIdx);
1839 // Load the old value of the high byte of the control word...
1840 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
1841 addFrameReference(BMI(BB, IP, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
1843 // Set the high part to be round to zero...
1844 addFrameReference(BMI(BB, IP, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
1846 // Reload the modified control word now...
1847 addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
1849 // Restore the memory image of control word to original value
1850 addFrameReference(BMI(BB, IP, X86::MOVrm8, 5),
1851 CWFrameIdx, 1).addReg(HighPartOfCW);
1853 // We don't have the facilities for directly storing byte sized data to
1854 // memory. Promote it to 16 bits. We also must promote unsigned values to
1855 // larger classes because we only have signed FP stores.
1856 unsigned StoreClass = DestClass;
1857 const Type *StoreTy = DestTy;
1858 if (StoreClass == cByte || DestTy->isUnsigned())
1859 switch (StoreClass) {
1860 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
1861 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
1862 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
1863 // The following treatment of cLong may not be perfectly right,
1864 // but it survives chains of casts of the form
1865 // double->ulong->double.
1866 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
1867 default: assert(0 && "Unknown store class!");
1870 // Spill the integer to memory and reload it from there...
1872 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
1874 static const unsigned Op1[] =
1875 { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
1876 addFrameReference(BMI(BB, IP, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
1878 if (DestClass == cLong) {
1879 addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg), FrameIdx);
1880 addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
1882 static const unsigned Op2[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
1883 addFrameReference(BMI(BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
1886 // Reload the original control word now...
1887 addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
1891 // Anything we haven't handled already, we can't (yet) handle at all.
1892 assert(0 && "Unhandled cast instruction!");
1896 /// visitVANextInst - Implement the va_next instruction...
1898 void ISel::visitVANextInst(VANextInst &I) {
1899 unsigned VAList = getReg(I.getOperand(0));
1900 unsigned DestReg = getReg(I);
1903 switch (I.getArgType()->getPrimitiveID()) {
1906 assert(0 && "Error: bad type for va_next instruction!");
1908 case Type::PointerTyID:
1909 case Type::UIntTyID:
1913 case Type::ULongTyID:
1914 case Type::LongTyID:
1915 case Type::DoubleTyID:
1920 // Increment the VAList pointer...
1921 BuildMI(BB, X86::ADDri32, 2, DestReg).addReg(VAList).addZImm(Size);
1924 void ISel::visitVAArgInst(VAArgInst &I) {
1925 unsigned VAList = getReg(I.getOperand(0));
1926 unsigned DestReg = getReg(I);
1928 switch (I.getType()->getPrimitiveID()) {
1931 assert(0 && "Error: bad type for va_next instruction!");
1933 case Type::PointerTyID:
1934 case Type::UIntTyID:
1936 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1938 case Type::ULongTyID:
1939 case Type::LongTyID:
1940 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
1941 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), VAList, 4);
1943 case Type::DoubleTyID:
1944 addDirectMem(BuildMI(BB, X86::FLDr64, 4, DestReg), VAList);
1950 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
1951 unsigned outputReg = getReg(I);
1952 MachineBasicBlock::iterator MI = BB->end();
1953 emitGEPOperation(BB, MI, I.getOperand(0),
1954 I.op_begin()+1, I.op_end(), outputReg);
1957 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
1958 MachineBasicBlock::iterator &IP,
1959 Value *Src, User::op_iterator IdxBegin,
1960 User::op_iterator IdxEnd, unsigned TargetReg) {
1961 const TargetData &TD = TM.getTargetData();
1962 const Type *Ty = Src->getType();
1963 unsigned BaseReg = getReg(Src, MBB, IP);
1965 // GEPs have zero or more indices; we must perform a struct access
1966 // or array access for each one.
1967 for (GetElementPtrInst::op_iterator oi = IdxBegin,
1968 oe = IdxEnd; oi != oe; ++oi) {
1970 unsigned NextReg = BaseReg;
1971 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1972 // It's a struct access. idx is the index into the structure,
1973 // which names the field. This index must have ubyte type.
1974 const ConstantUInt *CUI = cast<ConstantUInt>(idx);
1975 assert(CUI->getType() == Type::UByteTy
1976 && "Funny-looking structure index in GEP");
1977 // Use the TargetData structure to pick out what the layout of
1978 // the structure is in memory. Since the structure index must
1979 // be constant, we can get its value and use it to find the
1980 // right byte offset from the StructLayout class's list of
1981 // structure member offsets.
1982 unsigned idxValue = CUI->getValue();
1983 unsigned FieldOff = TD.getStructLayout(StTy)->MemberOffsets[idxValue];
1985 NextReg = makeAnotherReg(Type::UIntTy);
1986 // Emit an ADD to add FieldOff to the basePtr.
1987 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(FieldOff);
1989 // The next type is the member of the structure selected by the
1991 Ty = StTy->getElementTypes()[idxValue];
1992 } else if (const SequentialType *SqTy = cast<SequentialType>(Ty)) {
1993 // It's an array or pointer access: [ArraySize x ElementType].
1995 // idx is the index into the array. Unlike with structure
1996 // indices, we may not know its actual value at code-generation
1998 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2000 // Most GEP instructions use a [cast (int/uint) to LongTy] as their
2001 // operand on X86. Handle this case directly now...
2002 if (CastInst *CI = dyn_cast<CastInst>(idx))
2003 if (CI->getOperand(0)->getType() == Type::IntTy ||
2004 CI->getOperand(0)->getType() == Type::UIntTy)
2005 idx = CI->getOperand(0);
2007 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2008 // must find the size of the pointed-to type (Not coincidentally, the next
2009 // type is the type of the elements in the array).
2010 Ty = SqTy->getElementType();
2011 unsigned elementSize = TD.getTypeSize(Ty);
2013 // If idxReg is a constant, we don't need to perform the multiply!
2014 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2015 if (!CSI->isNullValue()) {
2016 unsigned Offset = elementSize*CSI->getValue();
2017 NextReg = makeAnotherReg(Type::UIntTy);
2018 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(Offset);
2020 } else if (elementSize == 1) {
2021 // If the element size is 1, we don't have to multiply, just add
2022 unsigned idxReg = getReg(idx, MBB, IP);
2023 NextReg = makeAnotherReg(Type::UIntTy);
2024 BMI(MBB, IP, X86::ADDrr32, 2, NextReg).addReg(BaseReg).addReg(idxReg);
2026 unsigned idxReg = getReg(idx, MBB, IP);
2027 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2029 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2031 // Emit an ADD to add OffsetReg to the basePtr.
2032 NextReg = makeAnotherReg(Type::UIntTy);
2033 BMI(MBB, IP, X86::ADDrr32, 2,NextReg).addReg(BaseReg).addReg(OffsetReg);
2036 // Now that we are here, further indices refer to subtypes of this
2037 // one, so we don't need to worry about BaseReg itself, anymore.
2040 // After we have processed all the indices, the result is left in
2041 // BaseReg. Move it to the register where we were expected to
2042 // put the answer. A 32-bit move should do it, because we are in
2044 BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
2048 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2049 /// frame manager, otherwise do it the hard way.
2051 void ISel::visitAllocaInst(AllocaInst &I) {
2052 // Find the data size of the alloca inst's getAllocatedType.
2053 const Type *Ty = I.getAllocatedType();
2054 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2056 // If this is a fixed size alloca in the entry block for the function,
2057 // statically stack allocate the space.
2059 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
2060 if (I.getParent() == I.getParent()->getParent()->begin()) {
2061 TySize *= CUI->getValue(); // Get total allocated size...
2062 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
2064 // Create a new stack object using the frame manager...
2065 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
2066 addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
2071 // Create a register to hold the temporary result of multiplying the type size
2072 // constant by the variable amount.
2073 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2074 unsigned SrcReg1 = getReg(I.getArraySize());
2076 // TotalSizeReg = mul <numelements>, <TypeSize>
2077 MachineBasicBlock::iterator MBBI = BB->end();
2078 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2080 // AddedSize = add <TotalSizeReg>, 15
2081 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2082 BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
2084 // AlignedSize = and <AddedSize>, ~15
2085 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2086 BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
2088 // Subtract size from stack pointer, thereby allocating some space.
2089 BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
2091 // Put a pointer to the space into the result register, by copying
2092 // the stack pointer.
2093 BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
2095 // Inform the Frame Information that we have just allocated a variable-sized
2097 F->getFrameInfo()->CreateVariableSizedObject();
2100 /// visitMallocInst - Malloc instructions are code generated into direct calls
2101 /// to the library malloc.
2103 void ISel::visitMallocInst(MallocInst &I) {
2104 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2107 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2108 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2110 Arg = makeAnotherReg(Type::UIntTy);
2111 unsigned Op0Reg = getReg(I.getOperand(0));
2112 MachineBasicBlock::iterator MBBI = BB->end();
2113 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2116 std::vector<ValueRecord> Args;
2117 Args.push_back(ValueRecord(Arg, Type::UIntTy));
2118 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2119 1).addExternalSymbol("malloc", true);
2120 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
2124 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2127 void ISel::visitFreeInst(FreeInst &I) {
2128 std::vector<ValueRecord> Args;
2129 Args.push_back(ValueRecord(I.getOperand(0)));
2130 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2131 1).addExternalSymbol("free", true);
2132 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
2136 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
2137 /// into a machine code representation is a very simple peep-hole fashion. The
2138 /// generated code sucks but the implementation is nice and simple.
2140 FunctionPass *createX86SimpleInstructionSelector(TargetMachine &TM) {
2141 return new ISel(TM);