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 "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/IntrinsicLowering.h"
22 #include "llvm/Pass.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 "Support/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->getPrimitiveID()) {
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 ISel : public FunctionPass, InstVisitor<ISel> {
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 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
91 /// runOnFunction - Top level implementation of instruction selection for
92 /// the entire function.
94 bool runOnFunction(Function &Fn) {
95 // First pass over the function, lower any unknown intrinsic functions
96 // with the IntrinsicLowering class.
97 LowerUnknownIntrinsicFunctionCalls(Fn);
99 F = &MachineFunction::construct(&Fn, TM);
101 // Create all of the machine basic blocks for the function...
102 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
103 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
107 // Set up a frame object for the return address. This is used by the
108 // llvm.returnaddress & llvm.frameaddress intrinisics.
109 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
111 // Copy incoming arguments off of the stack...
112 LoadArgumentsToVirtualRegs(Fn);
114 // Instruction select everything except PHI nodes
117 // Select the PHI nodes
120 // Insert the FP_REG_KILL instructions into blocks that need them.
126 // We always build a machine code representation for the function
130 virtual const char *getPassName() const {
131 return "X86 Simple Instruction Selection";
134 /// visitBasicBlock - This method is called when we are visiting a new basic
135 /// block. This simply creates a new MachineBasicBlock to emit code into
136 /// and adds it to the current MachineFunction. Subsequent visit* for
137 /// instructions will be invoked for all instructions in the basic block.
139 void visitBasicBlock(BasicBlock &LLVM_BB) {
140 BB = MBBMap[&LLVM_BB];
143 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
144 /// function, lowering any calls to unknown intrinsic functions into the
145 /// equivalent LLVM code.
147 void LowerUnknownIntrinsicFunctionCalls(Function &F);
149 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
150 /// from the stack into virtual registers.
152 void LoadArgumentsToVirtualRegs(Function &F);
154 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
155 /// because we have to generate our sources into the source basic blocks,
156 /// not the current one.
158 void SelectPHINodes();
160 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
161 /// that need them. This only occurs due to the floating point stackifier
162 /// not being aggressive enough to handle arbitrary global stackification.
164 void InsertFPRegKills();
166 // Visitation methods for various instructions. These methods simply emit
167 // fixed X86 code for each instruction.
170 // Control flow operators
171 void visitReturnInst(ReturnInst &RI);
172 void visitBranchInst(BranchInst &BI);
178 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
179 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
181 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
182 const std::vector<ValueRecord> &Args);
183 void visitCallInst(CallInst &I);
184 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
186 // Arithmetic operators
187 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
188 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
189 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
190 void visitMul(BinaryOperator &B);
192 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
193 void visitRem(BinaryOperator &B) { visitDivRem(B); }
194 void visitDivRem(BinaryOperator &B);
197 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
198 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
199 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
201 // Comparison operators...
202 void visitSetCondInst(SetCondInst &I);
203 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
204 MachineBasicBlock *MBB,
205 MachineBasicBlock::iterator MBBI);
206 void visitSelectInst(SelectInst &SI);
209 // Memory Instructions
210 void visitLoadInst(LoadInst &I);
211 void visitStoreInst(StoreInst &I);
212 void visitGetElementPtrInst(GetElementPtrInst &I);
213 void visitAllocaInst(AllocaInst &I);
214 void visitMallocInst(MallocInst &I);
215 void visitFreeInst(FreeInst &I);
218 void visitShiftInst(ShiftInst &I);
219 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
220 void visitCastInst(CastInst &I);
221 void visitVANextInst(VANextInst &I);
222 void visitVAArgInst(VAArgInst &I);
224 void visitInstruction(Instruction &I) {
225 std::cerr << "Cannot instruction select: " << I;
229 /// promote32 - Make a value 32-bits wide, and put it somewhere.
231 void promote32(unsigned targetReg, const ValueRecord &VR);
233 /// getAddressingMode - Get the addressing mode to use to address the
234 /// specified value. The returned value should be used with addFullAddress.
235 void getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
236 unsigned &IndexReg, unsigned &Disp);
239 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
241 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
242 std::vector<Value*> &GEPOps,
243 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
244 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
246 /// isGEPFoldable - Return true if the specified GEP can be completely
247 /// folded into the addressing mode of a load/store or lea instruction.
248 bool isGEPFoldable(MachineBasicBlock *MBB,
249 Value *Src, User::op_iterator IdxBegin,
250 User::op_iterator IdxEnd, unsigned &BaseReg,
251 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
253 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
254 /// constant expression GEP support.
256 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
257 Value *Src, User::op_iterator IdxBegin,
258 User::op_iterator IdxEnd, unsigned TargetReg);
260 /// emitCastOperation - Common code shared between visitCastInst and
261 /// constant expression cast support.
263 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
264 Value *Src, const Type *DestTy, unsigned TargetReg);
266 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
267 /// and constant expression support.
269 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
270 MachineBasicBlock::iterator IP,
271 Value *Op0, Value *Op1,
272 unsigned OperatorClass, unsigned TargetReg);
274 /// emitBinaryFPOperation - This method handles emission of floating point
275 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
276 void emitBinaryFPOperation(MachineBasicBlock *BB,
277 MachineBasicBlock::iterator IP,
278 Value *Op0, Value *Op1,
279 unsigned OperatorClass, unsigned TargetReg);
281 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
282 Value *Op0, Value *Op1, unsigned TargetReg);
284 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
285 unsigned DestReg, const Type *DestTy,
286 unsigned Op0Reg, unsigned Op1Reg);
287 void doMultiplyConst(MachineBasicBlock *MBB,
288 MachineBasicBlock::iterator MBBI,
289 unsigned DestReg, const Type *DestTy,
290 unsigned Op0Reg, unsigned Op1Val);
292 void emitDivRemOperation(MachineBasicBlock *BB,
293 MachineBasicBlock::iterator IP,
294 Value *Op0, Value *Op1, bool isDiv,
297 /// emitSetCCOperation - Common code shared between visitSetCondInst and
298 /// constant expression support.
300 void emitSetCCOperation(MachineBasicBlock *BB,
301 MachineBasicBlock::iterator IP,
302 Value *Op0, Value *Op1, unsigned Opcode,
305 /// emitShiftOperation - Common code shared between visitShiftInst and
306 /// constant expression support.
308 void emitShiftOperation(MachineBasicBlock *MBB,
309 MachineBasicBlock::iterator IP,
310 Value *Op, Value *ShiftAmount, bool isLeftShift,
311 const Type *ResultTy, unsigned DestReg);
313 /// emitSelectOperation - Common code shared between visitSelectInst and the
314 /// constant expression support.
315 void emitSelectOperation(MachineBasicBlock *MBB,
316 MachineBasicBlock::iterator IP,
317 Value *Cond, Value *TrueVal, Value *FalseVal,
320 /// copyConstantToRegister - Output the instructions required to put the
321 /// specified constant into the specified register.
323 void copyConstantToRegister(MachineBasicBlock *MBB,
324 MachineBasicBlock::iterator MBBI,
325 Constant *C, unsigned Reg);
327 /// makeAnotherReg - This method returns the next register number we haven't
330 /// Long values are handled somewhat specially. They are always allocated
331 /// as pairs of 32 bit integer values. The register number returned is the
332 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
333 /// of the long value.
335 unsigned makeAnotherReg(const Type *Ty) {
336 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
337 "Current target doesn't have X86 reg info??");
338 const X86RegisterInfo *MRI =
339 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
340 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
341 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
342 // Create the lower part
343 F->getSSARegMap()->createVirtualRegister(RC);
344 // Create the upper part.
345 return F->getSSARegMap()->createVirtualRegister(RC)-1;
348 // Add the mapping of regnumber => reg class to MachineFunction
349 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
350 return F->getSSARegMap()->createVirtualRegister(RC);
353 /// getReg - This method turns an LLVM value into a register number. This
354 /// is guaranteed to produce the same register number for a particular value
355 /// every time it is queried.
357 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
358 unsigned getReg(Value *V) {
359 // Just append to the end of the current bb.
360 MachineBasicBlock::iterator It = BB->end();
361 return getReg(V, BB, It);
363 unsigned getReg(Value *V, MachineBasicBlock *MBB,
364 MachineBasicBlock::iterator IPt) {
365 // If this operand is a constant, emit the code to copy the constant into
366 // the register here...
368 if (Constant *C = dyn_cast<Constant>(V)) {
369 unsigned Reg = makeAnotherReg(V->getType());
370 copyConstantToRegister(MBB, IPt, C, Reg);
372 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
373 unsigned Reg = makeAnotherReg(V->getType());
374 // Move the address of the global into the register
375 BuildMI(*MBB, IPt, X86::MOV32ri, 1, Reg).addGlobalAddress(GV);
377 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
378 // Do not emit noop casts at all.
379 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
380 return getReg(CI->getOperand(0), MBB, IPt);
383 unsigned &Reg = RegMap[V];
385 Reg = makeAnotherReg(V->getType());
394 /// copyConstantToRegister - Output the instructions required to put the
395 /// specified constant into the specified register.
397 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
398 MachineBasicBlock::iterator IP,
399 Constant *C, unsigned R) {
400 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
402 switch (CE->getOpcode()) {
403 case Instruction::GetElementPtr:
404 emitGEPOperation(MBB, IP, CE->getOperand(0),
405 CE->op_begin()+1, CE->op_end(), R);
407 case Instruction::Cast:
408 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
411 case Instruction::Xor: ++Class; // FALL THROUGH
412 case Instruction::Or: ++Class; // FALL THROUGH
413 case Instruction::And: ++Class; // FALL THROUGH
414 case Instruction::Sub: ++Class; // FALL THROUGH
415 case Instruction::Add:
416 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
420 case Instruction::Mul:
421 emitMultiply(MBB, IP, CE->getOperand(0), CE->getOperand(1), R);
424 case Instruction::Div:
425 case Instruction::Rem:
426 emitDivRemOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
427 CE->getOpcode() == Instruction::Div, R);
430 case Instruction::SetNE:
431 case Instruction::SetEQ:
432 case Instruction::SetLT:
433 case Instruction::SetGT:
434 case Instruction::SetLE:
435 case Instruction::SetGE:
436 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
440 case Instruction::Shl:
441 case Instruction::Shr:
442 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
443 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
446 case Instruction::Select:
447 emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
448 CE->getOperand(2), R);
452 std::cerr << "Offending expr: " << C << "\n";
453 assert(0 && "Constant expression not yet handled!\n");
457 if (C->getType()->isIntegral()) {
458 unsigned Class = getClassB(C->getType());
460 if (Class == cLong) {
461 // Copy the value into the register pair.
462 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
463 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
464 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
468 assert(Class <= cInt && "Type not handled yet!");
470 static const unsigned IntegralOpcodeTab[] = {
471 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
474 if (C->getType() == Type::BoolTy) {
475 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
477 ConstantInt *CI = cast<ConstantInt>(C);
478 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
480 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
481 if (CFP->isExactlyValue(+0.0))
482 BuildMI(*MBB, IP, X86::FLD0, 0, R);
483 else if (CFP->isExactlyValue(+1.0))
484 BuildMI(*MBB, IP, X86::FLD1, 0, R);
486 // Otherwise we need to spill the constant to memory...
487 MachineConstantPool *CP = F->getConstantPool();
488 unsigned CPI = CP->getConstantPoolIndex(CFP);
489 const Type *Ty = CFP->getType();
491 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
492 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
493 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
496 } else if (isa<ConstantPointerNull>(C)) {
497 // Copy zero (null pointer) to the register.
498 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
499 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
500 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(CPR->getValue());
502 std::cerr << "Offending constant: " << C << "\n";
503 assert(0 && "Type not handled yet!");
507 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
508 /// the stack into virtual registers.
510 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
511 // Emit instructions to load the arguments... On entry to a function on the
512 // X86, the stack frame looks like this:
514 // [ESP] -- return address
515 // [ESP + 4] -- first argument (leftmost lexically)
516 // [ESP + 8] -- second argument, if first argument is four bytes in size
519 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
520 MachineFrameInfo *MFI = F->getFrameInfo();
522 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
523 bool ArgLive = !I->use_empty();
524 unsigned Reg = ArgLive ? getReg(*I) : 0;
525 int FI; // Frame object index
527 switch (getClassB(I->getType())) {
530 FI = MFI->CreateFixedObject(1, ArgOffset);
531 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
536 FI = MFI->CreateFixedObject(2, ArgOffset);
537 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
542 FI = MFI->CreateFixedObject(4, ArgOffset);
543 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
548 FI = MFI->CreateFixedObject(8, ArgOffset);
549 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
550 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
552 ArgOffset += 4; // longs require 4 additional bytes
557 if (I->getType() == Type::FloatTy) {
558 Opcode = X86::FLD32m;
559 FI = MFI->CreateFixedObject(4, ArgOffset);
561 Opcode = X86::FLD64m;
562 FI = MFI->CreateFixedObject(8, ArgOffset);
564 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
566 if (I->getType() == Type::DoubleTy)
567 ArgOffset += 4; // doubles require 4 additional bytes
570 assert(0 && "Unhandled argument type!");
572 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
575 // If the function takes variable number of arguments, add a frame offset for
576 // the start of the first vararg value... this is used to expand
578 if (Fn.getFunctionType()->isVarArg())
579 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
583 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
584 /// because we have to generate our sources into the source basic blocks, not
587 void ISel::SelectPHINodes() {
588 const TargetInstrInfo &TII = TM.getInstrInfo();
589 const Function &LF = *F->getFunction(); // The LLVM function...
590 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
591 const BasicBlock *BB = I;
592 MachineBasicBlock &MBB = *MBBMap[I];
594 // Loop over all of the PHI nodes in the LLVM basic block...
595 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
596 for (BasicBlock::const_iterator I = BB->begin();
597 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
599 // Create a new machine instr PHI node, and insert it.
600 unsigned PHIReg = getReg(*PN);
601 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
602 X86::PHI, PN->getNumOperands(), PHIReg);
604 MachineInstr *LongPhiMI = 0;
605 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
606 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
607 X86::PHI, PN->getNumOperands(), PHIReg+1);
609 // PHIValues - Map of blocks to incoming virtual registers. We use this
610 // so that we only initialize one incoming value for a particular block,
611 // even if the block has multiple entries in the PHI node.
613 std::map<MachineBasicBlock*, unsigned> PHIValues;
615 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
616 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
618 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
619 PHIValues.lower_bound(PredMBB);
621 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
622 // We already inserted an initialization of the register for this
623 // predecessor. Recycle it.
624 ValReg = EntryIt->second;
627 // Get the incoming value into a virtual register.
629 Value *Val = PN->getIncomingValue(i);
631 // If this is a constant or GlobalValue, we may have to insert code
632 // into the basic block to compute it into a virtual register.
633 if (isa<Constant>(Val) || isa<GlobalValue>(Val)) {
634 if (isa<ConstantExpr>(Val)) {
635 // Because we don't want to clobber any values which might be in
636 // physical registers with the computation of this constant (which
637 // might be arbitrarily complex if it is a constant expression),
638 // just insert the computation at the top of the basic block.
639 MachineBasicBlock::iterator PI = PredMBB->begin();
641 // Skip over any PHI nodes though!
642 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
645 ValReg = getReg(Val, PredMBB, PI);
647 // Simple constants get emitted at the end of the basic block,
648 // before any terminator instructions. We "know" that the code to
649 // move a constant into a register will never clobber any flags.
650 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
653 ValReg = getReg(Val);
656 // Remember that we inserted a value for this PHI for this predecessor
657 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
660 PhiMI->addRegOperand(ValReg);
661 PhiMI->addMachineBasicBlockOperand(PredMBB);
663 LongPhiMI->addRegOperand(ValReg+1);
664 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
668 // Now that we emitted all of the incoming values for the PHI node, make
669 // sure to reposition the InsertPoint after the PHI that we just added.
670 // This is needed because we might have inserted a constant into this
671 // block, right after the PHI's which is before the old insert point!
672 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
678 /// RequiresFPRegKill - The floating point stackifier pass cannot insert
679 /// compensation code on critical edges. As such, it requires that we kill all
680 /// FP registers on the exit from any blocks that either ARE critical edges, or
681 /// branch to a block that has incoming critical edges.
683 /// Note that this kill instruction will eventually be eliminated when
684 /// restrictions in the stackifier are relaxed.
686 static bool RequiresFPRegKill(const MachineBasicBlock *MBB) {
688 const BasicBlock *BB = MBB->getBasicBlock ();
689 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
690 const BasicBlock *Succ = *SI;
691 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
692 ++PI; // Block have at least one predecessory
693 if (PI != PE) { // If it has exactly one, this isn't crit edge
694 // If this block has more than one predecessor, check all of the
695 // predecessors to see if they have multiple successors. If so, then the
696 // block we are analyzing needs an FPRegKill.
697 for (PI = pred_begin(Succ); PI != PE; ++PI) {
698 const BasicBlock *Pred = *PI;
699 succ_const_iterator SI2 = succ_begin(Pred);
700 ++SI2; // There must be at least one successor of this block.
701 if (SI2 != succ_end(Pred))
702 return true; // Yes, we must insert the kill on this edge.
706 // If we got this far, there is no need to insert the kill instruction.
713 // InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
714 // need them. This only occurs due to the floating point stackifier not being
715 // aggressive enough to handle arbitrary global stackification.
717 // Currently we insert an FP_REG_KILL instruction into each block that uses or
718 // defines a floating point virtual register.
720 // When the global register allocators (like linear scan) finally update live
721 // variable analysis, we can keep floating point values in registers across
722 // portions of the CFG that do not involve critical edges. This will be a big
723 // win, but we are waiting on the global allocators before we can do this.
725 // With a bit of work, the floating point stackifier pass can be enhanced to
726 // break critical edges as needed (to make a place to put compensation code),
727 // but this will require some infrastructure improvements as well.
729 void ISel::InsertFPRegKills() {
730 SSARegMap &RegMap = *F->getSSARegMap();
732 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
733 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
734 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
735 MachineOperand& MO = I->getOperand(i);
736 if (MO.isRegister() && MO.getReg()) {
737 unsigned Reg = MO.getReg();
738 if (MRegisterInfo::isVirtualRegister(Reg))
739 if (RegMap.getRegClass(Reg)->getSize() == 10)
743 // If we haven't found an FP register use or def in this basic block, check
744 // to see if any of our successors has an FP PHI node, which will cause a
745 // copy to be inserted into this block.
746 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
747 SE = BB->succ_end(); SI != SE; ++SI) {
748 MachineBasicBlock *SBB = *SI;
749 for (MachineBasicBlock::iterator I = SBB->begin();
750 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
751 if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
757 // Okay, this block uses an FP register. If the block has successors (ie,
758 // it's not an unwind/return), insert the FP_REG_KILL instruction.
759 if (BB->succ_size () && RequiresFPRegKill(BB)) {
760 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
767 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
768 // it into the conditional branch or select instruction which is the only user
769 // of the cc instruction. This is the case if the conditional branch is the
770 // only user of the setcc, and if the setcc is in the same basic block as the
771 // conditional branch. We also don't handle long arguments below, so we reject
772 // them here as well.
774 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
775 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
776 if (SCI->hasOneUse()) {
777 Instruction *User = cast<Instruction>(SCI->use_back());
778 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
779 SCI->getParent() == User->getParent() &&
780 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
781 SCI->getOpcode() == Instruction::SetEQ ||
782 SCI->getOpcode() == Instruction::SetNE))
788 // Return a fixed numbering for setcc instructions which does not depend on the
789 // order of the opcodes.
791 static unsigned getSetCCNumber(unsigned Opcode) {
793 default: assert(0 && "Unknown setcc instruction!");
794 case Instruction::SetEQ: return 0;
795 case Instruction::SetNE: return 1;
796 case Instruction::SetLT: return 2;
797 case Instruction::SetGE: return 3;
798 case Instruction::SetGT: return 4;
799 case Instruction::SetLE: return 5;
803 // LLVM -> X86 signed X86 unsigned
804 // ----- ---------- ------------
805 // seteq -> sete sete
806 // setne -> setne setne
807 // setlt -> setl setb
808 // setge -> setge setae
809 // setgt -> setg seta
810 // setle -> setle setbe
812 // sets // Used by comparison with 0 optimization
814 static const unsigned SetCCOpcodeTab[2][8] = {
815 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
817 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
818 X86::SETSr, X86::SETNSr },
821 // EmitComparison - This function emits a comparison of the two operands,
822 // returning the extended setcc code to use.
823 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
824 MachineBasicBlock *MBB,
825 MachineBasicBlock::iterator IP) {
826 // The arguments are already supposed to be of the same type.
827 const Type *CompTy = Op0->getType();
828 unsigned Class = getClassB(CompTy);
829 unsigned Op0r = getReg(Op0, MBB, IP);
831 // Special case handling of: cmp R, i
832 if (isa<ConstantPointerNull>(Op1)) {
833 if (OpNum < 2) // seteq/setne -> test
834 BuildMI(*MBB, IP, X86::TEST32rr, 2).addReg(Op0r).addReg(Op0r);
836 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(0);
839 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
840 if (Class == cByte || Class == cShort || Class == cInt) {
841 unsigned Op1v = CI->getRawValue();
843 // Mask off any upper bits of the constant, if there are any...
844 Op1v &= (1ULL << (8 << Class)) - 1;
846 // If this is a comparison against zero, emit more efficient code. We
847 // can't handle unsigned comparisons against zero unless they are == or
848 // !=. These should have been strength reduced already anyway.
849 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
850 static const unsigned TESTTab[] = {
851 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
853 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
855 if (OpNum == 2) return 6; // Map jl -> js
856 if (OpNum == 3) return 7; // Map jg -> jns
860 static const unsigned CMPTab[] = {
861 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
864 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
867 assert(Class == cLong && "Unknown integer class!");
868 unsigned LowCst = CI->getRawValue();
869 unsigned HiCst = CI->getRawValue() >> 32;
870 if (OpNum < 2) { // seteq, setne
871 unsigned LoTmp = Op0r;
873 LoTmp = makeAnotherReg(Type::IntTy);
874 BuildMI(*MBB, IP, X86::XOR32ri, 2, LoTmp).addReg(Op0r).addImm(LowCst);
876 unsigned HiTmp = Op0r+1;
878 HiTmp = makeAnotherReg(Type::IntTy);
879 BuildMI(*MBB, IP, X86::XOR32ri, 2,HiTmp).addReg(Op0r+1).addImm(HiCst);
881 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
882 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
885 // Emit a sequence of code which compares the high and low parts once
886 // each, then uses a conditional move to handle the overflow case. For
887 // example, a setlt for long would generate code like this:
889 // AL = lo(op1) < lo(op2) // Signedness depends on operands
890 // BL = hi(op1) < hi(op2) // Always unsigned comparison
891 // dest = hi(op1) == hi(op2) ? AL : BL;
894 // FIXME: This would be much better if we had hierarchical register
895 // classes! Until then, hardcode registers so that we can deal with
896 // their aliases (because we don't have conditional byte moves).
898 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(LowCst);
899 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
900 BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r+1).addImm(HiCst);
901 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0,X86::BL);
902 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
903 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
904 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
906 // NOTE: visitSetCondInst knows that the value is dumped into the BL
907 // register at this point for long values...
913 // Special case handling of comparison against +/- 0.0
914 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
915 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
916 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
917 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
918 BuildMI(*MBB, IP, X86::SAHF, 1);
922 unsigned Op1r = getReg(Op1, MBB, IP);
924 default: assert(0 && "Unknown type class!");
925 // Emit: cmp <var1>, <var2> (do the comparison). We can
926 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
929 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
932 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
935 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
938 if (0) { // for processors prior to the P6
939 BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
940 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
941 BuildMI(*MBB, IP, X86::SAHF, 1);
943 BuildMI(*MBB, IP, X86::FpUCOMI, 2).addReg(Op0r).addReg(Op1r);
948 if (OpNum < 2) { // seteq, setne
949 unsigned LoTmp = makeAnotherReg(Type::IntTy);
950 unsigned HiTmp = makeAnotherReg(Type::IntTy);
951 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
952 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
953 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
954 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
955 break; // Allow the sete or setne to be generated from flags set by OR
957 // Emit a sequence of code which compares the high and low parts once
958 // each, then uses a conditional move to handle the overflow case. For
959 // example, a setlt for long would generate code like this:
961 // AL = lo(op1) < lo(op2) // Signedness depends on operands
962 // BL = hi(op1) < hi(op2) // Always unsigned comparison
963 // dest = hi(op1) == hi(op2) ? AL : BL;
966 // FIXME: This would be much better if we had hierarchical register
967 // classes! Until then, hardcode registers so that we can deal with their
968 // aliases (because we don't have conditional byte moves).
970 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
971 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
972 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
973 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
974 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
975 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
976 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
978 // NOTE: visitSetCondInst knows that the value is dumped into the BL
979 // register at this point for long values...
986 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
987 /// register, then move it to wherever the result should be.
989 void ISel::visitSetCondInst(SetCondInst &I) {
990 if (canFoldSetCCIntoBranchOrSelect(&I))
991 return; // Fold this into a branch or select.
993 unsigned DestReg = getReg(I);
994 MachineBasicBlock::iterator MII = BB->end();
995 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
999 /// emitSetCCOperation - Common code shared between visitSetCondInst and
1000 /// constant expression support.
1002 void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
1003 MachineBasicBlock::iterator IP,
1004 Value *Op0, Value *Op1, unsigned Opcode,
1005 unsigned TargetReg) {
1006 unsigned OpNum = getSetCCNumber(Opcode);
1007 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
1009 const Type *CompTy = Op0->getType();
1010 unsigned CompClass = getClassB(CompTy);
1011 bool isSigned = CompTy->isSigned() && CompClass != cFP;
1013 if (CompClass != cLong || OpNum < 2) {
1014 // Handle normal comparisons with a setcc instruction...
1015 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
1017 // Handle long comparisons by copying the value which is already in BL into
1018 // the register we want...
1019 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
1023 void ISel::visitSelectInst(SelectInst &SI) {
1024 unsigned DestReg = getReg(SI);
1025 MachineBasicBlock::iterator MII = BB->end();
1026 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1027 SI.getFalseValue(), DestReg);
1030 /// emitSelect - Common code shared between visitSelectInst and the constant
1031 /// expression support.
1032 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1033 MachineBasicBlock::iterator IP,
1034 Value *Cond, Value *TrueVal, Value *FalseVal,
1036 unsigned SelectClass = getClassB(TrueVal->getType());
1038 // We don't support 8-bit conditional moves. If we have incoming constants,
1039 // transform them into 16-bit constants to avoid having a run-time conversion.
1040 if (SelectClass == cByte) {
1041 if (Constant *T = dyn_cast<Constant>(TrueVal))
1042 TrueVal = ConstantExpr::getCast(T, Type::ShortTy);
1043 if (Constant *F = dyn_cast<Constant>(FalseVal))
1044 FalseVal = ConstantExpr::getCast(F, Type::ShortTy);
1047 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1048 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1049 if (TrueReg == FalseReg) {
1050 static const unsigned Opcode[] = {
1051 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
1053 BuildMI(*MBB, IP, Opcode[SelectClass], 1, DestReg).addReg(TrueReg);
1054 if (SelectClass == cLong)
1055 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(TrueReg+1);
1060 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1061 // We successfully folded the setcc into the select instruction.
1063 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1064 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1067 const Type *CompTy = SCI->getOperand(0)->getType();
1068 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1070 // LLVM -> X86 signed X86 unsigned
1071 // ----- ---------- ------------
1072 // seteq -> cmovNE cmovNE
1073 // setne -> cmovE cmovE
1074 // setlt -> cmovGE cmovAE
1075 // setge -> cmovL cmovB
1076 // setgt -> cmovLE cmovBE
1077 // setle -> cmovG cmovA
1079 // cmovNS // Used by comparison with 0 optimization
1082 switch (SelectClass) {
1083 default: assert(0 && "Unknown value class!");
1085 // Annoyingly, we don't have a full set of floating point conditional
1087 static const unsigned OpcodeTab[2][8] = {
1088 { X86::FCMOVNE, X86::FCMOVE, X86::FCMOVAE, X86::FCMOVB,
1089 X86::FCMOVBE, X86::FCMOVA, 0, 0 },
1090 { X86::FCMOVNE, X86::FCMOVE, 0, 0, 0, 0, 0, 0 },
1092 Opcode = OpcodeTab[isSigned][OpNum];
1094 // If opcode == 0, we hit a case that we don't support. Output a setcc
1095 // and compare the result against zero.
1097 unsigned CompClass = getClassB(CompTy);
1099 if (CompClass != cLong || OpNum < 2) {
1100 CondReg = makeAnotherReg(Type::BoolTy);
1101 // Handle normal comparisons with a setcc instruction...
1102 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, CondReg);
1104 // Long comparisons end up in the BL register.
1108 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1109 Opcode = X86::FCMOVE;
1115 static const unsigned OpcodeTab[2][8] = {
1116 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVAE16rr, X86::CMOVB16rr,
1117 X86::CMOVBE16rr, X86::CMOVA16rr, 0, 0 },
1118 { X86::CMOVNE16rr, X86::CMOVE16rr, X86::CMOVGE16rr, X86::CMOVL16rr,
1119 X86::CMOVLE16rr, X86::CMOVG16rr, X86::CMOVNS16rr, X86::CMOVS16rr },
1121 Opcode = OpcodeTab[isSigned][OpNum];
1126 static const unsigned OpcodeTab[2][8] = {
1127 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVAE32rr, X86::CMOVB32rr,
1128 X86::CMOVBE32rr, X86::CMOVA32rr, 0, 0 },
1129 { X86::CMOVNE32rr, X86::CMOVE32rr, X86::CMOVGE32rr, X86::CMOVL32rr,
1130 X86::CMOVLE32rr, X86::CMOVG32rr, X86::CMOVNS32rr, X86::CMOVS32rr },
1132 Opcode = OpcodeTab[isSigned][OpNum];
1137 // Get the value being branched on, and use it to set the condition codes.
1138 unsigned CondReg = getReg(Cond, MBB, IP);
1139 BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1140 switch (SelectClass) {
1141 default: assert(0 && "Unknown value class!");
1142 case cFP: Opcode = X86::FCMOVE; break;
1144 case cShort: Opcode = X86::CMOVE16rr; break;
1146 case cLong: Opcode = X86::CMOVE32rr; break;
1150 unsigned RealDestReg = DestReg;
1153 // Annoyingly enough, X86 doesn't HAVE 8-bit conditional moves. Because of
1154 // this, we have to promote the incoming values to 16 bits, perform a 16-bit
1155 // cmove, then truncate the result.
1156 if (SelectClass == cByte) {
1157 DestReg = makeAnotherReg(Type::ShortTy);
1158 if (getClassB(TrueVal->getType()) == cByte) {
1159 // Promote the true value, by storing it into AL, and reading from AX.
1160 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::AL).addReg(TrueReg);
1161 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::AH).addImm(0);
1162 TrueReg = makeAnotherReg(Type::ShortTy);
1163 BuildMI(*MBB, IP, X86::MOV16rr, 1, TrueReg).addReg(X86::AX);
1165 if (getClassB(FalseVal->getType()) == cByte) {
1166 // Promote the true value, by storing it into CL, and reading from CX.
1167 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(FalseReg);
1168 BuildMI(*MBB, IP, X86::MOV8ri, 1, X86::CH).addImm(0);
1169 FalseReg = makeAnotherReg(Type::ShortTy);
1170 BuildMI(*MBB, IP, X86::MOV16rr, 1, FalseReg).addReg(X86::CX);
1174 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(TrueReg).addReg(FalseReg);
1176 switch (SelectClass) {
1178 // We did the computation with 16-bit registers. Truncate back to our
1179 // result by copying into AX then copying out AL.
1180 BuildMI(*MBB, IP, X86::MOV16rr, 1, X86::AX).addReg(DestReg);
1181 BuildMI(*MBB, IP, X86::MOV8rr, 1, RealDestReg).addReg(X86::AL);
1184 // Move the upper half of the value as well.
1185 BuildMI(*MBB, IP, Opcode, 2,DestReg+1).addReg(TrueReg+1).addReg(FalseReg+1);
1192 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1193 /// operand, in the specified target register.
1195 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1196 bool isUnsigned = VR.Ty->isUnsigned();
1198 Value *Val = VR.Val;
1199 const Type *Ty = VR.Ty;
1201 if (Constant *C = dyn_cast<Constant>(Val)) {
1202 Val = ConstantExpr::getCast(C, Type::IntTy);
1206 // If this is a simple constant, just emit a MOVri directly to avoid the
1208 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1209 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1210 BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
1215 // Make sure we have the register number for this value...
1216 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1218 switch (getClassB(Ty)) {
1220 // Extend value into target register (8->32)
1222 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
1224 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
1227 // Extend value into target register (16->32)
1229 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
1231 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
1234 // Move value into target register (32->32)
1235 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
1238 assert(0 && "Unpromotable operand class in promote32");
1242 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
1243 /// we have the following possibilities:
1245 /// ret void: No return value, simply emit a 'ret' instruction
1246 /// ret sbyte, ubyte : Extend value into EAX and return
1247 /// ret short, ushort: Extend value into EAX and return
1248 /// ret int, uint : Move value into EAX and return
1249 /// ret pointer : Move value into EAX and return
1250 /// ret long, ulong : Move value into EAX/EDX and return
1251 /// ret float/double : Top of FP stack
1253 void ISel::visitReturnInst(ReturnInst &I) {
1254 if (I.getNumOperands() == 0) {
1255 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
1259 Value *RetVal = I.getOperand(0);
1260 switch (getClassB(RetVal->getType())) {
1261 case cByte: // integral return values: extend or move into EAX and return
1264 promote32(X86::EAX, ValueRecord(RetVal));
1265 // Declare that EAX is live on exit
1266 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
1268 case cFP: { // Floats & Doubles: Return in ST(0)
1269 unsigned RetReg = getReg(RetVal);
1270 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
1271 // Declare that top-of-stack is live on exit
1272 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
1276 unsigned RetReg = getReg(RetVal);
1277 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
1278 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
1279 // Declare that EAX & EDX are live on exit
1280 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1285 visitInstruction(I);
1287 // Emit a 'ret' instruction
1288 BuildMI(BB, X86::RET, 0);
1291 // getBlockAfter - Return the basic block which occurs lexically after the
1293 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1294 Function::iterator I = BB; ++I; // Get iterator to next block
1295 return I != BB->getParent()->end() ? &*I : 0;
1298 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1299 /// that since code layout is frozen at this point, that if we are trying to
1300 /// jump to a block that is the immediate successor of the current block, we can
1301 /// just make a fall-through (but we don't currently).
1303 void ISel::visitBranchInst(BranchInst &BI) {
1304 // Update machine-CFG edges
1305 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1306 if (BI.isConditional())
1307 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1309 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1311 if (!BI.isConditional()) { // Unconditional branch?
1312 if (BI.getSuccessor(0) != NextBB)
1313 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1317 // See if we can fold the setcc into the branch itself...
1318 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1320 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1321 // computed some other way...
1322 unsigned condReg = getReg(BI.getCondition());
1323 BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
1324 if (BI.getSuccessor(1) == NextBB) {
1325 if (BI.getSuccessor(0) != NextBB)
1326 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1328 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1330 if (BI.getSuccessor(0) != NextBB)
1331 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1336 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1337 MachineBasicBlock::iterator MII = BB->end();
1338 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1340 const Type *CompTy = SCI->getOperand(0)->getType();
1341 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1344 // LLVM -> X86 signed X86 unsigned
1345 // ----- ---------- ------------
1353 // js // Used by comparison with 0 optimization
1356 static const unsigned OpcodeTab[2][8] = {
1357 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1358 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1359 X86::JS, X86::JNS },
1362 if (BI.getSuccessor(0) != NextBB) {
1363 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1364 if (BI.getSuccessor(1) != NextBB)
1365 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1367 // Change to the inverse condition...
1368 if (BI.getSuccessor(1) != NextBB) {
1370 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1376 /// doCall - This emits an abstract call instruction, setting up the arguments
1377 /// and the return value as appropriate. For the actual function call itself,
1378 /// it inserts the specified CallMI instruction into the stream.
1380 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1381 const std::vector<ValueRecord> &Args) {
1383 // Count how many bytes are to be pushed on the stack...
1384 unsigned NumBytes = 0;
1386 if (!Args.empty()) {
1387 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1388 switch (getClassB(Args[i].Ty)) {
1389 case cByte: case cShort: case cInt:
1390 NumBytes += 4; break;
1392 NumBytes += 8; break;
1394 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1396 default: assert(0 && "Unknown class!");
1399 // Adjust the stack pointer for the new arguments...
1400 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1402 // Arguments go on the stack in reverse order, as specified by the ABI.
1403 unsigned ArgOffset = 0;
1404 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1406 switch (getClassB(Args[i].Ty)) {
1409 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1410 // Zero/Sign extend constant, then stuff into memory.
1411 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1412 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1413 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1414 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1416 // Promote arg to 32 bits wide into a temporary register...
1417 ArgReg = makeAnotherReg(Type::UIntTy);
1418 promote32(ArgReg, Args[i]);
1419 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1420 X86::ESP, ArgOffset).addReg(ArgReg);
1424 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1425 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1426 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1427 X86::ESP, ArgOffset).addImm(Val);
1429 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1430 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1431 X86::ESP, ArgOffset).addReg(ArgReg);
1435 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1436 uint64_t Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1437 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1438 X86::ESP, ArgOffset).addImm(Val & ~0U);
1439 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1440 X86::ESP, ArgOffset+4).addImm(Val >> 32ULL);
1442 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1443 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1444 X86::ESP, ArgOffset).addReg(ArgReg);
1445 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1446 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1448 ArgOffset += 4; // 8 byte entry, not 4.
1452 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1453 if (Args[i].Ty == Type::FloatTy) {
1454 addRegOffset(BuildMI(BB, X86::FST32m, 5),
1455 X86::ESP, ArgOffset).addReg(ArgReg);
1457 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1458 addRegOffset(BuildMI(BB, X86::FST64m, 5),
1459 X86::ESP, ArgOffset).addReg(ArgReg);
1460 ArgOffset += 4; // 8 byte entry, not 4.
1464 default: assert(0 && "Unknown class!");
1469 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
1472 BB->push_back(CallMI);
1474 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
1476 // If there is a return value, scavenge the result from the location the call
1479 if (Ret.Ty != Type::VoidTy) {
1480 unsigned DestClass = getClassB(Ret.Ty);
1481 switch (DestClass) {
1485 // Integral results are in %eax, or the appropriate portion
1487 static const unsigned regRegMove[] = {
1488 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
1490 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1491 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1494 case cFP: // Floating-point return values live in %ST(0)
1495 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1497 case cLong: // Long values are left in EDX:EAX
1498 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1499 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
1501 default: assert(0 && "Unknown class!");
1507 /// visitCallInst - Push args on stack and do a procedure call instruction.
1508 void ISel::visitCallInst(CallInst &CI) {
1509 MachineInstr *TheCall;
1510 if (Function *F = CI.getCalledFunction()) {
1511 // Is it an intrinsic function call?
1512 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1513 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1517 // Emit a CALL instruction with PC-relative displacement.
1518 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1519 } else { // Emit an indirect call...
1520 unsigned Reg = getReg(CI.getCalledValue());
1521 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
1524 std::vector<ValueRecord> Args;
1525 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1526 Args.push_back(ValueRecord(CI.getOperand(i)));
1528 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1529 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1533 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1534 /// function, lowering any calls to unknown intrinsic functions into the
1535 /// equivalent LLVM code.
1537 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1538 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1539 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1540 if (CallInst *CI = dyn_cast<CallInst>(I++))
1541 if (Function *F = CI->getCalledFunction())
1542 switch (F->getIntrinsicID()) {
1543 case Intrinsic::not_intrinsic:
1544 case Intrinsic::vastart:
1545 case Intrinsic::vacopy:
1546 case Intrinsic::vaend:
1547 case Intrinsic::returnaddress:
1548 case Intrinsic::frameaddress:
1549 case Intrinsic::memcpy:
1550 case Intrinsic::memset:
1551 case Intrinsic::readport:
1552 case Intrinsic::writeport:
1553 // We directly implement these intrinsics
1555 case Intrinsic::readio: {
1556 // On X86, memory operations are in-order. Lower this intrinsic
1557 // into a volatile load.
1558 Instruction *Before = CI->getPrev();
1559 LoadInst * LI = new LoadInst (CI->getOperand(1), "", true, CI);
1560 CI->replaceAllUsesWith (LI);
1561 BB->getInstList().erase (CI);
1564 case Intrinsic::writeio: {
1565 // On X86, memory operations are in-order. Lower this intrinsic
1566 // into a volatile store.
1567 Instruction *Before = CI->getPrev();
1568 StoreInst * LI = new StoreInst (CI->getOperand(1),
1569 CI->getOperand(2), true, CI);
1570 CI->replaceAllUsesWith (LI);
1571 BB->getInstList().erase (CI);
1575 // All other intrinsic calls we must lower.
1576 Instruction *Before = CI->getPrev();
1577 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1578 if (Before) { // Move iterator to instruction after call
1587 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1588 unsigned TmpReg1, TmpReg2;
1590 case Intrinsic::vastart:
1591 // Get the address of the first vararg value...
1592 TmpReg1 = getReg(CI);
1593 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
1596 case Intrinsic::vacopy:
1597 TmpReg1 = getReg(CI);
1598 TmpReg2 = getReg(CI.getOperand(1));
1599 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
1601 case Intrinsic::vaend: return; // Noop on X86
1603 case Intrinsic::returnaddress:
1604 case Intrinsic::frameaddress:
1605 TmpReg1 = getReg(CI);
1606 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1607 if (ID == Intrinsic::returnaddress) {
1608 // Just load the return address
1609 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
1610 ReturnAddressIndex);
1612 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
1613 ReturnAddressIndex, -4);
1616 // Values other than zero are not implemented yet.
1617 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
1621 case Intrinsic::memcpy: {
1622 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1624 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1625 Align = AlignC->getRawValue();
1626 if (Align == 0) Align = 1;
1629 // Turn the byte code into # iterations
1632 switch (Align & 3) {
1633 case 2: // WORD aligned
1634 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1635 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1637 CountReg = makeAnotherReg(Type::IntTy);
1638 unsigned ByteReg = getReg(CI.getOperand(3));
1639 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1641 Opcode = X86::REP_MOVSW;
1643 case 0: // DWORD aligned
1644 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1645 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1647 CountReg = makeAnotherReg(Type::IntTy);
1648 unsigned ByteReg = getReg(CI.getOperand(3));
1649 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1651 Opcode = X86::REP_MOVSD;
1653 default: // BYTE aligned
1654 CountReg = getReg(CI.getOperand(3));
1655 Opcode = X86::REP_MOVSB;
1659 // No matter what the alignment is, we put the source in ESI, the
1660 // destination in EDI, and the count in ECX.
1661 TmpReg1 = getReg(CI.getOperand(1));
1662 TmpReg2 = getReg(CI.getOperand(2));
1663 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1664 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1665 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
1666 BuildMI(BB, Opcode, 0);
1669 case Intrinsic::memset: {
1670 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1672 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1673 Align = AlignC->getRawValue();
1674 if (Align == 0) Align = 1;
1677 // Turn the byte code into # iterations
1680 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1681 unsigned Val = ValC->getRawValue() & 255;
1683 // If the value is a constant, then we can potentially use larger copies.
1684 switch (Align & 3) {
1685 case 2: // WORD aligned
1686 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1687 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1689 CountReg = makeAnotherReg(Type::IntTy);
1690 unsigned ByteReg = getReg(CI.getOperand(3));
1691 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1693 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
1694 Opcode = X86::REP_STOSW;
1696 case 0: // DWORD aligned
1697 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1698 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1700 CountReg = makeAnotherReg(Type::IntTy);
1701 unsigned ByteReg = getReg(CI.getOperand(3));
1702 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1704 Val = (Val << 8) | Val;
1705 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
1706 Opcode = X86::REP_STOSD;
1708 default: // BYTE aligned
1709 CountReg = getReg(CI.getOperand(3));
1710 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
1711 Opcode = X86::REP_STOSB;
1715 // If it's not a constant value we are storing, just fall back. We could
1716 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1717 unsigned ValReg = getReg(CI.getOperand(2));
1718 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1719 CountReg = getReg(CI.getOperand(3));
1720 Opcode = X86::REP_STOSB;
1723 // No matter what the alignment is, we put the source in ESI, the
1724 // destination in EDI, and the count in ECX.
1725 TmpReg1 = getReg(CI.getOperand(1));
1726 //TmpReg2 = getReg(CI.getOperand(2));
1727 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1728 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1729 BuildMI(BB, Opcode, 0);
1733 case Intrinsic::readport: {
1734 // First, determine that the size of the operand falls within the acceptable
1735 // range for this architecture.
1737 if (getClassB(CI.getOperand(1)->getType()) != cShort) {
1738 std::cerr << "llvm.readport: Address size is not 16 bits\n";
1742 // Now, move the I/O port address into the DX register and use the IN
1743 // instruction to get the input data.
1745 unsigned Class = getClass(CI.getCalledFunction()->getReturnType());
1746 unsigned DestReg = getReg(CI);
1748 // If the port is a single-byte constant, use the immediate form.
1749 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(1)))
1750 if ((C->getRawValue() & 255) == C->getRawValue()) {
1753 BuildMI(BB, X86::IN8ri, 1).addImm((unsigned char)C->getRawValue());
1754 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1757 BuildMI(BB, X86::IN16ri, 1).addImm((unsigned char)C->getRawValue());
1758 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1761 BuildMI(BB, X86::IN32ri, 1).addImm((unsigned char)C->getRawValue());
1762 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1767 unsigned Reg = getReg(CI.getOperand(1));
1768 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1771 BuildMI(BB, X86::IN8rr, 0);
1772 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1775 BuildMI(BB, X86::IN16rr, 0);
1776 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::AX);
1779 BuildMI(BB, X86::IN32rr, 0);
1780 BuildMI(BB, X86::MOV8rr, 1, DestReg).addReg(X86::EAX);
1783 std::cerr << "Cannot do input on this data type";
1789 case Intrinsic::writeport: {
1790 // First, determine that the size of the operand falls within the
1791 // acceptable range for this architecture.
1792 if (getClass(CI.getOperand(2)->getType()) != cShort) {
1793 std::cerr << "llvm.writeport: Address size is not 16 bits\n";
1797 unsigned Class = getClassB(CI.getOperand(1)->getType());
1798 unsigned ValReg = getReg(CI.getOperand(1));
1801 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1804 BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(ValReg);
1807 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(ValReg);
1810 std::cerr << "llvm.writeport: invalid data type for X86 target";
1815 // If the port is a single-byte constant, use the immediate form.
1816 if (ConstantInt *C = dyn_cast<ConstantInt>(CI.getOperand(2)))
1817 if ((C->getRawValue() & 255) == C->getRawValue()) {
1818 static const unsigned O[] = { X86::OUT8ir, X86::OUT16ir, X86::OUT32ir };
1819 BuildMI(BB, O[Class], 1).addImm((unsigned char)C->getRawValue());
1823 // Otherwise, move the I/O port address into the DX register and the value
1824 // to write into the AL/AX/EAX register.
1825 static const unsigned Opc[] = { X86::OUT8rr, X86::OUT16rr, X86::OUT32rr };
1826 unsigned Reg = getReg(CI.getOperand(2));
1827 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
1828 BuildMI(BB, Opc[Class], 0);
1832 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1836 static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1837 if (LI.getParent() != User.getParent())
1839 BasicBlock::iterator It = &LI;
1840 // Check all of the instructions between the load and the user. We should
1841 // really use alias analysis here, but for now we just do something simple.
1842 for (++It; It != BasicBlock::iterator(&User); ++It) {
1843 switch (It->getOpcode()) {
1844 case Instruction::Free:
1845 case Instruction::Store:
1846 case Instruction::Call:
1847 case Instruction::Invoke:
1849 case Instruction::Load:
1850 if (cast<LoadInst>(It)->isVolatile() && LI.isVolatile())
1858 /// visitSimpleBinary - Implement simple binary operators for integral types...
1859 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1862 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1863 unsigned DestReg = getReg(B);
1864 MachineBasicBlock::iterator MI = BB->end();
1865 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1867 // Special case: op Reg, load [mem]
1868 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
1869 if (!B.swapOperands())
1870 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
1872 unsigned Class = getClassB(B.getType());
1873 if (isa<LoadInst>(Op1) && Class != cLong &&
1874 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
1878 static const unsigned OpcodeTab[][3] = {
1879 // Arithmetic operators
1880 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
1881 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
1883 // Bitwise operators
1884 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
1885 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
1886 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
1888 Opcode = OpcodeTab[OperatorClass][Class];
1890 static const unsigned OpcodeTab[][2] = {
1891 { X86::FADD32m, X86::FADD64m }, // ADD
1892 { X86::FSUB32m, X86::FSUB64m }, // SUB
1894 const Type *Ty = Op0->getType();
1895 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1896 Opcode = OpcodeTab[OperatorClass][Ty == Type::DoubleTy];
1899 unsigned BaseReg, Scale, IndexReg, Disp;
1900 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), BaseReg,
1901 Scale, IndexReg, Disp);
1903 unsigned Op0r = getReg(Op0);
1904 addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r),
1905 BaseReg, Scale, IndexReg, Disp);
1909 // If this is a floating point subtract, check to see if we can fold the first
1911 if (Class == cFP && OperatorClass == 1 &&
1912 isa<LoadInst>(Op0) &&
1913 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B)) {
1914 const Type *Ty = Op0->getType();
1915 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1916 unsigned Opcode = Ty == Type::FloatTy ? X86::FSUBR32m : X86::FSUBR64m;
1918 unsigned BaseReg, Scale, IndexReg, Disp;
1919 getAddressingMode(cast<LoadInst>(Op0)->getOperand(0), BaseReg,
1920 Scale, IndexReg, Disp);
1922 unsigned Op1r = getReg(Op1);
1923 addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op1r),
1924 BaseReg, Scale, IndexReg, Disp);
1928 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1932 /// emitBinaryFPOperation - This method handles emission of floating point
1933 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
1934 void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1935 MachineBasicBlock::iterator IP,
1936 Value *Op0, Value *Op1,
1937 unsigned OperatorClass, unsigned DestReg) {
1939 // Special case: op Reg, <const fp>
1940 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1))
1941 if (!Op1C->isExactlyValue(+0.0) && !Op1C->isExactlyValue(+1.0)) {
1942 // Create a constant pool entry for this constant.
1943 MachineConstantPool *CP = F->getConstantPool();
1944 unsigned CPI = CP->getConstantPoolIndex(Op1C);
1945 const Type *Ty = Op1->getType();
1947 static const unsigned OpcodeTab[][4] = {
1948 { X86::FADD32m, X86::FSUB32m, X86::FMUL32m, X86::FDIV32m }, // Float
1949 { X86::FADD64m, X86::FSUB64m, X86::FMUL64m, X86::FDIV64m }, // Double
1952 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1953 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1954 unsigned Op0r = getReg(Op0, BB, IP);
1955 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
1956 DestReg).addReg(Op0r), CPI);
1960 // Special case: R1 = op <const fp>, R2
1961 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1962 if (CFP->isExactlyValue(-0.0) && OperatorClass == 1) {
1964 unsigned op1Reg = getReg(Op1, BB, IP);
1965 BuildMI(*BB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
1967 } else if (!CFP->isExactlyValue(+0.0) && !CFP->isExactlyValue(+1.0)) {
1968 // R1 = op CST, R2 --> R1 = opr R2, CST
1970 // Create a constant pool entry for this constant.
1971 MachineConstantPool *CP = F->getConstantPool();
1972 unsigned CPI = CP->getConstantPoolIndex(CFP);
1973 const Type *Ty = CFP->getType();
1975 static const unsigned OpcodeTab[][4] = {
1976 { X86::FADD32m, X86::FSUBR32m, X86::FMUL32m, X86::FDIVR32m }, // Float
1977 { X86::FADD64m, X86::FSUBR64m, X86::FMUL64m, X86::FDIVR64m }, // Double
1980 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
1981 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1982 unsigned Op1r = getReg(Op1, BB, IP);
1983 addConstantPoolReference(BuildMI(*BB, IP, Opcode, 5,
1984 DestReg).addReg(Op1r), CPI);
1989 static const unsigned OpcodeTab[4] = {
1990 X86::FpADD, X86::FpSUB, X86::FpMUL, X86::FpDIV
1993 unsigned Opcode = OpcodeTab[OperatorClass];
1994 unsigned Op0r = getReg(Op0, BB, IP);
1995 unsigned Op1r = getReg(Op1, BB, IP);
1996 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1999 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
2000 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
2003 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
2004 /// and constant expression support.
2006 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
2007 MachineBasicBlock::iterator IP,
2008 Value *Op0, Value *Op1,
2009 unsigned OperatorClass, unsigned DestReg) {
2010 unsigned Class = getClassB(Op0->getType());
2013 assert(OperatorClass < 2 && "No logical ops for FP!");
2014 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
2018 // sub 0, X -> neg X
2019 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
2020 if (OperatorClass == 1 && CI->isNullValue()) {
2021 unsigned op1Reg = getReg(Op1, MBB, IP);
2022 static unsigned const NEGTab[] = {
2023 X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
2025 BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
2027 if (Class == cLong) {
2028 // We just emitted: Dl = neg Sl
2029 // Now emit : T = addc Sh, 0
2031 unsigned T = makeAnotherReg(Type::IntTy);
2032 BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
2033 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
2038 // Special case: op Reg, <const int>
2039 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
2040 unsigned Op0r = getReg(Op0, MBB, IP);
2042 // xor X, -1 -> not X
2043 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
2044 static unsigned const NOTTab[] = {
2045 X86::NOT8r, X86::NOT16r, X86::NOT32r, 0, X86::NOT32r
2047 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
2048 if (Class == cLong) // Invert the top part too
2049 BuildMI(*MBB, IP, X86::NOT32r, 1, DestReg+1).addReg(Op0r+1);
2053 // add X, -1 -> dec X
2054 if (OperatorClass == 0 && Op1C->isAllOnesValue() && Class != cLong) {
2055 // Note that we can't use dec for 64-bit decrements, because it does not
2056 // set the carry flag!
2057 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
2058 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
2062 // add X, 1 -> inc X
2063 if (OperatorClass == 0 && Op1C->equalsInt(1) && Class != cLong) {
2064 // Note that we can't use inc for 64-bit increments, because it does not
2065 // set the carry flag!
2066 static unsigned const INCTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
2067 BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
2071 static const unsigned OpcodeTab[][5] = {
2072 // Arithmetic operators
2073 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri }, // ADD
2074 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri }, // SUB
2076 // Bitwise operators
2077 { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri }, // AND
2078 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri }, // OR
2079 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri }, // XOR
2082 unsigned Opcode = OpcodeTab[OperatorClass][Class];
2083 unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
2085 if (Class != cLong) {
2086 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2090 // If this is a long value and the high or low bits have a special
2091 // property, emit some special cases.
2092 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
2094 // If the constant is zero in the low 32-bits, just copy the low part
2095 // across and apply the normal 32-bit operation to the high parts. There
2096 // will be no carry or borrow into the top.
2098 if (OperatorClass != 2) // All but and...
2099 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0r);
2101 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2102 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg+1)
2103 .addReg(Op0r+1).addImm(Op1h);
2107 // If this is a logical operation and the top 32-bits are zero, just
2108 // operate on the lower 32.
2109 if (Op1h == 0 && OperatorClass > 1) {
2110 BuildMI(*MBB, IP, OpcodeTab[OperatorClass][cLong], 2, DestReg)
2111 .addReg(Op0r).addImm(Op1l);
2112 if (OperatorClass != 2) // All but and
2113 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(Op0r+1);
2115 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2119 // TODO: We could handle lots of other special cases here, such as AND'ing
2120 // with 0xFFFFFFFF00000000 -> noop, etc.
2122 // Otherwise, code generate the full operation with a constant.
2123 static const unsigned TopTab[] = {
2124 X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
2127 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
2128 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
2129 .addReg(Op0r+1).addImm(Op1h);
2133 // Finally, handle the general case now.
2134 static const unsigned OpcodeTab[][5] = {
2135 // Arithmetic operators
2136 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, 0, X86::ADD32rr }, // ADD
2137 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, 0, X86::SUB32rr }, // SUB
2139 // Bitwise operators
2140 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr }, // AND
2141 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr }, // OR
2142 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr }, // XOR
2145 unsigned Opcode = OpcodeTab[OperatorClass][Class];
2146 unsigned Op0r = getReg(Op0, MBB, IP);
2147 unsigned Op1r = getReg(Op1, MBB, IP);
2148 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2150 if (Class == cLong) { // Handle the upper 32 bits of long values...
2151 static const unsigned TopTab[] = {
2152 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
2154 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
2155 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2159 /// doMultiply - Emit appropriate instructions to multiply together the
2160 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
2161 /// result should be given as DestTy.
2163 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
2164 unsigned DestReg, const Type *DestTy,
2165 unsigned op0Reg, unsigned op1Reg) {
2166 unsigned Class = getClass(DestTy);
2170 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
2171 .addReg(op0Reg).addReg(op1Reg);
2174 // Must use the MUL instruction, which forces use of AL...
2175 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
2176 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
2177 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
2180 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
2184 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
2185 // returns zero when the input is not exactly a power of two.
2186 static unsigned ExactLog2(unsigned Val) {
2187 if (Val == 0 || (Val & (Val-1))) return 0;
2197 /// doMultiplyConst - This function is specialized to efficiently codegen an 8,
2198 /// 16, or 32-bit integer multiply by a constant.
2199 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
2200 MachineBasicBlock::iterator IP,
2201 unsigned DestReg, const Type *DestTy,
2202 unsigned op0Reg, unsigned ConstRHS) {
2203 static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
2204 static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
2205 static const unsigned ADDrrTab[] = {X86::ADD8rr, X86::ADD16rr, X86::ADD32rr};
2207 unsigned Class = getClass(DestTy);
2209 // Handle special cases here.
2212 BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
2215 BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
2218 BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(op0Reg).addReg(op0Reg);
2223 if (Class == cInt) {
2224 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, DestReg),
2225 op0Reg, ConstRHS-1, op0Reg, 0);
2230 // If the element size is exactly a power of 2, use a shift to get it.
2231 if (unsigned Shift = ExactLog2(ConstRHS)) {
2233 default: assert(0 && "Unknown class for this function!");
2235 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2238 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2241 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
2246 if (Class == cShort) {
2247 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
2249 } else if (Class == cInt) {
2250 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
2254 // Most general case, emit a normal multiply...
2255 unsigned TmpReg = makeAnotherReg(DestTy);
2256 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
2258 // Emit a MUL to multiply the register holding the index by
2259 // elementSize, putting the result in OffsetReg.
2260 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
2263 /// visitMul - Multiplies are not simple binary operators because they must deal
2264 /// with the EAX register explicitly.
2266 void ISel::visitMul(BinaryOperator &I) {
2267 unsigned ResultReg = getReg(I);
2269 Value *Op0 = I.getOperand(0);
2270 Value *Op1 = I.getOperand(1);
2272 // Fold loads into floating point multiplies.
2273 if (getClass(Op0->getType()) == cFP) {
2274 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
2275 if (!I.swapOperands())
2276 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
2277 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2278 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2279 const Type *Ty = Op0->getType();
2280 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2281 unsigned Opcode = Ty == Type::FloatTy ? X86::FMUL32m : X86::FMUL64m;
2283 unsigned BaseReg, Scale, IndexReg, Disp;
2284 getAddressingMode(LI->getOperand(0), BaseReg,
2285 Scale, IndexReg, Disp);
2287 unsigned Op0r = getReg(Op0);
2288 addFullAddress(BuildMI(BB, Opcode, 2, ResultReg).addReg(Op0r),
2289 BaseReg, Scale, IndexReg, Disp);
2294 MachineBasicBlock::iterator IP = BB->end();
2295 emitMultiply(BB, IP, Op0, Op1, ResultReg);
2298 void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2299 Value *Op0, Value *Op1, unsigned DestReg) {
2300 MachineBasicBlock &BB = *MBB;
2301 TypeClass Class = getClass(Op0->getType());
2303 // Simple scalar multiply?
2304 unsigned Op0Reg = getReg(Op0, &BB, IP);
2309 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2310 unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
2311 doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
2313 unsigned Op1Reg = getReg(Op1, &BB, IP);
2314 doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
2318 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2324 // Long value. We have to do things the hard way...
2325 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2326 unsigned CLow = CI->getRawValue();
2327 unsigned CHi = CI->getRawValue() >> 32;
2330 // If the low part of the constant is all zeros, things are simple.
2331 BuildMI(BB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2332 doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
2336 // Multiply the two low parts... capturing carry into EDX
2337 unsigned OverflowReg = 0;
2339 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
2341 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2342 OverflowReg = makeAnotherReg(Type::UIntTy);
2343 BuildMI(BB, IP, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
2344 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2345 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1RegL); // AL*BL
2347 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2348 BuildMI(BB, IP, X86::MOV32rr, 1,
2349 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2352 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2353 doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
2355 unsigned AHBLplusOverflowReg;
2357 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2358 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2359 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2361 AHBLplusOverflowReg = AHBLReg;
2365 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
2367 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2368 doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
2370 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2371 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2376 // General 64x64 multiply
2378 unsigned Op1Reg = getReg(Op1, &BB, IP);
2379 // Multiply the two low parts... capturing carry into EDX
2380 BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
2381 BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
2383 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2384 BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
2385 BuildMI(BB, IP, X86::MOV32rr, 1,
2386 OverflowReg).addReg(X86::EDX); // AL*BL >> 32
2388 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
2389 BuildMI(BB, IP, X86::IMUL32rr, 2,
2390 AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2392 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2393 BuildMI(BB, IP, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
2394 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2396 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2397 BuildMI(BB, IP, X86::IMUL32rr, 2,
2398 ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2400 BuildMI(BB, IP, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
2401 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2405 /// visitDivRem - Handle division and remainder instructions... these
2406 /// instruction both require the same instructions to be generated, they just
2407 /// select the result from a different register. Note that both of these
2408 /// instructions work differently for signed and unsigned operands.
2410 void ISel::visitDivRem(BinaryOperator &I) {
2411 unsigned ResultReg = getReg(I);
2412 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2414 // Fold loads into floating point divides.
2415 if (getClass(Op0->getType()) == cFP) {
2416 if (LoadInst *LI = dyn_cast<LoadInst>(Op1))
2417 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2418 const Type *Ty = Op0->getType();
2419 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2420 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIV32m : X86::FDIV64m;
2422 unsigned BaseReg, Scale, IndexReg, Disp;
2423 getAddressingMode(LI->getOperand(0), BaseReg,
2424 Scale, IndexReg, Disp);
2426 unsigned Op0r = getReg(Op0);
2427 addFullAddress(BuildMI(BB, Opcode, 2, ResultReg).addReg(Op0r),
2428 BaseReg, Scale, IndexReg, Disp);
2432 if (LoadInst *LI = dyn_cast<LoadInst>(Op0))
2433 if (isSafeToFoldLoadIntoInstruction(*LI, I)) {
2434 const Type *Ty = Op0->getType();
2435 assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
2436 unsigned Opcode = Ty == Type::FloatTy ? X86::FDIVR32m : X86::FDIVR64m;
2438 unsigned BaseReg, Scale, IndexReg, Disp;
2439 getAddressingMode(LI->getOperand(0), BaseReg,
2440 Scale, IndexReg, Disp);
2442 unsigned Op1r = getReg(Op1);
2443 addFullAddress(BuildMI(BB, Opcode, 2, ResultReg).addReg(Op1r),
2444 BaseReg, Scale, IndexReg, Disp);
2450 MachineBasicBlock::iterator IP = BB->end();
2451 emitDivRemOperation(BB, IP, Op0, Op1,
2452 I.getOpcode() == Instruction::Div, ResultReg);
2455 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
2456 MachineBasicBlock::iterator IP,
2457 Value *Op0, Value *Op1, bool isDiv,
2458 unsigned ResultReg) {
2459 const Type *Ty = Op0->getType();
2460 unsigned Class = getClass(Ty);
2462 case cFP: // Floating point divide
2464 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2466 } else { // Floating point remainder...
2467 unsigned Op0Reg = getReg(Op0, BB, IP);
2468 unsigned Op1Reg = getReg(Op1, BB, IP);
2469 MachineInstr *TheCall =
2470 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
2471 std::vector<ValueRecord> Args;
2472 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2473 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2474 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
2478 static const char *FnName[] =
2479 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
2480 unsigned Op0Reg = getReg(Op0, BB, IP);
2481 unsigned Op1Reg = getReg(Op1, BB, IP);
2482 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2483 MachineInstr *TheCall =
2484 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
2486 std::vector<ValueRecord> Args;
2487 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2488 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2489 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
2492 case cByte: case cShort: case cInt:
2493 break; // Small integrals, handled below...
2494 default: assert(0 && "Unknown class!");
2497 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
2498 static const unsigned NEGOpcode[] = { X86::NEG8r, X86::NEG16r, X86::NEG32r };
2499 static const unsigned SAROpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
2500 static const unsigned SHROpcode[]={ X86::SHR8ri, X86::SHR16ri, X86::SHR32ri };
2501 static const unsigned ADDOpcode[]={ X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
2503 // Special case signed division by power of 2.
2505 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2506 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2507 int V = CI->getValue();
2509 if (V == 1) { // X /s 1 => X
2510 unsigned Op0Reg = getReg(Op0, BB, IP);
2511 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2515 if (V == -1) { // X /s -1 => -X
2516 unsigned Op0Reg = getReg(Op0, BB, IP);
2517 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(Op0Reg);
2522 if (V < 0) { // Not a positive power of 2?
2524 isNeg = true; // Maybe it's a negative power of 2.
2526 if (unsigned Log = ExactLog2(V)) {
2528 unsigned Op0Reg = getReg(Op0, BB, IP);
2529 unsigned TmpReg = makeAnotherReg(Op0->getType());
2531 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg)
2532 .addReg(Op0Reg).addImm(Log-1);
2534 BuildMI(*BB, IP, MovOpcode[Class], 1, TmpReg).addReg(Op0Reg);
2535 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2536 BuildMI(*BB, IP, SHROpcode[Class], 2, TmpReg2)
2537 .addReg(TmpReg).addImm(32-Log);
2538 unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2539 BuildMI(*BB, IP, ADDOpcode[Class], 2, TmpReg3)
2540 .addReg(Op0Reg).addReg(TmpReg2);
2542 unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2543 BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg4)
2544 .addReg(Op0Reg).addImm(Log);
2546 BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg4);
2551 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
2552 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
2553 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
2555 static const unsigned DivOpcode[][4] = {
2556 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
2557 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
2560 unsigned Reg = Regs[Class];
2561 unsigned ExtReg = ExtRegs[Class];
2563 // Put the first operand into one of the A registers...
2564 unsigned Op0Reg = getReg(Op0, BB, IP);
2565 unsigned Op1Reg = getReg(Op1, BB, IP);
2566 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
2568 if (Ty->isSigned()) {
2569 // Emit a sign extension instruction...
2570 unsigned ShiftResult = makeAnotherReg(Op0->getType());
2571 BuildMI(*BB, IP, SAROpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
2572 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
2574 // Emit the appropriate divide or remainder instruction...
2575 BuildMI(*BB, IP, DivOpcode[1][Class], 1).addReg(Op1Reg);
2577 // If unsigned, emit a zeroing instruction... (reg = 0)
2578 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
2580 // Emit the appropriate divide or remainder instruction...
2581 BuildMI(*BB, IP, DivOpcode[0][Class], 1).addReg(Op1Reg);
2584 // Figure out which register we want to pick the result out of...
2585 unsigned DestReg = isDiv ? Reg : ExtReg;
2587 // Put the result into the destination register...
2588 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
2592 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2593 /// for constant immediate shift values, and for constant immediate
2594 /// shift values equal to 1. Even the general case is sort of special,
2595 /// because the shift amount has to be in CL, not just any old register.
2597 void ISel::visitShiftInst(ShiftInst &I) {
2598 MachineBasicBlock::iterator IP = BB->end ();
2599 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
2600 I.getOpcode () == Instruction::Shl, I.getType (),
2604 /// emitShiftOperation - Common code shared between visitShiftInst and
2605 /// constant expression support.
2606 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2607 MachineBasicBlock::iterator IP,
2608 Value *Op, Value *ShiftAmount, bool isLeftShift,
2609 const Type *ResultTy, unsigned DestReg) {
2610 unsigned SrcReg = getReg (Op, MBB, IP);
2611 bool isSigned = ResultTy->isSigned ();
2612 unsigned Class = getClass (ResultTy);
2614 static const unsigned ConstantOperand[][4] = {
2615 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 }, // SHR
2616 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 }, // SAR
2617 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SHL
2618 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SAL = SHL
2621 static const unsigned NonConstantOperand[][4] = {
2622 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
2623 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
2624 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
2625 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
2628 // Longs, as usual, are handled specially...
2629 if (Class == cLong) {
2630 // If we have a constant shift, we can generate much more efficient code
2631 // than otherwise...
2633 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2634 unsigned Amount = CUI->getValue();
2636 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2638 BuildMI(*MBB, IP, Opc[3], 3,
2639 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
2640 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
2642 BuildMI(*MBB, IP, Opc[3], 3,
2643 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
2644 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
2646 } else { // Shifting more than 32 bits
2650 BuildMI(*MBB, IP, X86::SHL32ri, 2,
2651 DestReg + 1).addReg(SrcReg).addImm(Amount);
2653 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
2655 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
2658 BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
2659 DestReg).addReg(SrcReg+1).addImm(Amount);
2661 BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
2663 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2667 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2669 if (!isLeftShift && isSigned) {
2670 // If this is a SHR of a Long, then we need to do funny sign extension
2671 // stuff. TmpReg gets the value to use as the high-part if we are
2672 // shifting more than 32 bits.
2673 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
2675 // Other shifts use a fixed zero value if the shift is more than 32
2677 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
2680 // Initialize CL with the shift amount...
2681 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
2682 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2684 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2685 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2687 // TmpReg2 = shld inHi, inLo
2688 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
2690 // TmpReg3 = shl inLo, CL
2691 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
2693 // Set the flags to indicate whether the shift was by more than 32 bits.
2694 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2696 // DestHi = (>32) ? TmpReg3 : TmpReg2;
2697 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2698 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
2699 // DestLo = (>32) ? TmpReg : TmpReg3;
2700 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2701 DestReg).addReg(TmpReg3).addReg(TmpReg);
2703 // TmpReg2 = shrd inLo, inHi
2704 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
2706 // TmpReg3 = s[ah]r inHi, CL
2707 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
2710 // Set the flags to indicate whether the shift was by more than 32 bits.
2711 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2713 // DestLo = (>32) ? TmpReg3 : TmpReg2;
2714 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2715 DestReg).addReg(TmpReg2).addReg(TmpReg3);
2717 // DestHi = (>32) ? TmpReg : TmpReg3;
2718 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
2719 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
2725 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2726 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2727 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2729 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
2730 BuildMI(*MBB, IP, Opc[Class], 2,
2731 DestReg).addReg(SrcReg).addImm(CUI->getValue());
2732 } else { // The shift amount is non-constant.
2733 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2734 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2736 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
2737 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
2742 void ISel::getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
2743 unsigned &IndexReg, unsigned &Disp) {
2744 BaseReg = 0; Scale = 1; IndexReg = 0; Disp = 0;
2745 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
2746 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
2747 BaseReg, Scale, IndexReg, Disp))
2749 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2750 if (CE->getOpcode() == Instruction::GetElementPtr)
2751 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
2752 BaseReg, Scale, IndexReg, Disp))
2756 // If it's not foldable, reset addr mode.
2757 BaseReg = getReg(Addr);
2758 Scale = 1; IndexReg = 0; Disp = 0;
2762 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
2763 /// instruction. The load and store instructions are the only place where we
2764 /// need to worry about the memory layout of the target machine.
2766 void ISel::visitLoadInst(LoadInst &I) {
2767 // Check to see if this load instruction is going to be folded into a binary
2768 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
2769 // pattern matching instruction selector be nice?
2770 unsigned Class = getClassB(I.getType());
2771 if (I.hasOneUse()) {
2772 Instruction *User = cast<Instruction>(I.use_back());
2773 switch (User->getOpcode()) {
2774 case Instruction::Cast:
2775 // If this is a cast from a signed-integer type to a floating point type,
2776 // fold the cast here.
2777 if (getClass(User->getType()) == cFP &&
2778 (I.getType() == Type::ShortTy || I.getType() == Type::IntTy ||
2779 I.getType() == Type::LongTy)) {
2780 unsigned DestReg = getReg(User);
2781 static const unsigned Opcode[] = {
2782 0/*BYTE*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m
2784 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
2785 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
2786 addFullAddress(BuildMI(BB, Opcode[Class], 5, DestReg),
2787 BaseReg, Scale, IndexReg, Disp);
2794 case Instruction::Add:
2795 case Instruction::Sub:
2796 case Instruction::And:
2797 case Instruction::Or:
2798 case Instruction::Xor:
2799 if (Class == cLong) User = 0;
2801 case Instruction::Mul:
2802 case Instruction::Div:
2803 if (Class != cFP) User = 0;
2804 break; // Folding only implemented for floating point.
2805 default: User = 0; break;
2809 // Okay, we found a user. If the load is the first operand and there is
2810 // no second operand load, reverse the operand ordering. Note that this
2811 // can fail for a subtract (ie, no change will be made).
2812 if (!isa<LoadInst>(User->getOperand(1)))
2813 cast<BinaryOperator>(User)->swapOperands();
2815 // Okay, now that everything is set up, if this load is used by the second
2816 // operand, and if there are no instructions that invalidate the load
2817 // before the binary operator, eliminate the load.
2818 if (User->getOperand(1) == &I &&
2819 isSafeToFoldLoadIntoInstruction(I, *User))
2820 return; // Eliminate the load!
2822 // If this is a floating point sub or div, we won't be able to swap the
2823 // operands, but we will still be able to eliminate the load.
2824 if (Class == cFP && User->getOperand(0) == &I &&
2825 !isa<LoadInst>(User->getOperand(1)) &&
2826 (User->getOpcode() == Instruction::Sub ||
2827 User->getOpcode() == Instruction::Div) &&
2828 isSafeToFoldLoadIntoInstruction(I, *User))
2829 return; // Eliminate the load!
2833 unsigned DestReg = getReg(I);
2834 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
2835 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
2837 if (Class == cLong) {
2838 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
2839 BaseReg, Scale, IndexReg, Disp);
2840 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
2841 BaseReg, Scale, IndexReg, Disp+4);
2845 static const unsigned Opcodes[] = {
2846 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m
2848 unsigned Opcode = Opcodes[Class];
2849 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
2850 addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
2851 BaseReg, Scale, IndexReg, Disp);
2854 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
2857 void ISel::visitStoreInst(StoreInst &I) {
2858 unsigned BaseReg, Scale, IndexReg, Disp;
2859 getAddressingMode(I.getOperand(1), BaseReg, Scale, IndexReg, Disp);
2861 const Type *ValTy = I.getOperand(0)->getType();
2862 unsigned Class = getClassB(ValTy);
2864 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
2865 uint64_t Val = CI->getRawValue();
2866 if (Class == cLong) {
2867 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2868 BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
2869 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2870 BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
2872 static const unsigned Opcodes[] = {
2873 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
2875 unsigned Opcode = Opcodes[Class];
2876 addFullAddress(BuildMI(BB, Opcode, 5),
2877 BaseReg, Scale, IndexReg, Disp).addImm(Val);
2879 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
2880 addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
2881 BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
2883 if (Class == cLong) {
2884 unsigned ValReg = getReg(I.getOperand(0));
2885 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2886 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2887 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2888 BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
2890 unsigned ValReg = getReg(I.getOperand(0));
2891 static const unsigned Opcodes[] = {
2892 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
2894 unsigned Opcode = Opcodes[Class];
2895 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
2896 addFullAddress(BuildMI(BB, Opcode, 1+4),
2897 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2903 /// visitCastInst - Here we have various kinds of copying with or without sign
2904 /// extension going on.
2906 void ISel::visitCastInst(CastInst &CI) {
2907 Value *Op = CI.getOperand(0);
2909 unsigned SrcClass = getClassB(Op->getType());
2910 unsigned DestClass = getClassB(CI.getType());
2911 // Noop casts are not emitted: getReg will return the source operand as the
2912 // register to use for any uses of the noop cast.
2913 if (DestClass == SrcClass)
2916 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2917 // of the case are GEP instructions, then the cast does not need to be
2918 // generated explicitly, it will be folded into the GEP.
2919 if (DestClass == cLong && SrcClass == cInt) {
2920 bool AllUsesAreGEPs = true;
2921 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2922 if (!isa<GetElementPtrInst>(*I)) {
2923 AllUsesAreGEPs = false;
2927 // No need to codegen this cast if all users are getelementptr instrs...
2928 if (AllUsesAreGEPs) return;
2931 // If this cast converts a load from a short,int, or long integer to a FP
2932 // value, we will have folded this cast away.
2933 if (DestClass == cFP && isa<LoadInst>(Op) && Op->hasOneUse() &&
2934 (Op->getType() == Type::ShortTy || Op->getType() == Type::IntTy ||
2935 Op->getType() == Type::LongTy))
2939 unsigned DestReg = getReg(CI);
2940 MachineBasicBlock::iterator MI = BB->end();
2941 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2944 /// emitCastOperation - Common code shared between visitCastInst and constant
2945 /// expression cast support.
2947 void ISel::emitCastOperation(MachineBasicBlock *BB,
2948 MachineBasicBlock::iterator IP,
2949 Value *Src, const Type *DestTy,
2951 const Type *SrcTy = Src->getType();
2952 unsigned SrcClass = getClassB(SrcTy);
2953 unsigned DestClass = getClassB(DestTy);
2954 unsigned SrcReg = getReg(Src, BB, IP);
2956 // Implement casts to bool by using compare on the operand followed by set if
2957 // not zero on the result.
2958 if (DestTy == Type::BoolTy) {
2961 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
2964 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
2967 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
2970 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2971 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
2975 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
2976 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
2977 BuildMI(*BB, IP, X86::SAHF, 1);
2981 // If the zero flag is not set, then the value is true, set the byte to
2983 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
2987 static const unsigned RegRegMove[] = {
2988 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
2991 // Implement casts between values of the same type class (as determined by
2992 // getClass) by using a register-to-register move.
2993 if (SrcClass == DestClass) {
2994 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
2995 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
2996 } else if (SrcClass == cFP) {
2997 if (SrcTy == Type::FloatTy) { // double -> float
2998 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2999 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
3000 } else { // float -> double
3001 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
3002 "Unknown cFP member!");
3003 // Truncate from double to float by storing to memory as short, then
3005 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
3006 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
3007 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
3008 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
3010 } else if (SrcClass == cLong) {
3011 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3012 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
3014 assert(0 && "Cannot handle this type of cast instruction!");
3020 // Handle cast of SMALLER int to LARGER int using a move with sign extension
3021 // or zero extension, depending on whether the source type was signed.
3022 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
3023 SrcClass < DestClass) {
3024 bool isLong = DestClass == cLong;
3025 if (isLong) DestClass = cInt;
3027 static const unsigned Opc[][4] = {
3028 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
3029 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
3032 bool isUnsigned = SrcTy->isUnsigned();
3033 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
3034 DestReg).addReg(SrcReg);
3036 if (isLong) { // Handle upper 32 bits as appropriate...
3037 if (isUnsigned) // Zero out top bits...
3038 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
3039 else // Sign extend bottom half...
3040 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
3045 // Special case long -> int ...
3046 if (SrcClass == cLong && DestClass == cInt) {
3047 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
3051 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
3052 // move out of AX or AL.
3053 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
3054 && SrcClass > DestClass) {
3055 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
3056 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
3057 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
3061 // Handle casts from integer to floating point now...
3062 if (DestClass == cFP) {
3063 // Promote the integer to a type supported by FLD. We do this because there
3064 // are no unsigned FLD instructions, so we must promote an unsigned value to
3065 // a larger signed value, then use FLD on the larger value.
3067 const Type *PromoteType = 0;
3068 unsigned PromoteOpcode = 0;
3069 unsigned RealDestReg = DestReg;
3070 switch (SrcTy->getPrimitiveID()) {
3071 case Type::BoolTyID:
3072 case Type::SByteTyID:
3073 // We don't have the facilities for directly loading byte sized data from
3074 // memory (even signed). Promote it to 16 bits.
3075 PromoteType = Type::ShortTy;
3076 PromoteOpcode = X86::MOVSX16rr8;
3078 case Type::UByteTyID:
3079 PromoteType = Type::ShortTy;
3080 PromoteOpcode = X86::MOVZX16rr8;
3082 case Type::UShortTyID:
3083 PromoteType = Type::IntTy;
3084 PromoteOpcode = X86::MOVZX32rr16;
3086 case Type::UIntTyID: {
3087 // Make a 64 bit temporary... and zero out the top of it...
3088 unsigned TmpReg = makeAnotherReg(Type::LongTy);
3089 BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
3090 BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
3091 SrcTy = Type::LongTy;
3096 case Type::ULongTyID:
3097 // Don't fild into the read destination.
3098 DestReg = makeAnotherReg(Type::DoubleTy);
3100 default: // No promotion needed...
3105 unsigned TmpReg = makeAnotherReg(PromoteType);
3106 BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
3107 SrcTy = PromoteType;
3108 SrcClass = getClass(PromoteType);
3112 // Spill the integer to memory and reload it from there...
3114 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
3116 if (SrcClass == cLong) {
3117 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
3118 FrameIdx).addReg(SrcReg);
3119 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
3120 FrameIdx, 4).addReg(SrcReg+1);
3122 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
3123 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
3124 FrameIdx).addReg(SrcReg);
3127 static const unsigned Op2[] =
3128 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
3129 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
3131 // We need special handling for unsigned 64-bit integer sources. If the
3132 // input number has the "sign bit" set, then we loaded it incorrectly as a
3133 // negative 64-bit number. In this case, add an offset value.
3134 if (SrcTy == Type::ULongTy) {
3135 // Emit a test instruction to see if the dynamic input value was signed.
3136 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
3138 // If the sign bit is set, get a pointer to an offset, otherwise get a
3139 // pointer to a zero.
3140 MachineConstantPool *CP = F->getConstantPool();
3141 unsigned Zero = makeAnotherReg(Type::IntTy);
3142 Constant *Null = Constant::getNullValue(Type::UIntTy);
3143 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
3144 CP->getConstantPoolIndex(Null));
3145 unsigned Offset = makeAnotherReg(Type::IntTy);
3146 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
3148 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
3149 CP->getConstantPoolIndex(OffsetCst));
3150 unsigned Addr = makeAnotherReg(Type::IntTy);
3151 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
3153 // Load the constant for an add. FIXME: this could make an 'fadd' that
3154 // reads directly from memory, but we don't support these yet.
3155 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
3156 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
3158 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
3159 .addReg(ConstReg).addReg(DestReg);
3165 // Handle casts from floating point to integer now...
3166 if (SrcClass == cFP) {
3167 // Change the floating point control register to use "round towards zero"
3168 // mode when truncating to an integer value.
3170 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
3171 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
3173 // Load the old value of the high byte of the control word...
3174 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
3175 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
3178 // Set the high part to be round to zero...
3179 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
3180 CWFrameIdx, 1).addImm(12);
3182 // Reload the modified control word now...
3183 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
3185 // Restore the memory image of control word to original value
3186 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
3187 CWFrameIdx, 1).addReg(HighPartOfCW);
3189 // We don't have the facilities for directly storing byte sized data to
3190 // memory. Promote it to 16 bits. We also must promote unsigned values to
3191 // larger classes because we only have signed FP stores.
3192 unsigned StoreClass = DestClass;
3193 const Type *StoreTy = DestTy;
3194 if (StoreClass == cByte || DestTy->isUnsigned())
3195 switch (StoreClass) {
3196 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
3197 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
3198 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
3199 // The following treatment of cLong may not be perfectly right,
3200 // but it survives chains of casts of the form
3201 // double->ulong->double.
3202 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
3203 default: assert(0 && "Unknown store class!");
3206 // Spill the integer to memory and reload it from there...
3208 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
3210 static const unsigned Op1[] =
3211 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
3212 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
3213 FrameIdx).addReg(SrcReg);
3215 if (DestClass == cLong) {
3216 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
3217 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
3220 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
3221 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
3224 // Reload the original control word now...
3225 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
3229 // Anything we haven't handled already, we can't (yet) handle at all.
3230 assert(0 && "Unhandled cast instruction!");
3234 /// visitVANextInst - Implement the va_next instruction...
3236 void ISel::visitVANextInst(VANextInst &I) {
3237 unsigned VAList = getReg(I.getOperand(0));
3238 unsigned DestReg = getReg(I);
3241 switch (I.getArgType()->getPrimitiveID()) {
3244 assert(0 && "Error: bad type for va_next instruction!");
3246 case Type::PointerTyID:
3247 case Type::UIntTyID:
3251 case Type::ULongTyID:
3252 case Type::LongTyID:
3253 case Type::DoubleTyID:
3258 // Increment the VAList pointer...
3259 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
3262 void ISel::visitVAArgInst(VAArgInst &I) {
3263 unsigned VAList = getReg(I.getOperand(0));
3264 unsigned DestReg = getReg(I);
3266 switch (I.getType()->getPrimitiveID()) {
3269 assert(0 && "Error: bad type for va_next instruction!");
3271 case Type::PointerTyID:
3272 case Type::UIntTyID:
3274 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3276 case Type::ULongTyID:
3277 case Type::LongTyID:
3278 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
3279 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
3281 case Type::DoubleTyID:
3282 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
3287 /// visitGetElementPtrInst - instruction-select GEP instructions
3289 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
3290 // If this GEP instruction will be folded into all of its users, we don't need
3291 // to explicitly calculate it!
3292 unsigned A, B, C, D;
3293 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
3294 // Check all of the users of the instruction to see if they are loads and
3296 bool AllWillFold = true;
3297 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
3298 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
3299 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
3300 cast<Instruction>(*UI)->getOperand(0) == &I) {
3301 AllWillFold = false;
3305 // If the instruction is foldable, and will be folded into all users, don't
3307 if (AllWillFold) return;
3310 unsigned outputReg = getReg(I);
3311 emitGEPOperation(BB, BB->end(), I.getOperand(0),
3312 I.op_begin()+1, I.op_end(), outputReg);
3315 /// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
3316 /// GEPTypes (the derived types being stepped through at each level). On return
3317 /// from this function, if some indexes of the instruction are representable as
3318 /// an X86 lea instruction, the machine operands are put into the Ops
3319 /// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
3320 /// lists. Otherwise, GEPOps.size() is returned. If this returns a an
3321 /// addressing mode that only partially consumes the input, the BaseReg input of
3322 /// the addressing mode must be left free.
3324 /// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
3326 void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
3327 std::vector<Value*> &GEPOps,
3328 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
3329 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
3330 const TargetData &TD = TM.getTargetData();
3332 // Clear out the state we are working with...
3333 BaseReg = 0; // No base register
3334 Scale = 1; // Unit scale
3335 IndexReg = 0; // No index register
3336 Disp = 0; // No displacement
3338 // While there are GEP indexes that can be folded into the current address,
3339 // keep processing them.
3340 while (!GEPTypes.empty()) {
3341 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
3342 // It's a struct access. CUI is the index into the structure,
3343 // which names the field. This index must have unsigned type.
3344 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
3346 // Use the TargetData structure to pick out what the layout of the
3347 // structure is in memory. Since the structure index must be constant, we
3348 // can get its value and use it to find the right byte offset from the
3349 // StructLayout class's list of structure member offsets.
3350 Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
3351 GEPOps.pop_back(); // Consume a GEP operand
3352 GEPTypes.pop_back();
3354 // It's an array or pointer access: [ArraySize x ElementType].
3355 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3356 Value *idx = GEPOps.back();
3358 // idx is the index into the array. Unlike with structure
3359 // indices, we may not know its actual value at code-generation
3362 // If idx is a constant, fold it into the offset.
3363 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
3364 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
3365 Disp += TypeSize*CSI->getValue();
3366 } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
3367 Disp += TypeSize*CUI->getValue();
3369 // If the index reg is already taken, we can't handle this index.
3370 if (IndexReg) return;
3372 // If this is a size that we can handle, then add the index as
3374 case 1: case 2: case 4: case 8:
3375 // These are all acceptable scales on X86.
3379 // Otherwise, we can't handle this scale
3383 if (CastInst *CI = dyn_cast<CastInst>(idx))
3384 if (CI->getOperand(0)->getType() == Type::IntTy ||
3385 CI->getOperand(0)->getType() == Type::UIntTy)
3386 idx = CI->getOperand(0);
3388 IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
3391 GEPOps.pop_back(); // Consume a GEP operand
3392 GEPTypes.pop_back();
3396 // GEPTypes is empty, which means we have a single operand left. See if we
3397 // can set it as the base register.
3399 // FIXME: When addressing modes are more powerful/correct, we could load
3400 // global addresses directly as 32-bit immediates.
3401 assert(BaseReg == 0);
3402 BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
3403 GEPOps.pop_back(); // Consume the last GEP operand
3407 /// isGEPFoldable - Return true if the specified GEP can be completely
3408 /// folded into the addressing mode of a load/store or lea instruction.
3409 bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
3410 Value *Src, User::op_iterator IdxBegin,
3411 User::op_iterator IdxEnd, unsigned &BaseReg,
3412 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
3413 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
3414 Src = CPR->getValue();
3416 std::vector<Value*> GEPOps;
3417 GEPOps.resize(IdxEnd-IdxBegin+1);
3419 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3421 std::vector<const Type*> GEPTypes;
3422 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3423 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3425 MachineBasicBlock::iterator IP;
3426 if (MBB) IP = MBB->end();
3427 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
3429 // We can fold it away iff the getGEPIndex call eliminated all operands.
3430 return GEPOps.empty();
3433 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
3434 MachineBasicBlock::iterator IP,
3435 Value *Src, User::op_iterator IdxBegin,
3436 User::op_iterator IdxEnd, unsigned TargetReg) {
3437 const TargetData &TD = TM.getTargetData();
3438 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
3439 Src = CPR->getValue();
3441 std::vector<Value*> GEPOps;
3442 GEPOps.resize(IdxEnd-IdxBegin+1);
3444 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
3446 std::vector<const Type*> GEPTypes;
3447 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
3448 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
3450 // Keep emitting instructions until we consume the entire GEP instruction.
3451 while (!GEPOps.empty()) {
3452 unsigned OldSize = GEPOps.size();
3453 unsigned BaseReg, Scale, IndexReg, Disp;
3454 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
3456 if (GEPOps.size() != OldSize) {
3457 // getGEPIndex consumed some of the input. Build an LEA instruction here.
3458 unsigned NextTarget = 0;
3459 if (!GEPOps.empty()) {
3460 assert(BaseReg == 0 &&
3461 "getGEPIndex should have left the base register open for chaining!");
3462 NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
3465 if (IndexReg == 0 && Disp == 0)
3466 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
3468 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
3469 BaseReg, Scale, IndexReg, Disp);
3471 TargetReg = NextTarget;
3472 } else if (GEPTypes.empty()) {
3473 // The getGEPIndex operation didn't want to build an LEA. Check to see if
3474 // all operands are consumed but the base pointer. If so, just load it
3475 // into the register.
3476 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
3477 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
3479 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
3480 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
3482 break; // we are now done
3485 // It's an array or pointer access: [ArraySize x ElementType].
3486 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
3487 Value *idx = GEPOps.back();
3488 GEPOps.pop_back(); // Consume a GEP operand
3489 GEPTypes.pop_back();
3491 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
3492 // operand on X86. Handle this case directly now...
3493 if (CastInst *CI = dyn_cast<CastInst>(idx))
3494 if (CI->getOperand(0)->getType() == Type::IntTy ||
3495 CI->getOperand(0)->getType() == Type::UIntTy)
3496 idx = CI->getOperand(0);
3498 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
3499 // must find the size of the pointed-to type (Not coincidentally, the next
3500 // type is the type of the elements in the array).
3501 const Type *ElTy = SqTy->getElementType();
3502 unsigned elementSize = TD.getTypeSize(ElTy);
3504 // If idxReg is a constant, we don't need to perform the multiply!
3505 if (ConstantInt *CSI = dyn_cast<ConstantInt>(idx)) {
3506 if (!CSI->isNullValue()) {
3507 unsigned Offset = elementSize*CSI->getRawValue();
3508 unsigned Reg = makeAnotherReg(Type::UIntTy);
3509 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
3510 .addReg(Reg).addImm(Offset);
3511 --IP; // Insert the next instruction before this one.
3512 TargetReg = Reg; // Codegen the rest of the GEP into this
3514 } else if (elementSize == 1) {
3515 // If the element size is 1, we don't have to multiply, just add
3516 unsigned idxReg = getReg(idx, MBB, IP);
3517 unsigned Reg = makeAnotherReg(Type::UIntTy);
3518 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
3519 --IP; // Insert the next instruction before this one.
3520 TargetReg = Reg; // Codegen the rest of the GEP into this
3522 unsigned idxReg = getReg(idx, MBB, IP);
3523 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
3525 // Make sure we can back the iterator up to point to the first
3526 // instruction emitted.
3527 MachineBasicBlock::iterator BeforeIt = IP;
3528 if (IP == MBB->begin())
3529 BeforeIt = MBB->end();
3532 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
3534 // Emit an ADD to add OffsetReg to the basePtr.
3535 unsigned Reg = makeAnotherReg(Type::UIntTy);
3536 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
3537 .addReg(Reg).addReg(OffsetReg);
3539 // Step to the first instruction of the multiply.
3540 if (BeforeIt == MBB->end())
3545 TargetReg = Reg; // Codegen the rest of the GEP into this
3552 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
3553 /// frame manager, otherwise do it the hard way.
3555 void ISel::visitAllocaInst(AllocaInst &I) {
3556 // Find the data size of the alloca inst's getAllocatedType.
3557 const Type *Ty = I.getAllocatedType();
3558 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
3560 // If this is a fixed size alloca in the entry block for the function,
3561 // statically stack allocate the space.
3563 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
3564 if (I.getParent() == I.getParent()->getParent()->begin()) {
3565 TySize *= CUI->getValue(); // Get total allocated size...
3566 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
3568 // Create a new stack object using the frame manager...
3569 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
3570 addFrameReference(BuildMI(BB, X86::LEA32r, 5, getReg(I)), FrameIdx);
3575 // Create a register to hold the temporary result of multiplying the type size
3576 // constant by the variable amount.
3577 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
3578 unsigned SrcReg1 = getReg(I.getArraySize());
3580 // TotalSizeReg = mul <numelements>, <TypeSize>
3581 MachineBasicBlock::iterator MBBI = BB->end();
3582 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
3584 // AddedSize = add <TotalSizeReg>, 15
3585 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
3586 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
3588 // AlignedSize = and <AddedSize>, ~15
3589 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
3590 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
3592 // Subtract size from stack pointer, thereby allocating some space.
3593 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
3595 // Put a pointer to the space into the result register, by copying
3596 // the stack pointer.
3597 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
3599 // Inform the Frame Information that we have just allocated a variable-sized
3601 F->getFrameInfo()->CreateVariableSizedObject();
3604 /// visitMallocInst - Malloc instructions are code generated into direct calls
3605 /// to the library malloc.
3607 void ISel::visitMallocInst(MallocInst &I) {
3608 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
3611 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
3612 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
3614 Arg = makeAnotherReg(Type::UIntTy);
3615 unsigned Op0Reg = getReg(I.getOperand(0));
3616 MachineBasicBlock::iterator MBBI = BB->end();
3617 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
3620 std::vector<ValueRecord> Args;
3621 Args.push_back(ValueRecord(Arg, Type::UIntTy));
3622 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
3623 1).addExternalSymbol("malloc", true);
3624 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
3628 /// visitFreeInst - Free instructions are code gen'd to call the free libc
3631 void ISel::visitFreeInst(FreeInst &I) {
3632 std::vector<ValueRecord> Args;
3633 Args.push_back(ValueRecord(I.getOperand(0)));
3634 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
3635 1).addExternalSymbol("free", true);
3636 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
3639 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
3640 /// into a machine code representation is a very simple peep-hole fashion. The
3641 /// generated code sucks but the implementation is nice and simple.
3643 FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
3644 return new ISel(TM);