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 "llvm/Support/CFG.h"
32 #include "Support/Statistic.h"
37 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
41 struct ISel : public FunctionPass, InstVisitor<ISel> {
43 MachineFunction *F; // The function we are compiling into
44 MachineBasicBlock *BB; // The current MBB we are compiling
45 int VarArgsFrameIndex; // FrameIndex for start of varargs area
46 int ReturnAddressIndex; // FrameIndex for the return address
48 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
50 // MBBMap - Mapping between LLVM BB -> Machine BB
51 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
53 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
55 /// runOnFunction - Top level implementation of instruction selection for
56 /// the entire function.
58 bool runOnFunction(Function &Fn) {
59 // First pass over the function, lower any unknown intrinsic functions
60 // with the IntrinsicLowering class.
61 LowerUnknownIntrinsicFunctionCalls(Fn);
63 F = &MachineFunction::construct(&Fn, TM);
65 // Create all of the machine basic blocks for the function...
66 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
67 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
71 // Set up a frame object for the return address. This is used by the
72 // llvm.returnaddress & llvm.frameaddress intrinisics.
73 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
75 // Copy incoming arguments off of the stack...
76 LoadArgumentsToVirtualRegs(Fn);
78 // Instruction select everything except PHI nodes
81 // Select the PHI nodes
84 // Insert the FP_REG_KILL instructions into blocks that need them.
90 // We always build a machine code representation for the function
94 virtual const char *getPassName() const {
95 return "X86 Simple Instruction Selection";
98 /// visitBasicBlock - This method is called when we are visiting a new basic
99 /// block. This simply creates a new MachineBasicBlock to emit code into
100 /// and adds it to the current MachineFunction. Subsequent visit* for
101 /// instructions will be invoked for all instructions in the basic block.
103 void visitBasicBlock(BasicBlock &LLVM_BB) {
104 BB = MBBMap[&LLVM_BB];
107 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
108 /// function, lowering any calls to unknown intrinsic functions into the
109 /// equivalent LLVM code.
111 void LowerUnknownIntrinsicFunctionCalls(Function &F);
113 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
114 /// from the stack into virtual registers.
116 void LoadArgumentsToVirtualRegs(Function &F);
118 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
119 /// because we have to generate our sources into the source basic blocks,
120 /// not the current one.
122 void SelectPHINodes();
124 /// InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks
125 /// that need them. This only occurs due to the floating point stackifier
126 /// not being aggressive enough to handle arbitrary global stackification.
128 void InsertFPRegKills();
130 // Visitation methods for various instructions. These methods simply emit
131 // fixed X86 code for each instruction.
134 // Control flow operators
135 void visitReturnInst(ReturnInst &RI);
136 void visitBranchInst(BranchInst &BI);
142 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
143 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
145 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
146 const std::vector<ValueRecord> &Args);
147 void visitCallInst(CallInst &I);
148 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
150 // Arithmetic operators
151 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
152 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
153 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
154 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
155 unsigned DestReg, const Type *DestTy,
156 unsigned Op0Reg, unsigned Op1Reg);
157 void doMultiplyConst(MachineBasicBlock *MBB,
158 MachineBasicBlock::iterator MBBI,
159 unsigned DestReg, const Type *DestTy,
160 unsigned Op0Reg, unsigned Op1Val);
161 void visitMul(BinaryOperator &B);
163 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
164 void visitRem(BinaryOperator &B) { visitDivRem(B); }
165 void visitDivRem(BinaryOperator &B);
168 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
169 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
170 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
172 // Comparison operators...
173 void visitSetCondInst(SetCondInst &I);
174 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
175 MachineBasicBlock *MBB,
176 MachineBasicBlock::iterator MBBI);
178 // Memory Instructions
179 void visitLoadInst(LoadInst &I);
180 void visitStoreInst(StoreInst &I);
181 void visitGetElementPtrInst(GetElementPtrInst &I);
182 void visitAllocaInst(AllocaInst &I);
183 void visitMallocInst(MallocInst &I);
184 void visitFreeInst(FreeInst &I);
187 void visitShiftInst(ShiftInst &I);
188 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
189 void visitCastInst(CastInst &I);
190 void visitVANextInst(VANextInst &I);
191 void visitVAArgInst(VAArgInst &I);
193 void visitInstruction(Instruction &I) {
194 std::cerr << "Cannot instruction select: " << I;
198 /// promote32 - Make a value 32-bits wide, and put it somewhere.
200 void promote32(unsigned targetReg, const ValueRecord &VR);
202 /// getAddressingMode - Get the addressing mode to use to address the
203 /// specified value. The returned value should be used with addFullAddress.
204 void getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
205 unsigned &IndexReg, unsigned &Disp);
208 /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
210 void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
211 std::vector<Value*> &GEPOps,
212 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
213 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
215 /// isGEPFoldable - Return true if the specified GEP can be completely
216 /// folded into the addressing mode of a load/store or lea instruction.
217 bool isGEPFoldable(MachineBasicBlock *MBB,
218 Value *Src, User::op_iterator IdxBegin,
219 User::op_iterator IdxEnd, unsigned &BaseReg,
220 unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
222 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
223 /// constant expression GEP support.
225 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
226 Value *Src, User::op_iterator IdxBegin,
227 User::op_iterator IdxEnd, unsigned TargetReg);
229 /// emitCastOperation - Common code shared between visitCastInst and
230 /// constant expression cast support.
232 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
233 Value *Src, const Type *DestTy, unsigned TargetReg);
235 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
236 /// and constant expression support.
238 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
239 MachineBasicBlock::iterator IP,
240 Value *Op0, Value *Op1,
241 unsigned OperatorClass, unsigned TargetReg);
243 void emitDivRemOperation(MachineBasicBlock *BB,
244 MachineBasicBlock::iterator IP,
245 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
246 const Type *Ty, unsigned TargetReg);
248 /// emitSetCCOperation - Common code shared between visitSetCondInst and
249 /// constant expression support.
251 void emitSetCCOperation(MachineBasicBlock *BB,
252 MachineBasicBlock::iterator IP,
253 Value *Op0, Value *Op1, unsigned Opcode,
256 /// emitShiftOperation - Common code shared between visitShiftInst and
257 /// constant expression support.
259 void emitShiftOperation(MachineBasicBlock *MBB,
260 MachineBasicBlock::iterator IP,
261 Value *Op, Value *ShiftAmount, bool isLeftShift,
262 const Type *ResultTy, unsigned DestReg);
265 /// copyConstantToRegister - Output the instructions required to put the
266 /// specified constant into the specified register.
268 void copyConstantToRegister(MachineBasicBlock *MBB,
269 MachineBasicBlock::iterator MBBI,
270 Constant *C, unsigned Reg);
272 /// makeAnotherReg - This method returns the next register number we haven't
275 /// Long values are handled somewhat specially. They are always allocated
276 /// as pairs of 32 bit integer values. The register number returned is the
277 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
278 /// of the long value.
280 unsigned makeAnotherReg(const Type *Ty) {
281 assert(dynamic_cast<const X86RegisterInfo*>(TM.getRegisterInfo()) &&
282 "Current target doesn't have X86 reg info??");
283 const X86RegisterInfo *MRI =
284 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
285 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
286 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
287 // Create the lower part
288 F->getSSARegMap()->createVirtualRegister(RC);
289 // Create the upper part.
290 return F->getSSARegMap()->createVirtualRegister(RC)-1;
293 // Add the mapping of regnumber => reg class to MachineFunction
294 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
295 return F->getSSARegMap()->createVirtualRegister(RC);
298 /// getReg - This method turns an LLVM value into a register number. This
299 /// is guaranteed to produce the same register number for a particular value
300 /// every time it is queried.
302 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
303 unsigned getReg(Value *V) {
304 // Just append to the end of the current bb.
305 MachineBasicBlock::iterator It = BB->end();
306 return getReg(V, BB, It);
308 unsigned getReg(Value *V, MachineBasicBlock *MBB,
309 MachineBasicBlock::iterator IPt) {
310 unsigned &Reg = RegMap[V];
312 Reg = makeAnotherReg(V->getType());
316 // If this operand is a constant, emit the code to copy the constant into
317 // the register here...
319 if (Constant *C = dyn_cast<Constant>(V)) {
320 copyConstantToRegister(MBB, IPt, C, Reg);
321 RegMap.erase(V); // Assign a new name to this constant if ref'd again
322 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
323 // Move the address of the global into the register
324 BuildMI(*MBB, IPt, X86::MOV32ri, 1, Reg).addGlobalAddress(GV);
325 RegMap.erase(V); // Assign a new name to this address if ref'd again
333 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
337 cByte, cShort, cInt, cFP, cLong
340 /// getClass - Turn a primitive type into a "class" number which is based on the
341 /// size of the type, and whether or not it is floating point.
343 static inline TypeClass getClass(const Type *Ty) {
344 switch (Ty->getPrimitiveID()) {
345 case Type::SByteTyID:
346 case Type::UByteTyID: return cByte; // Byte operands are class #0
347 case Type::ShortTyID:
348 case Type::UShortTyID: return cShort; // Short operands are class #1
351 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
353 case Type::FloatTyID:
354 case Type::DoubleTyID: return cFP; // Floating Point is #3
357 case Type::ULongTyID: return cLong; // Longs are class #4
359 assert(0 && "Invalid type to getClass!");
360 return cByte; // not reached
364 // getClassB - Just like getClass, but treat boolean values as bytes.
365 static inline TypeClass getClassB(const Type *Ty) {
366 if (Ty == Type::BoolTy) return cByte;
371 /// copyConstantToRegister - Output the instructions required to put the
372 /// specified constant into the specified register.
374 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
375 MachineBasicBlock::iterator IP,
376 Constant *C, unsigned R) {
377 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
379 switch (CE->getOpcode()) {
380 case Instruction::GetElementPtr:
381 emitGEPOperation(MBB, IP, CE->getOperand(0),
382 CE->op_begin()+1, CE->op_end(), R);
384 case Instruction::Cast:
385 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
388 case Instruction::Xor: ++Class; // FALL THROUGH
389 case Instruction::Or: ++Class; // FALL THROUGH
390 case Instruction::And: ++Class; // FALL THROUGH
391 case Instruction::Sub: ++Class; // FALL THROUGH
392 case Instruction::Add:
393 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
397 case Instruction::Mul: {
398 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
399 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
400 doMultiply(MBB, IP, R, CE->getType(), Op0Reg, Op1Reg);
403 case Instruction::Div:
404 case Instruction::Rem: {
405 unsigned Op0Reg = getReg(CE->getOperand(0), MBB, IP);
406 unsigned Op1Reg = getReg(CE->getOperand(1), MBB, IP);
407 emitDivRemOperation(MBB, IP, Op0Reg, Op1Reg,
408 CE->getOpcode() == Instruction::Div,
413 case Instruction::SetNE:
414 case Instruction::SetEQ:
415 case Instruction::SetLT:
416 case Instruction::SetGT:
417 case Instruction::SetLE:
418 case Instruction::SetGE:
419 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
423 case Instruction::Shl:
424 case Instruction::Shr:
425 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
426 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
430 std::cerr << "Offending expr: " << C << "\n";
431 assert(0 && "Constant expression not yet handled!\n");
435 if (C->getType()->isIntegral()) {
436 unsigned Class = getClassB(C->getType());
438 if (Class == cLong) {
439 // Copy the value into the register pair.
440 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
441 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(Val & 0xFFFFFFFF);
442 BuildMI(*MBB, IP, X86::MOV32ri, 1, R+1).addImm(Val >> 32);
446 assert(Class <= cInt && "Type not handled yet!");
448 static const unsigned IntegralOpcodeTab[] = {
449 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
452 if (C->getType() == Type::BoolTy) {
453 BuildMI(*MBB, IP, X86::MOV8ri, 1, R).addImm(C == ConstantBool::True);
455 ConstantInt *CI = cast<ConstantInt>(C);
456 BuildMI(*MBB, IP, IntegralOpcodeTab[Class],1,R).addImm(CI->getRawValue());
458 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
459 if (CFP->isExactlyValue(+0.0))
460 BuildMI(*MBB, IP, X86::FLD0, 0, R);
461 else if (CFP->isExactlyValue(+1.0))
462 BuildMI(*MBB, IP, X86::FLD1, 0, R);
464 // Otherwise we need to spill the constant to memory...
465 MachineConstantPool *CP = F->getConstantPool();
466 unsigned CPI = CP->getConstantPoolIndex(CFP);
467 const Type *Ty = CFP->getType();
469 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
470 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
471 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
474 } else if (isa<ConstantPointerNull>(C)) {
475 // Copy zero (null pointer) to the register.
476 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
477 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
478 BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(CPR->getValue());
480 std::cerr << "Offending constant: " << C << "\n";
481 assert(0 && "Type not handled yet!");
485 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
486 /// the stack into virtual registers.
488 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
489 // Emit instructions to load the arguments... On entry to a function on the
490 // X86, the stack frame looks like this:
492 // [ESP] -- return address
493 // [ESP + 4] -- first argument (leftmost lexically)
494 // [ESP + 8] -- second argument, if first argument is four bytes in size
497 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
498 MachineFrameInfo *MFI = F->getFrameInfo();
500 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
501 unsigned Reg = getReg(*I);
503 int FI; // Frame object index
504 switch (getClassB(I->getType())) {
506 FI = MFI->CreateFixedObject(1, ArgOffset);
507 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Reg), FI);
510 FI = MFI->CreateFixedObject(2, ArgOffset);
511 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Reg), FI);
514 FI = MFI->CreateFixedObject(4, ArgOffset);
515 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
518 FI = MFI->CreateFixedObject(8, ArgOffset);
519 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg), FI);
520 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Reg+1), FI, 4);
521 ArgOffset += 4; // longs require 4 additional bytes
525 if (I->getType() == Type::FloatTy) {
526 Opcode = X86::FLD32m;
527 FI = MFI->CreateFixedObject(4, ArgOffset);
529 Opcode = X86::FLD64m;
530 FI = MFI->CreateFixedObject(8, ArgOffset);
531 ArgOffset += 4; // doubles require 4 additional bytes
533 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
536 assert(0 && "Unhandled argument type!");
538 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
541 // If the function takes variable number of arguments, add a frame offset for
542 // the start of the first vararg value... this is used to expand
544 if (Fn.getFunctionType()->isVarArg())
545 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
549 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
550 /// because we have to generate our sources into the source basic blocks, not
553 void ISel::SelectPHINodes() {
554 const TargetInstrInfo &TII = TM.getInstrInfo();
555 const Function &LF = *F->getFunction(); // The LLVM function...
556 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
557 const BasicBlock *BB = I;
558 MachineBasicBlock &MBB = *MBBMap[I];
560 // Loop over all of the PHI nodes in the LLVM basic block...
561 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
562 for (BasicBlock::const_iterator I = BB->begin();
563 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
565 // Create a new machine instr PHI node, and insert it.
566 unsigned PHIReg = getReg(*PN);
567 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
568 X86::PHI, PN->getNumOperands(), PHIReg);
570 MachineInstr *LongPhiMI = 0;
571 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
572 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
573 X86::PHI, PN->getNumOperands(), PHIReg+1);
575 // PHIValues - Map of blocks to incoming virtual registers. We use this
576 // so that we only initialize one incoming value for a particular block,
577 // even if the block has multiple entries in the PHI node.
579 std::map<MachineBasicBlock*, unsigned> PHIValues;
581 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
582 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
584 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
585 PHIValues.lower_bound(PredMBB);
587 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
588 // We already inserted an initialization of the register for this
589 // predecessor. Recycle it.
590 ValReg = EntryIt->second;
593 // Get the incoming value into a virtual register.
595 Value *Val = PN->getIncomingValue(i);
597 // If this is a constant or GlobalValue, we may have to insert code
598 // into the basic block to compute it into a virtual register.
599 if (isa<Constant>(Val) || isa<GlobalValue>(Val)) {
600 // Because we don't want to clobber any values which might be in
601 // physical registers with the computation of this constant (which
602 // might be arbitrarily complex if it is a constant expression),
603 // just insert the computation at the top of the basic block.
604 MachineBasicBlock::iterator PI = PredMBB->begin();
606 // Skip over any PHI nodes though!
607 while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
610 ValReg = getReg(Val, PredMBB, PI);
612 ValReg = getReg(Val);
615 // Remember that we inserted a value for this PHI for this predecessor
616 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
619 PhiMI->addRegOperand(ValReg);
620 PhiMI->addMachineBasicBlockOperand(PredMBB);
622 LongPhiMI->addRegOperand(ValReg+1);
623 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
627 // Now that we emitted all of the incoming values for the PHI node, make
628 // sure to reposition the InsertPoint after the PHI that we just added.
629 // This is needed because we might have inserted a constant into this
630 // block, right after the PHI's which is before the old insert point!
631 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
637 /// RequiresFPRegKill - The floating point stackifier pass cannot insert
638 /// compensation code on critical edges. As such, it requires that we kill all
639 /// FP registers on the exit from any blocks that either ARE critical edges, or
640 /// branch to a block that has incoming critical edges.
642 /// Note that this kill instruction will eventually be eliminated when
643 /// restrictions in the stackifier are relaxed.
645 static bool RequiresFPRegKill(const BasicBlock *BB) {
647 for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
648 const BasicBlock *Succ = *SI;
649 pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
650 ++PI; // Block have at least one predecessory
651 if (PI != PE) { // If it has exactly one, this isn't crit edge
652 // If this block has more than one predecessor, check all of the
653 // predecessors to see if they have multiple successors. If so, then the
654 // block we are analyzing needs an FPRegKill.
655 for (PI = pred_begin(Succ); PI != PE; ++PI) {
656 const BasicBlock *Pred = *PI;
657 succ_const_iterator SI2 = succ_begin(Pred);
658 ++SI2; // There must be at least one successor of this block.
659 if (SI2 != succ_end(Pred))
660 return true; // Yes, we must insert the kill on this edge.
664 // If we got this far, there is no need to insert the kill instruction.
671 // InsertFPRegKills - Insert FP_REG_KILL instructions into basic blocks that
672 // need them. This only occurs due to the floating point stackifier not being
673 // aggressive enough to handle arbitrary global stackification.
675 // Currently we insert an FP_REG_KILL instruction into each block that uses or
676 // defines a floating point virtual register.
678 // When the global register allocators (like linear scan) finally update live
679 // variable analysis, we can keep floating point values in registers across
680 // portions of the CFG that do not involve critical edges. This will be a big
681 // win, but we are waiting on the global allocators before we can do this.
683 // With a bit of work, the floating point stackifier pass can be enhanced to
684 // break critical edges as needed (to make a place to put compensation code),
685 // but this will require some infrastructure improvements as well.
687 void ISel::InsertFPRegKills() {
688 SSARegMap &RegMap = *F->getSSARegMap();
690 for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
691 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
692 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
693 MachineOperand& MO = I->getOperand(i);
694 if (MO.isRegister() && MO.getReg()) {
695 unsigned Reg = MO.getReg();
696 if (MRegisterInfo::isVirtualRegister(Reg))
697 if (RegMap.getRegClass(Reg)->getSize() == 10)
701 // If we haven't found an FP register use or def in this basic block, check
702 // to see if any of our successors has an FP PHI node, which will cause a
703 // copy to be inserted into this block.
704 for (succ_const_iterator SI = succ_begin(BB->getBasicBlock()),
705 E = succ_end(BB->getBasicBlock()); SI != E; ++SI) {
706 MachineBasicBlock *SBB = MBBMap[*SI];
707 for (MachineBasicBlock::iterator I = SBB->begin();
708 I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
709 if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
715 // Okay, this block uses an FP register. If the block has successors (ie,
716 // it's not an unwind/return), insert the FP_REG_KILL instruction.
717 if (BB->getBasicBlock()->getTerminator()->getNumSuccessors() &&
718 RequiresFPRegKill(BB->getBasicBlock())) {
719 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
726 // canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
727 // the conditional branch instruction which is the only user of the cc
728 // instruction. This is the case if the conditional branch is the only user of
729 // the setcc, and if the setcc is in the same basic block as the conditional
730 // branch. We also don't handle long arguments below, so we reject them here as
733 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
734 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
735 if (SCI->hasOneUse() && isa<BranchInst>(SCI->use_back()) &&
736 SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
737 const Type *Ty = SCI->getOperand(0)->getType();
738 if (Ty != Type::LongTy && Ty != Type::ULongTy)
744 // Return a fixed numbering for setcc instructions which does not depend on the
745 // order of the opcodes.
747 static unsigned getSetCCNumber(unsigned Opcode) {
749 default: assert(0 && "Unknown setcc instruction!");
750 case Instruction::SetEQ: return 0;
751 case Instruction::SetNE: return 1;
752 case Instruction::SetLT: return 2;
753 case Instruction::SetGE: return 3;
754 case Instruction::SetGT: return 4;
755 case Instruction::SetLE: return 5;
759 // LLVM -> X86 signed X86 unsigned
760 // ----- ---------- ------------
761 // seteq -> sete sete
762 // setne -> setne setne
763 // setlt -> setl setb
764 // setge -> setge setae
765 // setgt -> setg seta
766 // setle -> setle setbe
768 // sets // Used by comparison with 0 optimization
770 static const unsigned SetCCOpcodeTab[2][8] = {
771 { X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr,
773 { X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr,
774 X86::SETSr, X86::SETNSr },
777 // EmitComparison - This function emits a comparison of the two operands,
778 // returning the extended setcc code to use.
779 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
780 MachineBasicBlock *MBB,
781 MachineBasicBlock::iterator IP) {
782 // The arguments are already supposed to be of the same type.
783 const Type *CompTy = Op0->getType();
784 unsigned Class = getClassB(CompTy);
785 unsigned Op0r = getReg(Op0, MBB, IP);
787 // Special case handling of: cmp R, i
788 if (Class == cByte || Class == cShort || Class == cInt)
789 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
790 uint64_t Op1v = cast<ConstantInt>(CI)->getRawValue();
792 // Mask off any upper bits of the constant, if there are any...
793 Op1v &= (1ULL << (8 << Class)) - 1;
795 // If this is a comparison against zero, emit more efficient code. We
796 // can't handle unsigned comparisons against zero unless they are == or
797 // !=. These should have been strength reduced already anyway.
798 if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
799 static const unsigned TESTTab[] = {
800 X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
802 BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(Op0r).addReg(Op0r);
804 if (OpNum == 2) return 6; // Map jl -> js
805 if (OpNum == 3) return 7; // Map jg -> jns
809 static const unsigned CMPTab[] = {
810 X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
813 BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
817 // Special case handling of comparison against +/- 0.0
818 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
819 if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
820 BuildMI(*MBB, IP, X86::FTST, 1).addReg(Op0r);
821 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
822 BuildMI(*MBB, IP, X86::SAHF, 1);
826 unsigned Op1r = getReg(Op1, MBB, IP);
828 default: assert(0 && "Unknown type class!");
829 // Emit: cmp <var1>, <var2> (do the comparison). We can
830 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
833 BuildMI(*MBB, IP, X86::CMP8rr, 2).addReg(Op0r).addReg(Op1r);
836 BuildMI(*MBB, IP, X86::CMP16rr, 2).addReg(Op0r).addReg(Op1r);
839 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
842 BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
843 BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
844 BuildMI(*MBB, IP, X86::SAHF, 1);
848 if (OpNum < 2) { // seteq, setne
849 unsigned LoTmp = makeAnotherReg(Type::IntTy);
850 unsigned HiTmp = makeAnotherReg(Type::IntTy);
851 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
852 BuildMI(*MBB, IP, X86::XOR32rr, 2, LoTmp).addReg(Op0r).addReg(Op1r);
853 BuildMI(*MBB, IP, X86::XOR32rr, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
854 BuildMI(*MBB, IP, X86::OR32rr, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
855 break; // Allow the sete or setne to be generated from flags set by OR
857 // Emit a sequence of code which compares the high and low parts once
858 // each, then uses a conditional move to handle the overflow case. For
859 // example, a setlt for long would generate code like this:
861 // AL = lo(op1) < lo(op2) // Signedness depends on operands
862 // BL = hi(op1) < hi(op2) // Always unsigned comparison
863 // dest = hi(op1) == hi(op2) ? AL : BL;
866 // FIXME: This would be much better if we had hierarchical register
867 // classes! Until then, hardcode registers so that we can deal with their
868 // aliases (because we don't have conditional byte moves).
870 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
871 BuildMI(*MBB, IP, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
872 BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r+1).addReg(Op1r+1);
873 BuildMI(*MBB, IP, SetCCOpcodeTab[CompTy->isSigned()][OpNum], 0, X86::BL);
874 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::BH);
875 BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, X86::AH);
876 BuildMI(*MBB, IP, X86::CMOVE16rr, 2, X86::BX).addReg(X86::BX)
878 // NOTE: visitSetCondInst knows that the value is dumped into the BL
879 // register at this point for long values...
887 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
888 /// register, then move it to wherever the result should be.
890 void ISel::visitSetCondInst(SetCondInst &I) {
891 if (canFoldSetCCIntoBranch(&I)) return; // Fold this into a branch...
893 unsigned DestReg = getReg(I);
894 MachineBasicBlock::iterator MII = BB->end();
895 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
899 /// emitSetCCOperation - Common code shared between visitSetCondInst and
900 /// constant expression support.
902 void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
903 MachineBasicBlock::iterator IP,
904 Value *Op0, Value *Op1, unsigned Opcode,
905 unsigned TargetReg) {
906 unsigned OpNum = getSetCCNumber(Opcode);
907 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
909 const Type *CompTy = Op0->getType();
910 unsigned CompClass = getClassB(CompTy);
911 bool isSigned = CompTy->isSigned() && CompClass != cFP;
913 if (CompClass != cLong || OpNum < 2) {
914 // Handle normal comparisons with a setcc instruction...
915 BuildMI(*MBB, IP, SetCCOpcodeTab[isSigned][OpNum], 0, TargetReg);
917 // Handle long comparisons by copying the value which is already in BL into
918 // the register we want...
919 BuildMI(*MBB, IP, X86::MOV8rr, 1, TargetReg).addReg(X86::BL);
926 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
927 /// operand, in the specified target register.
929 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
930 bool isUnsigned = VR.Ty->isUnsigned();
932 // Make sure we have the register number for this value...
933 unsigned Reg = VR.Val ? getReg(VR.Val) : VR.Reg;
935 switch (getClassB(VR.Ty)) {
937 // Extend value into target register (8->32)
939 BuildMI(BB, X86::MOVZX32rr8, 1, targetReg).addReg(Reg);
941 BuildMI(BB, X86::MOVSX32rr8, 1, targetReg).addReg(Reg);
944 // Extend value into target register (16->32)
946 BuildMI(BB, X86::MOVZX32rr16, 1, targetReg).addReg(Reg);
948 BuildMI(BB, X86::MOVSX32rr16, 1, targetReg).addReg(Reg);
951 // Move value into target register (32->32)
952 BuildMI(BB, X86::MOV32rr, 1, targetReg).addReg(Reg);
955 assert(0 && "Unpromotable operand class in promote32");
959 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
960 /// we have the following possibilities:
962 /// ret void: No return value, simply emit a 'ret' instruction
963 /// ret sbyte, ubyte : Extend value into EAX and return
964 /// ret short, ushort: Extend value into EAX and return
965 /// ret int, uint : Move value into EAX and return
966 /// ret pointer : Move value into EAX and return
967 /// ret long, ulong : Move value into EAX/EDX and return
968 /// ret float/double : Top of FP stack
970 void ISel::visitReturnInst(ReturnInst &I) {
971 if (I.getNumOperands() == 0) {
972 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
976 Value *RetVal = I.getOperand(0);
977 unsigned RetReg = getReg(RetVal);
978 switch (getClassB(RetVal->getType())) {
979 case cByte: // integral return values: extend or move into EAX and return
982 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
983 // Declare that EAX is live on exit
984 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
986 case cFP: // Floats & Doubles: Return in ST(0)
987 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
988 // Declare that top-of-stack is live on exit
989 BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
992 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
993 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RetReg+1);
994 // Declare that EAX & EDX are live on exit
995 BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX)
1001 // Emit a 'ret' instruction
1002 BuildMI(BB, X86::RET, 0);
1005 // getBlockAfter - Return the basic block which occurs lexically after the
1007 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1008 Function::iterator I = BB; ++I; // Get iterator to next block
1009 return I != BB->getParent()->end() ? &*I : 0;
1012 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1013 /// that since code layout is frozen at this point, that if we are trying to
1014 /// jump to a block that is the immediate successor of the current block, we can
1015 /// just make a fall-through (but we don't currently).
1017 void ISel::visitBranchInst(BranchInst &BI) {
1018 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1020 if (!BI.isConditional()) { // Unconditional branch?
1021 if (BI.getSuccessor(0) != NextBB)
1022 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1026 // See if we can fold the setcc into the branch itself...
1027 SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
1029 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1030 // computed some other way...
1031 unsigned condReg = getReg(BI.getCondition());
1032 BuildMI(BB, X86::CMP8ri, 2).addReg(condReg).addImm(0);
1033 if (BI.getSuccessor(1) == NextBB) {
1034 if (BI.getSuccessor(0) != NextBB)
1035 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
1037 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
1039 if (BI.getSuccessor(0) != NextBB)
1040 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
1045 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1046 MachineBasicBlock::iterator MII = BB->end();
1047 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1049 const Type *CompTy = SCI->getOperand(0)->getType();
1050 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1053 // LLVM -> X86 signed X86 unsigned
1054 // ----- ---------- ------------
1062 // js // Used by comparison with 0 optimization
1065 static const unsigned OpcodeTab[2][8] = {
1066 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE, 0, 0 },
1067 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
1068 X86::JS, X86::JNS },
1071 if (BI.getSuccessor(0) != NextBB) {
1072 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
1073 if (BI.getSuccessor(1) != NextBB)
1074 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
1076 // Change to the inverse condition...
1077 if (BI.getSuccessor(1) != NextBB) {
1079 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
1085 /// doCall - This emits an abstract call instruction, setting up the arguments
1086 /// and the return value as appropriate. For the actual function call itself,
1087 /// it inserts the specified CallMI instruction into the stream.
1089 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1090 const std::vector<ValueRecord> &Args) {
1092 // Count how many bytes are to be pushed on the stack...
1093 unsigned NumBytes = 0;
1095 if (!Args.empty()) {
1096 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1097 switch (getClassB(Args[i].Ty)) {
1098 case cByte: case cShort: case cInt:
1099 NumBytes += 4; break;
1101 NumBytes += 8; break;
1103 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1105 default: assert(0 && "Unknown class!");
1108 // Adjust the stack pointer for the new arguments...
1109 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1111 // Arguments go on the stack in reverse order, as specified by the ABI.
1112 unsigned ArgOffset = 0;
1113 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1115 switch (getClassB(Args[i].Ty)) {
1118 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1119 // Zero/Sign extend constant, then stuff into memory.
1120 ConstantInt *Val = cast<ConstantInt>(Args[i].Val);
1121 Val = cast<ConstantInt>(ConstantExpr::getCast(Val, Type::IntTy));
1122 addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
1123 .addImm(Val->getRawValue() & 0xFFFFFFFF);
1125 // Promote arg to 32 bits wide into a temporary register...
1126 ArgReg = makeAnotherReg(Type::UIntTy);
1127 promote32(ArgReg, Args[i]);
1128 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1129 X86::ESP, ArgOffset).addReg(ArgReg);
1133 if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
1134 unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
1135 addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
1136 X86::ESP, ArgOffset).addImm(Val);
1138 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1139 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1140 X86::ESP, ArgOffset).addReg(ArgReg);
1144 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1145 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1146 X86::ESP, ArgOffset).addReg(ArgReg);
1147 addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
1148 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
1149 ArgOffset += 4; // 8 byte entry, not 4.
1153 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1154 if (Args[i].Ty == Type::FloatTy) {
1155 addRegOffset(BuildMI(BB, X86::FST32m, 5),
1156 X86::ESP, ArgOffset).addReg(ArgReg);
1158 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1159 addRegOffset(BuildMI(BB, X86::FST64m, 5),
1160 X86::ESP, ArgOffset).addReg(ArgReg);
1161 ArgOffset += 4; // 8 byte entry, not 4.
1165 default: assert(0 && "Unknown class!");
1170 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(0);
1173 BB->push_back(CallMI);
1175 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addImm(NumBytes);
1177 // If there is a return value, scavenge the result from the location the call
1180 if (Ret.Ty != Type::VoidTy) {
1181 unsigned DestClass = getClassB(Ret.Ty);
1182 switch (DestClass) {
1186 // Integral results are in %eax, or the appropriate portion
1188 static const unsigned regRegMove[] = {
1189 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr
1191 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
1192 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
1195 case cFP: // Floating-point return values live in %ST(0)
1196 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
1198 case cLong: // Long values are left in EDX:EAX
1199 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg).addReg(X86::EAX);
1200 BuildMI(BB, X86::MOV32rr, 1, Ret.Reg+1).addReg(X86::EDX);
1202 default: assert(0 && "Unknown class!");
1208 /// visitCallInst - Push args on stack and do a procedure call instruction.
1209 void ISel::visitCallInst(CallInst &CI) {
1210 MachineInstr *TheCall;
1211 if (Function *F = CI.getCalledFunction()) {
1212 // Is it an intrinsic function call?
1213 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1214 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1218 // Emit a CALL instruction with PC-relative displacement.
1219 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
1220 } else { // Emit an indirect call...
1221 unsigned Reg = getReg(CI.getCalledValue());
1222 TheCall = BuildMI(X86::CALL32r, 1).addReg(Reg);
1225 std::vector<ValueRecord> Args;
1226 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1227 Args.push_back(ValueRecord(CI.getOperand(i)));
1229 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1230 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1234 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1235 /// function, lowering any calls to unknown intrinsic functions into the
1236 /// equivalent LLVM code.
1238 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1239 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1240 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1241 if (CallInst *CI = dyn_cast<CallInst>(I++))
1242 if (Function *F = CI->getCalledFunction())
1243 switch (F->getIntrinsicID()) {
1244 case Intrinsic::not_intrinsic:
1245 case Intrinsic::vastart:
1246 case Intrinsic::vacopy:
1247 case Intrinsic::vaend:
1248 case Intrinsic::returnaddress:
1249 case Intrinsic::frameaddress:
1250 case Intrinsic::memcpy:
1251 case Intrinsic::memset:
1252 // We directly implement these intrinsics
1255 // All other intrinsic calls we must lower.
1256 Instruction *Before = CI->getPrev();
1257 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1258 if (Before) { // Move iterator to instruction after call
1267 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1268 unsigned TmpReg1, TmpReg2;
1270 case Intrinsic::vastart:
1271 // Get the address of the first vararg value...
1272 TmpReg1 = getReg(CI);
1273 addFrameReference(BuildMI(BB, X86::LEA32r, 5, TmpReg1), VarArgsFrameIndex);
1276 case Intrinsic::vacopy:
1277 TmpReg1 = getReg(CI);
1278 TmpReg2 = getReg(CI.getOperand(1));
1279 BuildMI(BB, X86::MOV32rr, 1, TmpReg1).addReg(TmpReg2);
1281 case Intrinsic::vaend: return; // Noop on X86
1283 case Intrinsic::returnaddress:
1284 case Intrinsic::frameaddress:
1285 TmpReg1 = getReg(CI);
1286 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1287 if (ID == Intrinsic::returnaddress) {
1288 // Just load the return address
1289 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
1290 ReturnAddressIndex);
1292 addFrameReference(BuildMI(BB, X86::LEA32r, 4, TmpReg1),
1293 ReturnAddressIndex, -4);
1296 // Values other than zero are not implemented yet.
1297 BuildMI(BB, X86::MOV32ri, 1, TmpReg1).addImm(0);
1301 case Intrinsic::memcpy: {
1302 assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
1304 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1305 Align = AlignC->getRawValue();
1306 if (Align == 0) Align = 1;
1309 // Turn the byte code into # iterations
1312 switch (Align & 3) {
1313 case 2: // WORD aligned
1314 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1315 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1317 CountReg = makeAnotherReg(Type::IntTy);
1318 unsigned ByteReg = getReg(CI.getOperand(3));
1319 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1321 Opcode = X86::REP_MOVSW;
1323 case 0: // DWORD aligned
1324 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1325 CountReg = getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1327 CountReg = makeAnotherReg(Type::IntTy);
1328 unsigned ByteReg = getReg(CI.getOperand(3));
1329 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1331 Opcode = X86::REP_MOVSD;
1333 default: // BYTE aligned
1334 CountReg = getReg(CI.getOperand(3));
1335 Opcode = X86::REP_MOVSB;
1339 // No matter what the alignment is, we put the source in ESI, the
1340 // destination in EDI, and the count in ECX.
1341 TmpReg1 = getReg(CI.getOperand(1));
1342 TmpReg2 = getReg(CI.getOperand(2));
1343 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1344 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1345 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
1346 BuildMI(BB, Opcode, 0);
1349 case Intrinsic::memset: {
1350 assert(CI.getNumOperands() == 5 && "Illegal llvm.memset call!");
1352 if (ConstantInt *AlignC = dyn_cast<ConstantInt>(CI.getOperand(4))) {
1353 Align = AlignC->getRawValue();
1354 if (Align == 0) Align = 1;
1357 // Turn the byte code into # iterations
1360 if (ConstantInt *ValC = dyn_cast<ConstantInt>(CI.getOperand(2))) {
1361 unsigned Val = ValC->getRawValue() & 255;
1363 // If the value is a constant, then we can potentially use larger copies.
1364 switch (Align & 3) {
1365 case 2: // WORD aligned
1366 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1367 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/2));
1369 CountReg = makeAnotherReg(Type::IntTy);
1370 unsigned ByteReg = getReg(CI.getOperand(3));
1371 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
1373 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
1374 Opcode = X86::REP_STOSW;
1376 case 0: // DWORD aligned
1377 if (ConstantInt *I = dyn_cast<ConstantInt>(CI.getOperand(3))) {
1378 CountReg =getReg(ConstantUInt::get(Type::UIntTy, I->getRawValue()/4));
1380 CountReg = makeAnotherReg(Type::IntTy);
1381 unsigned ByteReg = getReg(CI.getOperand(3));
1382 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
1384 Val = (Val << 8) | Val;
1385 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
1386 Opcode = X86::REP_STOSD;
1388 default: // BYTE aligned
1389 CountReg = getReg(CI.getOperand(3));
1390 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
1391 Opcode = X86::REP_STOSB;
1395 // If it's not a constant value we are storing, just fall back. We could
1396 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
1397 unsigned ValReg = getReg(CI.getOperand(2));
1398 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
1399 CountReg = getReg(CI.getOperand(3));
1400 Opcode = X86::REP_STOSB;
1403 // No matter what the alignment is, we put the source in ESI, the
1404 // destination in EDI, and the count in ECX.
1405 TmpReg1 = getReg(CI.getOperand(1));
1406 //TmpReg2 = getReg(CI.getOperand(2));
1407 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
1408 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
1409 BuildMI(BB, Opcode, 0);
1413 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1417 static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
1418 if (LI.getParent() != User.getParent())
1420 BasicBlock::iterator It = &LI;
1421 // Check all of the instructions between the load and the user. We should
1422 // really use alias analysis here, but for now we just do something simple.
1423 for (++It; It != BasicBlock::iterator(&User); ++It) {
1424 switch (It->getOpcode()) {
1425 case Instruction::Malloc:
1426 case Instruction::Free:
1427 case Instruction::Store:
1428 case Instruction::Call:
1429 case Instruction::Invoke:
1437 /// visitSimpleBinary - Implement simple binary operators for integral types...
1438 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1441 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1442 unsigned DestReg = getReg(B);
1443 MachineBasicBlock::iterator MI = BB->end();
1444 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1446 // Special case: op Reg, load [mem]
1447 if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
1448 if (!B.swapOperands())
1449 std::swap(Op0, Op1); // Make sure any loads are in the RHS.
1451 unsigned Class = getClassB(B.getType());
1452 if (isa<LoadInst>(Op1) && Class < cFP &&
1453 isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
1455 static const unsigned OpcodeTab[][3] = {
1456 // Arithmetic operators
1457 { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm }, // ADD
1458 { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm }, // SUB
1460 // Bitwise operators
1461 { X86::AND8rm, X86::AND16rm, X86::AND32rm }, // AND
1462 { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm }, // OR
1463 { X86::XOR8rm, X86::XOR16rm, X86::XOR32rm }, // XOR
1466 assert(Class < cFP && "General code handles 64-bit integer types!");
1467 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1469 unsigned BaseReg, Scale, IndexReg, Disp;
1470 getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), BaseReg,
1471 Scale, IndexReg, Disp);
1473 unsigned Op0r = getReg(Op0);
1474 addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r),
1475 BaseReg, Scale, IndexReg, Disp);
1479 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1482 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1483 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1486 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1487 /// and constant expression support.
1489 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1490 MachineBasicBlock::iterator IP,
1491 Value *Op0, Value *Op1,
1492 unsigned OperatorClass, unsigned DestReg) {
1493 unsigned Class = getClassB(Op0->getType());
1495 // sub 0, X -> neg X
1496 if (OperatorClass == 1 && Class != cLong)
1497 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
1498 if (CI->isNullValue()) {
1499 unsigned op1Reg = getReg(Op1, MBB, IP);
1501 default: assert(0 && "Unknown class for this function!");
1503 BuildMI(*MBB, IP, X86::NEG8r, 1, DestReg).addReg(op1Reg);
1506 BuildMI(*MBB, IP, X86::NEG16r, 1, DestReg).addReg(op1Reg);
1509 BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg).addReg(op1Reg);
1513 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1514 if (CFP->isExactlyValue(-0.0)) {
1516 unsigned op1Reg = getReg(Op1, MBB, IP);
1517 BuildMI(*MBB, IP, X86::FCHS, 1, DestReg).addReg(op1Reg);
1521 // Special case: op Reg, <const>
1522 if (Class != cLong && isa<ConstantInt>(Op1)) {
1523 ConstantInt *Op1C = cast<ConstantInt>(Op1);
1524 unsigned Op0r = getReg(Op0, MBB, IP);
1526 // xor X, -1 -> not X
1527 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1528 static unsigned const NOTTab[] = { X86::NOT8r, X86::NOT16r, X86::NOT32r };
1529 BuildMI(*MBB, IP, NOTTab[Class], 1, DestReg).addReg(Op0r);
1533 // add X, -1 -> dec X
1534 if (OperatorClass == 0 && Op1C->isAllOnesValue()) {
1535 static unsigned const DECTab[] = { X86::DEC8r, X86::DEC16r, X86::DEC32r };
1536 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1540 // add X, 1 -> inc X
1541 if (OperatorClass == 0 && Op1C->equalsInt(1)) {
1542 static unsigned const DECTab[] = { X86::INC8r, X86::INC16r, X86::INC32r };
1543 BuildMI(*MBB, IP, DECTab[Class], 1, DestReg).addReg(Op0r);
1547 static const unsigned OpcodeTab[][3] = {
1548 // Arithmetic operators
1549 { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri }, // ADD
1550 { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri }, // SUB
1552 // Bitwise operators
1553 { X86::AND8ri, X86::AND16ri, X86::AND32ri }, // AND
1554 { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri }, // OR
1555 { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri }, // XOR
1558 assert(Class < cFP && "General code handles 64-bit integer types!");
1559 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1562 uint64_t Op1v = cast<ConstantInt>(Op1C)->getRawValue();
1563 BuildMI(*MBB, IP, Opcode, 5, DestReg).addReg(Op0r).addImm(Op1v);
1567 // Finally, handle the general case now.
1568 static const unsigned OpcodeTab[][4] = {
1569 // Arithmetic operators
1570 { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, X86::FpADD }, // ADD
1571 { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::FpSUB }, // SUB
1573 // Bitwise operators
1574 { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0 }, // AND
1575 { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0 }, // OR
1576 { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0 }, // XOR
1579 bool isLong = false;
1580 if (Class == cLong) {
1582 Class = cInt; // Bottom 32 bits are handled just like ints
1585 unsigned Opcode = OpcodeTab[OperatorClass][Class];
1586 assert(Opcode && "Floating point arguments to logical inst?");
1587 unsigned Op0r = getReg(Op0, MBB, IP);
1588 unsigned Op1r = getReg(Op1, MBB, IP);
1589 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1591 if (isLong) { // Handle the upper 32 bits of long values...
1592 static const unsigned TopTab[] = {
1593 X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
1595 BuildMI(*MBB, IP, TopTab[OperatorClass], 2,
1596 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1600 /// doMultiply - Emit appropriate instructions to multiply together the
1601 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1602 /// result should be given as DestTy.
1604 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1605 unsigned DestReg, const Type *DestTy,
1606 unsigned op0Reg, unsigned op1Reg) {
1607 unsigned Class = getClass(DestTy);
1609 case cFP: // Floating point multiply
1610 BuildMI(*MBB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1614 BuildMI(*MBB, MBBI, Class == cInt ? X86::IMUL32rr:X86::IMUL16rr, 2, DestReg)
1615 .addReg(op0Reg).addReg(op1Reg);
1618 // Must use the MUL instruction, which forces use of AL...
1619 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, X86::AL).addReg(op0Reg);
1620 BuildMI(*MBB, MBBI, X86::MUL8r, 1).addReg(op1Reg);
1621 BuildMI(*MBB, MBBI, X86::MOV8rr, 1, DestReg).addReg(X86::AL);
1624 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
1628 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1629 // returns zero when the input is not exactly a power of two.
1630 static unsigned ExactLog2(unsigned Val) {
1631 if (Val == 0) return 0;
1634 if (Val & 1) return 0;
1641 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1642 MachineBasicBlock::iterator IP,
1643 unsigned DestReg, const Type *DestTy,
1644 unsigned op0Reg, unsigned ConstRHS) {
1645 unsigned Class = getClass(DestTy);
1647 // If the element size is exactly a power of 2, use a shift to get it.
1648 if (unsigned Shift = ExactLog2(ConstRHS)) {
1650 default: assert(0 && "Unknown class for this function!");
1652 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1655 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1658 BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
1663 if (Class == cShort) {
1664 BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
1666 } else if (Class == cInt) {
1667 BuildMI(*MBB, IP, X86::IMUL32rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
1671 // Most general case, emit a normal multiply...
1672 static const unsigned MOVriTab[] = {
1673 X86::MOV8ri, X86::MOV16ri, X86::MOV32ri
1676 unsigned TmpReg = makeAnotherReg(DestTy);
1677 BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
1679 // Emit a MUL to multiply the register holding the index by
1680 // elementSize, putting the result in OffsetReg.
1681 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
1684 /// visitMul - Multiplies are not simple binary operators because they must deal
1685 /// with the EAX register explicitly.
1687 void ISel::visitMul(BinaryOperator &I) {
1688 unsigned Op0Reg = getReg(I.getOperand(0));
1689 unsigned DestReg = getReg(I);
1691 // Simple scalar multiply?
1692 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
1693 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1))) {
1694 unsigned Val = (unsigned)CI->getRawValue(); // Cannot be 64-bit constant
1695 MachineBasicBlock::iterator MBBI = BB->end();
1696 doMultiplyConst(BB, MBBI, DestReg, I.getType(), Op0Reg, Val);
1698 unsigned Op1Reg = getReg(I.getOperand(1));
1699 MachineBasicBlock::iterator MBBI = BB->end();
1700 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
1703 unsigned Op1Reg = getReg(I.getOperand(1));
1705 // Long value. We have to do things the hard way...
1706 // Multiply the two low parts... capturing carry into EDX
1707 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
1708 BuildMI(BB, X86::MUL32r, 1).addReg(Op1Reg); // AL*BL
1710 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1711 BuildMI(BB, X86::MOV32rr, 1, DestReg).addReg(X86::EAX); // AL*BL
1712 BuildMI(BB, X86::MOV32rr, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
1714 MachineBasicBlock::iterator MBBI = BB->end();
1715 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
1716 BuildMI(*BB, MBBI, X86::IMUL32rr,2,AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1718 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1719 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AH*BL+(AL*BL >> 32)
1720 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1723 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1724 BuildMI(*BB, MBBI, X86::IMUL32rr,2,ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1726 BuildMI(*BB, MBBI, X86::ADD32rr, 2, // AL*BH + AH*BL + (AL*BL >> 32)
1727 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1732 /// visitDivRem - Handle division and remainder instructions... these
1733 /// instruction both require the same instructions to be generated, they just
1734 /// select the result from a different register. Note that both of these
1735 /// instructions work differently for signed and unsigned operands.
1737 void ISel::visitDivRem(BinaryOperator &I) {
1738 unsigned Op0Reg = getReg(I.getOperand(0));
1739 unsigned Op1Reg = getReg(I.getOperand(1));
1740 unsigned ResultReg = getReg(I);
1742 MachineBasicBlock::iterator IP = BB->end();
1743 emitDivRemOperation(BB, IP, Op0Reg, Op1Reg, I.getOpcode() == Instruction::Div,
1744 I.getType(), ResultReg);
1747 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
1748 MachineBasicBlock::iterator IP,
1749 unsigned Op0Reg, unsigned Op1Reg, bool isDiv,
1750 const Type *Ty, unsigned ResultReg) {
1751 unsigned Class = getClass(Ty);
1753 case cFP: // Floating point divide
1755 BuildMI(*BB, IP, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1756 } else { // Floating point remainder...
1757 MachineInstr *TheCall =
1758 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1759 std::vector<ValueRecord> Args;
1760 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1761 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1762 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1766 static const char *FnName[] =
1767 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1769 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
1770 MachineInstr *TheCall =
1771 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1773 std::vector<ValueRecord> Args;
1774 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1775 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1776 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1779 case cByte: case cShort: case cInt:
1780 break; // Small integrals, handled below...
1781 default: assert(0 && "Unknown class!");
1784 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
1785 static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
1786 static const unsigned SarOpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
1787 static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
1788 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1790 static const unsigned DivOpcode[][4] = {
1791 { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 }, // Unsigned division
1792 { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 }, // Signed division
1795 bool isSigned = Ty->isSigned();
1796 unsigned Reg = Regs[Class];
1797 unsigned ExtReg = ExtRegs[Class];
1799 // Put the first operand into one of the A registers...
1800 BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1803 // Emit a sign extension instruction...
1804 unsigned ShiftResult = makeAnotherReg(Ty);
1805 BuildMI(*BB, IP, SarOpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
1806 BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
1808 // If unsigned, emit a zeroing instruction... (reg = 0)
1809 BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
1812 // Emit the appropriate divide or remainder instruction...
1813 BuildMI(*BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1815 // Figure out which register we want to pick the result out of...
1816 unsigned DestReg = isDiv ? Reg : ExtReg;
1818 // Put the result into the destination register...
1819 BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1823 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1824 /// for constant immediate shift values, and for constant immediate
1825 /// shift values equal to 1. Even the general case is sort of special,
1826 /// because the shift amount has to be in CL, not just any old register.
1828 void ISel::visitShiftInst(ShiftInst &I) {
1829 MachineBasicBlock::iterator IP = BB->end ();
1830 emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
1831 I.getOpcode () == Instruction::Shl, I.getType (),
1835 /// emitShiftOperation - Common code shared between visitShiftInst and
1836 /// constant expression support.
1837 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
1838 MachineBasicBlock::iterator IP,
1839 Value *Op, Value *ShiftAmount, bool isLeftShift,
1840 const Type *ResultTy, unsigned DestReg) {
1841 unsigned SrcReg = getReg (Op, MBB, IP);
1842 bool isSigned = ResultTy->isSigned ();
1843 unsigned Class = getClass (ResultTy);
1845 static const unsigned ConstantOperand[][4] = {
1846 { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 }, // SHR
1847 { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 }, // SAR
1848 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SHL
1849 { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 }, // SAL = SHL
1852 static const unsigned NonConstantOperand[][4] = {
1853 { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL }, // SHR
1854 { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL }, // SAR
1855 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SHL
1856 { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL }, // SAL = SHL
1859 // Longs, as usual, are handled specially...
1860 if (Class == cLong) {
1861 // If we have a constant shift, we can generate much more efficient code
1862 // than otherwise...
1864 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
1865 unsigned Amount = CUI->getValue();
1867 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1869 BuildMI(*MBB, IP, Opc[3], 3,
1870 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
1871 BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
1873 BuildMI(*MBB, IP, Opc[3], 3,
1874 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addImm(Amount);
1875 BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
1877 } else { // Shifting more than 32 bits
1880 BuildMI(*MBB, IP, X86::SHL32ri, 2,
1881 DestReg + 1).addReg(SrcReg).addImm(Amount);
1882 BuildMI(*MBB, IP, X86::MOV32ri, 1,
1885 unsigned Opcode = isSigned ? X86::SAR32ri : X86::SHR32ri;
1886 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(SrcReg+1).addImm(Amount);
1887 BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
1891 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1893 if (!isLeftShift && isSigned) {
1894 // If this is a SHR of a Long, then we need to do funny sign extension
1895 // stuff. TmpReg gets the value to use as the high-part if we are
1896 // shifting more than 32 bits.
1897 BuildMI(*MBB, IP, X86::SAR32ri, 2, TmpReg).addReg(SrcReg).addImm(31);
1899 // Other shifts use a fixed zero value if the shift is more than 32
1901 BuildMI(*MBB, IP, X86::MOV32ri, 1, TmpReg).addImm(0);
1904 // Initialize CL with the shift amount...
1905 unsigned ShiftAmountReg = getReg(ShiftAmount, MBB, IP);
1906 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
1908 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1909 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
1911 // TmpReg2 = shld inHi, inLo
1912 BuildMI(*MBB, IP, X86::SHLD32rrCL,2,TmpReg2).addReg(SrcReg+1)
1914 // TmpReg3 = shl inLo, CL
1915 BuildMI(*MBB, IP, X86::SHL32rCL, 1, TmpReg3).addReg(SrcReg);
1917 // Set the flags to indicate whether the shift was by more than 32 bits.
1918 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
1920 // DestHi = (>32) ? TmpReg3 : TmpReg2;
1921 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
1922 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
1923 // DestLo = (>32) ? TmpReg : TmpReg3;
1924 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
1925 DestReg).addReg(TmpReg3).addReg(TmpReg);
1927 // TmpReg2 = shrd inLo, inHi
1928 BuildMI(*MBB, IP, X86::SHRD32rrCL,2,TmpReg2).addReg(SrcReg)
1930 // TmpReg3 = s[ah]r inHi, CL
1931 BuildMI(*MBB, IP, isSigned ? X86::SAR32rCL : X86::SHR32rCL, 1, TmpReg3)
1934 // Set the flags to indicate whether the shift was by more than 32 bits.
1935 BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
1937 // DestLo = (>32) ? TmpReg3 : TmpReg2;
1938 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
1939 DestReg).addReg(TmpReg2).addReg(TmpReg3);
1941 // DestHi = (>32) ? TmpReg : TmpReg3;
1942 BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
1943 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
1949 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
1950 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1951 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
1953 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1954 BuildMI(*MBB, IP, Opc[Class], 2,
1955 DestReg).addReg(SrcReg).addImm(CUI->getValue());
1956 } else { // The shift amount is non-constant.
1957 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
1958 BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
1960 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1961 BuildMI(*MBB, IP, Opc[Class], 1, DestReg).addReg(SrcReg);
1966 void ISel::getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
1967 unsigned &IndexReg, unsigned &Disp) {
1968 BaseReg = 0; Scale = 1; IndexReg = 0; Disp = 0;
1969 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
1970 if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
1971 BaseReg, Scale, IndexReg, Disp))
1973 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
1974 if (CE->getOpcode() == Instruction::GetElementPtr)
1975 if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
1976 BaseReg, Scale, IndexReg, Disp))
1980 // If it's not foldable, reset addr mode.
1981 BaseReg = getReg(Addr);
1982 Scale = 1; IndexReg = 0; Disp = 0;
1986 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
1987 /// instruction. The load and store instructions are the only place where we
1988 /// need to worry about the memory layout of the target machine.
1990 void ISel::visitLoadInst(LoadInst &I) {
1991 // Check to see if this load instruction is going to be folded into a binary
1992 // instruction, like add. If so, we don't want to emit it. Wouldn't a real
1993 // pattern matching instruction selector be nice?
1994 if (I.hasOneUse() && getClassB(I.getType()) < cFP) {
1995 Instruction *User = cast<Instruction>(I.use_back());
1996 switch (User->getOpcode()) {
1997 default: User = 0; break;
1998 case Instruction::Add:
1999 case Instruction::Sub:
2000 case Instruction::And:
2001 case Instruction::Or:
2002 case Instruction::Xor:
2007 // Okay, we found a user. If the load is the first operand and there is
2008 // no second operand load, reverse the operand ordering. Note that this
2009 // can fail for a subtract (ie, no change will be made).
2010 if (!isa<LoadInst>(User->getOperand(1)))
2011 cast<BinaryOperator>(User)->swapOperands();
2013 // Okay, now that everything is set up, if this load is used by the second
2014 // operand, and if there are no instructions that invalidate the load
2015 // before the binary operator, eliminate the load.
2016 if (User->getOperand(1) == &I &&
2017 isSafeToFoldLoadIntoInstruction(I, *User))
2018 return; // Eliminate the load!
2022 unsigned DestReg = getReg(I);
2023 unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
2024 getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
2026 unsigned Class = getClassB(I.getType());
2027 if (Class == cLong) {
2028 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
2029 BaseReg, Scale, IndexReg, Disp);
2030 addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
2031 BaseReg, Scale, IndexReg, Disp+4);
2035 static const unsigned Opcodes[] = {
2036 X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m
2038 unsigned Opcode = Opcodes[Class];
2039 if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
2040 addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
2041 BaseReg, Scale, IndexReg, Disp);
2044 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
2047 void ISel::visitStoreInst(StoreInst &I) {
2048 unsigned BaseReg, Scale, IndexReg, Disp;
2049 getAddressingMode(I.getOperand(1), BaseReg, Scale, IndexReg, Disp);
2051 const Type *ValTy = I.getOperand(0)->getType();
2052 unsigned Class = getClassB(ValTy);
2054 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
2055 uint64_t Val = CI->getRawValue();
2056 if (Class == cLong) {
2057 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2058 BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
2059 addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
2060 BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
2062 static const unsigned Opcodes[] = {
2063 X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
2065 unsigned Opcode = Opcodes[Class];
2066 addFullAddress(BuildMI(BB, Opcode, 5),
2067 BaseReg, Scale, IndexReg, Disp).addImm(Val);
2069 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
2070 addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
2071 BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
2073 if (Class == cLong) {
2074 unsigned ValReg = getReg(I.getOperand(0));
2075 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2076 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2077 addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
2078 BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
2080 unsigned ValReg = getReg(I.getOperand(0));
2081 static const unsigned Opcodes[] = {
2082 X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
2084 unsigned Opcode = Opcodes[Class];
2085 if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
2086 addFullAddress(BuildMI(BB, Opcode, 1+4),
2087 BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
2093 /// visitCastInst - Here we have various kinds of copying with or without sign
2094 /// extension going on.
2096 void ISel::visitCastInst(CastInst &CI) {
2097 Value *Op = CI.getOperand(0);
2098 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2099 // of the case are GEP instructions, then the cast does not need to be
2100 // generated explicitly, it will be folded into the GEP.
2101 if (CI.getType() == Type::LongTy &&
2102 (Op->getType() == Type::IntTy || Op->getType() == Type::UIntTy)) {
2103 bool AllUsesAreGEPs = true;
2104 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2105 if (!isa<GetElementPtrInst>(*I)) {
2106 AllUsesAreGEPs = false;
2110 // No need to codegen this cast if all users are getelementptr instrs...
2111 if (AllUsesAreGEPs) return;
2114 unsigned DestReg = getReg(CI);
2115 MachineBasicBlock::iterator MI = BB->end();
2116 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2119 /// emitCastOperation - Common code shared between visitCastInst and constant
2120 /// expression cast support.
2122 void ISel::emitCastOperation(MachineBasicBlock *BB,
2123 MachineBasicBlock::iterator IP,
2124 Value *Src, const Type *DestTy,
2126 unsigned SrcReg = getReg(Src, BB, IP);
2127 const Type *SrcTy = Src->getType();
2128 unsigned SrcClass = getClassB(SrcTy);
2129 unsigned DestClass = getClassB(DestTy);
2131 // Implement casts to bool by using compare on the operand followed by set if
2132 // not zero on the result.
2133 if (DestTy == Type::BoolTy) {
2136 BuildMI(*BB, IP, X86::TEST8rr, 2).addReg(SrcReg).addReg(SrcReg);
2139 BuildMI(*BB, IP, X86::TEST16rr, 2).addReg(SrcReg).addReg(SrcReg);
2142 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg).addReg(SrcReg);
2145 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2146 BuildMI(*BB, IP, X86::OR32rr, 2, TmpReg).addReg(SrcReg).addReg(SrcReg+1);
2150 BuildMI(*BB, IP, X86::FTST, 1).addReg(SrcReg);
2151 BuildMI(*BB, IP, X86::FNSTSW8r, 0);
2152 BuildMI(*BB, IP, X86::SAHF, 1);
2156 // If the zero flag is not set, then the value is true, set the byte to
2158 BuildMI(*BB, IP, X86::SETNEr, 1, DestReg);
2162 static const unsigned RegRegMove[] = {
2163 X86::MOV8rr, X86::MOV16rr, X86::MOV32rr, X86::FpMOV, X86::MOV32rr
2166 // Implement casts between values of the same type class (as determined by
2167 // getClass) by using a register-to-register move.
2168 if (SrcClass == DestClass) {
2169 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
2170 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
2171 } else if (SrcClass == cFP) {
2172 if (SrcTy == Type::FloatTy) { // double -> float
2173 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2174 BuildMI(*BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
2175 } else { // float -> double
2176 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2177 "Unknown cFP member!");
2178 // Truncate from double to float by storing to memory as short, then
2180 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
2181 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
2182 addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
2183 addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
2185 } else if (SrcClass == cLong) {
2186 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2187 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg+1);
2189 assert(0 && "Cannot handle this type of cast instruction!");
2195 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2196 // or zero extension, depending on whether the source type was signed.
2197 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2198 SrcClass < DestClass) {
2199 bool isLong = DestClass == cLong;
2200 if (isLong) DestClass = cInt;
2202 static const unsigned Opc[][4] = {
2203 { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
2204 { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr } // u
2207 bool isUnsigned = SrcTy->isUnsigned();
2208 BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
2209 DestReg).addReg(SrcReg);
2211 if (isLong) { // Handle upper 32 bits as appropriate...
2212 if (isUnsigned) // Zero out top bits...
2213 BuildMI(*BB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
2214 else // Sign extend bottom half...
2215 BuildMI(*BB, IP, X86::SAR32ri, 2, DestReg+1).addReg(DestReg).addImm(31);
2220 // Special case long -> int ...
2221 if (SrcClass == cLong && DestClass == cInt) {
2222 BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
2226 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
2227 // move out of AX or AL.
2228 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2229 && SrcClass > DestClass) {
2230 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
2231 BuildMI(*BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
2232 BuildMI(*BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
2236 // Handle casts from integer to floating point now...
2237 if (DestClass == cFP) {
2238 // Promote the integer to a type supported by FLD. We do this because there
2239 // are no unsigned FLD instructions, so we must promote an unsigned value to
2240 // a larger signed value, then use FLD on the larger value.
2242 const Type *PromoteType = 0;
2243 unsigned PromoteOpcode;
2244 unsigned RealDestReg = DestReg;
2245 switch (SrcTy->getPrimitiveID()) {
2246 case Type::BoolTyID:
2247 case Type::SByteTyID:
2248 // We don't have the facilities for directly loading byte sized data from
2249 // memory (even signed). Promote it to 16 bits.
2250 PromoteType = Type::ShortTy;
2251 PromoteOpcode = X86::MOVSX16rr8;
2253 case Type::UByteTyID:
2254 PromoteType = Type::ShortTy;
2255 PromoteOpcode = X86::MOVZX16rr8;
2257 case Type::UShortTyID:
2258 PromoteType = Type::IntTy;
2259 PromoteOpcode = X86::MOVZX32rr16;
2261 case Type::UIntTyID: {
2262 // Make a 64 bit temporary... and zero out the top of it...
2263 unsigned TmpReg = makeAnotherReg(Type::LongTy);
2264 BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
2265 BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
2266 SrcTy = Type::LongTy;
2271 case Type::ULongTyID:
2272 // Don't fild into the read destination.
2273 DestReg = makeAnotherReg(Type::DoubleTy);
2275 default: // No promotion needed...
2280 unsigned TmpReg = makeAnotherReg(PromoteType);
2281 unsigned Opc = SrcTy->isSigned() ? X86::MOVSX16rr8 : X86::MOVZX16rr8;
2282 BuildMI(*BB, IP, Opc, 1, TmpReg).addReg(SrcReg);
2283 SrcTy = PromoteType;
2284 SrcClass = getClass(PromoteType);
2288 // Spill the integer to memory and reload it from there...
2290 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2292 if (SrcClass == cLong) {
2293 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
2294 FrameIdx).addReg(SrcReg);
2295 addFrameReference(BuildMI(*BB, IP, X86::MOV32mr, 5),
2296 FrameIdx, 4).addReg(SrcReg+1);
2298 static const unsigned Op1[] = { X86::MOV8mr, X86::MOV16mr, X86::MOV32mr };
2299 addFrameReference(BuildMI(*BB, IP, Op1[SrcClass], 5),
2300 FrameIdx).addReg(SrcReg);
2303 static const unsigned Op2[] =
2304 { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
2305 addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
2307 // We need special handling for unsigned 64-bit integer sources. If the
2308 // input number has the "sign bit" set, then we loaded it incorrectly as a
2309 // negative 64-bit number. In this case, add an offset value.
2310 if (SrcTy == Type::ULongTy) {
2311 // Emit a test instruction to see if the dynamic input value was signed.
2312 BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
2314 // If the sign bit is set, get a pointer to an offset, otherwise get a
2315 // pointer to a zero.
2316 MachineConstantPool *CP = F->getConstantPool();
2317 unsigned Zero = makeAnotherReg(Type::IntTy);
2318 Constant *Null = Constant::getNullValue(Type::UIntTy);
2319 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
2320 CP->getConstantPoolIndex(Null));
2321 unsigned Offset = makeAnotherReg(Type::IntTy);
2322 Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
2324 addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
2325 CP->getConstantPoolIndex(OffsetCst));
2326 unsigned Addr = makeAnotherReg(Type::IntTy);
2327 BuildMI(*BB, IP, X86::CMOVS32rr, 2, Addr).addReg(Zero).addReg(Offset);
2329 // Load the constant for an add. FIXME: this could make an 'fadd' that
2330 // reads directly from memory, but we don't support these yet.
2331 unsigned ConstReg = makeAnotherReg(Type::DoubleTy);
2332 addDirectMem(BuildMI(*BB, IP, X86::FLD32m, 4, ConstReg), Addr);
2334 BuildMI(*BB, IP, X86::FpADD, 2, RealDestReg)
2335 .addReg(ConstReg).addReg(DestReg);
2341 // Handle casts from floating point to integer now...
2342 if (SrcClass == cFP) {
2343 // Change the floating point control register to use "round towards zero"
2344 // mode when truncating to an integer value.
2346 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
2347 addFrameReference(BuildMI(*BB, IP, X86::FNSTCW16m, 4), CWFrameIdx);
2349 // Load the old value of the high byte of the control word...
2350 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
2351 addFrameReference(BuildMI(*BB, IP, X86::MOV8rm, 4, HighPartOfCW),
2354 // Set the high part to be round to zero...
2355 addFrameReference(BuildMI(*BB, IP, X86::MOV8mi, 5),
2356 CWFrameIdx, 1).addImm(12);
2358 // Reload the modified control word now...
2359 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
2361 // Restore the memory image of control word to original value
2362 addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
2363 CWFrameIdx, 1).addReg(HighPartOfCW);
2365 // We don't have the facilities for directly storing byte sized data to
2366 // memory. Promote it to 16 bits. We also must promote unsigned values to
2367 // larger classes because we only have signed FP stores.
2368 unsigned StoreClass = DestClass;
2369 const Type *StoreTy = DestTy;
2370 if (StoreClass == cByte || DestTy->isUnsigned())
2371 switch (StoreClass) {
2372 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
2373 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
2374 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
2375 // The following treatment of cLong may not be perfectly right,
2376 // but it survives chains of casts of the form
2377 // double->ulong->double.
2378 case cLong: StoreTy = Type::LongTy; StoreClass = cLong; break;
2379 default: assert(0 && "Unknown store class!");
2382 // Spill the integer to memory and reload it from there...
2384 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
2386 static const unsigned Op1[] =
2387 { 0, X86::FIST16m, X86::FIST32m, 0, X86::FISTP64m };
2388 addFrameReference(BuildMI(*BB, IP, Op1[StoreClass], 5),
2389 FrameIdx).addReg(SrcReg);
2391 if (DestClass == cLong) {
2392 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg), FrameIdx);
2393 addFrameReference(BuildMI(*BB, IP, X86::MOV32rm, 4, DestReg+1),
2396 static const unsigned Op2[] = { X86::MOV8rm, X86::MOV16rm, X86::MOV32rm };
2397 addFrameReference(BuildMI(*BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
2400 // Reload the original control word now...
2401 addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
2405 // Anything we haven't handled already, we can't (yet) handle at all.
2406 assert(0 && "Unhandled cast instruction!");
2410 /// visitVANextInst - Implement the va_next instruction...
2412 void ISel::visitVANextInst(VANextInst &I) {
2413 unsigned VAList = getReg(I.getOperand(0));
2414 unsigned DestReg = getReg(I);
2417 switch (I.getArgType()->getPrimitiveID()) {
2420 assert(0 && "Error: bad type for va_next instruction!");
2422 case Type::PointerTyID:
2423 case Type::UIntTyID:
2427 case Type::ULongTyID:
2428 case Type::LongTyID:
2429 case Type::DoubleTyID:
2434 // Increment the VAList pointer...
2435 BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
2438 void ISel::visitVAArgInst(VAArgInst &I) {
2439 unsigned VAList = getReg(I.getOperand(0));
2440 unsigned DestReg = getReg(I);
2442 switch (I.getType()->getPrimitiveID()) {
2445 assert(0 && "Error: bad type for va_next instruction!");
2447 case Type::PointerTyID:
2448 case Type::UIntTyID:
2450 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2452 case Type::ULongTyID:
2453 case Type::LongTyID:
2454 addDirectMem(BuildMI(BB, X86::MOV32rm, 4, DestReg), VAList);
2455 addRegOffset(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), VAList, 4);
2457 case Type::DoubleTyID:
2458 addDirectMem(BuildMI(BB, X86::FLD64m, 4, DestReg), VAList);
2463 /// visitGetElementPtrInst - instruction-select GEP instructions
2465 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2466 // If this GEP instruction will be folded into all of its users, we don't need
2467 // to explicitly calculate it!
2468 unsigned A, B, C, D;
2469 if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
2470 // Check all of the users of the instruction to see if they are loads and
2472 bool AllWillFold = true;
2473 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI)
2474 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Load)
2475 if (cast<Instruction>(*UI)->getOpcode() != Instruction::Store ||
2476 cast<Instruction>(*UI)->getOperand(0) == &I) {
2477 AllWillFold = false;
2481 // If the instruction is foldable, and will be folded into all users, don't
2483 if (AllWillFold) return;
2486 unsigned outputReg = getReg(I);
2487 emitGEPOperation(BB, BB->end(), I.getOperand(0),
2488 I.op_begin()+1, I.op_end(), outputReg);
2491 /// getGEPIndex - Inspect the getelementptr operands specified with GEPOps and
2492 /// GEPTypes (the derived types being stepped through at each level). On return
2493 /// from this function, if some indexes of the instruction are representable as
2494 /// an X86 lea instruction, the machine operands are put into the Ops
2495 /// instruction and the consumed indexes are poped from the GEPOps/GEPTypes
2496 /// lists. Otherwise, GEPOps.size() is returned. If this returns a an
2497 /// addressing mode that only partially consumes the input, the BaseReg input of
2498 /// the addressing mode must be left free.
2500 /// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
2502 void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2503 std::vector<Value*> &GEPOps,
2504 std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
2505 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2506 const TargetData &TD = TM.getTargetData();
2508 // Clear out the state we are working with...
2509 BaseReg = 0; // No base register
2510 Scale = 1; // Unit scale
2511 IndexReg = 0; // No index register
2512 Disp = 0; // No displacement
2514 // While there are GEP indexes that can be folded into the current address,
2515 // keep processing them.
2516 while (!GEPTypes.empty()) {
2517 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2518 // It's a struct access. CUI is the index into the structure,
2519 // which names the field. This index must have unsigned type.
2520 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2522 // Use the TargetData structure to pick out what the layout of the
2523 // structure is in memory. Since the structure index must be constant, we
2524 // can get its value and use it to find the right byte offset from the
2525 // StructLayout class's list of structure member offsets.
2526 Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
2527 GEPOps.pop_back(); // Consume a GEP operand
2528 GEPTypes.pop_back();
2530 // It's an array or pointer access: [ArraySize x ElementType].
2531 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2532 Value *idx = GEPOps.back();
2534 // idx is the index into the array. Unlike with structure
2535 // indices, we may not know its actual value at code-generation
2537 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2539 // If idx is a constant, fold it into the offset.
2540 unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
2541 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2542 Disp += TypeSize*CSI->getValue();
2544 // If the index reg is already taken, we can't handle this index.
2545 if (IndexReg) return;
2547 // If this is a size that we can handle, then add the index as
2549 case 1: case 2: case 4: case 8:
2550 // These are all acceptable scales on X86.
2554 // Otherwise, we can't handle this scale
2558 if (CastInst *CI = dyn_cast<CastInst>(idx))
2559 if (CI->getOperand(0)->getType() == Type::IntTy ||
2560 CI->getOperand(0)->getType() == Type::UIntTy)
2561 idx = CI->getOperand(0);
2563 IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
2566 GEPOps.pop_back(); // Consume a GEP operand
2567 GEPTypes.pop_back();
2571 // GEPTypes is empty, which means we have a single operand left. See if we
2572 // can set it as the base register.
2574 // FIXME: When addressing modes are more powerful/correct, we could load
2575 // global addresses directly as 32-bit immediates.
2576 assert(BaseReg == 0);
2577 BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
2578 GEPOps.pop_back(); // Consume the last GEP operand
2582 /// isGEPFoldable - Return true if the specified GEP can be completely
2583 /// folded into the addressing mode of a load/store or lea instruction.
2584 bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
2585 Value *Src, User::op_iterator IdxBegin,
2586 User::op_iterator IdxEnd, unsigned &BaseReg,
2587 unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
2588 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2589 Src = CPR->getValue();
2591 std::vector<Value*> GEPOps;
2592 GEPOps.resize(IdxEnd-IdxBegin+1);
2594 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2596 std::vector<const Type*> GEPTypes;
2597 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2598 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2600 MachineBasicBlock::iterator IP;
2601 if (MBB) IP = MBB->end();
2602 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2604 // We can fold it away iff the getGEPIndex call eliminated all operands.
2605 return GEPOps.empty();
2608 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2609 MachineBasicBlock::iterator IP,
2610 Value *Src, User::op_iterator IdxBegin,
2611 User::op_iterator IdxEnd, unsigned TargetReg) {
2612 const TargetData &TD = TM.getTargetData();
2613 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2614 Src = CPR->getValue();
2616 std::vector<Value*> GEPOps;
2617 GEPOps.resize(IdxEnd-IdxBegin+1);
2619 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2621 std::vector<const Type*> GEPTypes;
2622 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2623 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2625 // Keep emitting instructions until we consume the entire GEP instruction.
2626 while (!GEPOps.empty()) {
2627 unsigned OldSize = GEPOps.size();
2628 unsigned BaseReg, Scale, IndexReg, Disp;
2629 getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
2631 if (GEPOps.size() != OldSize) {
2632 // getGEPIndex consumed some of the input. Build an LEA instruction here.
2633 unsigned NextTarget = 0;
2634 if (!GEPOps.empty()) {
2635 assert(BaseReg == 0 &&
2636 "getGEPIndex should have left the base register open for chaining!");
2637 NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
2640 if (IndexReg == 0 && Disp == 0)
2641 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
2643 addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
2644 BaseReg, Scale, IndexReg, Disp);
2646 TargetReg = NextTarget;
2647 } else if (GEPTypes.empty()) {
2648 // The getGEPIndex operation didn't want to build an LEA. Check to see if
2649 // all operands are consumed but the base pointer. If so, just load it
2650 // into the register.
2651 if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps[0])) {
2652 BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(GV);
2654 unsigned BaseReg = getReg(GEPOps[0], MBB, IP);
2655 BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
2657 break; // we are now done
2660 // It's an array or pointer access: [ArraySize x ElementType].
2661 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2662 Value *idx = GEPOps.back();
2663 GEPOps.pop_back(); // Consume a GEP operand
2664 GEPTypes.pop_back();
2666 // idx is the index into the array. Unlike with structure
2667 // indices, we may not know its actual value at code-generation
2669 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
2671 // Most GEP instructions use a [cast (int/uint) to LongTy] as their
2672 // operand on X86. Handle this case directly now...
2673 if (CastInst *CI = dyn_cast<CastInst>(idx))
2674 if (CI->getOperand(0)->getType() == Type::IntTy ||
2675 CI->getOperand(0)->getType() == Type::UIntTy)
2676 idx = CI->getOperand(0);
2678 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2679 // must find the size of the pointed-to type (Not coincidentally, the next
2680 // type is the type of the elements in the array).
2681 const Type *ElTy = SqTy->getElementType();
2682 unsigned elementSize = TD.getTypeSize(ElTy);
2684 // If idxReg is a constant, we don't need to perform the multiply!
2685 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
2686 if (!CSI->isNullValue()) {
2687 unsigned Offset = elementSize*CSI->getValue();
2688 unsigned Reg = makeAnotherReg(Type::UIntTy);
2689 BuildMI(*MBB, IP, X86::ADD32ri, 2, TargetReg)
2690 .addReg(Reg).addImm(Offset);
2691 --IP; // Insert the next instruction before this one.
2692 TargetReg = Reg; // Codegen the rest of the GEP into this
2694 } else if (elementSize == 1) {
2695 // If the element size is 1, we don't have to multiply, just add
2696 unsigned idxReg = getReg(idx, MBB, IP);
2697 unsigned Reg = makeAnotherReg(Type::UIntTy);
2698 BuildMI(*MBB, IP, X86::ADD32rr, 2,TargetReg).addReg(Reg).addReg(idxReg);
2699 --IP; // Insert the next instruction before this one.
2700 TargetReg = Reg; // Codegen the rest of the GEP into this
2702 unsigned idxReg = getReg(idx, MBB, IP);
2703 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2705 // Make sure we can back the iterator up to point to the first
2706 // instruction emitted.
2707 MachineBasicBlock::iterator BeforeIt = IP;
2708 if (IP == MBB->begin())
2709 BeforeIt = MBB->end();
2712 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2714 // Emit an ADD to add OffsetReg to the basePtr.
2715 unsigned Reg = makeAnotherReg(Type::UIntTy);
2716 BuildMI(*MBB, IP, X86::ADD32rr, 2, TargetReg)
2717 .addReg(Reg).addReg(OffsetReg);
2719 // Step to the first instruction of the multiply.
2720 if (BeforeIt == MBB->end())
2725 TargetReg = Reg; // Codegen the rest of the GEP into this
2732 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2733 /// frame manager, otherwise do it the hard way.
2735 void ISel::visitAllocaInst(AllocaInst &I) {
2736 // Find the data size of the alloca inst's getAllocatedType.
2737 const Type *Ty = I.getAllocatedType();
2738 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2740 // If this is a fixed size alloca in the entry block for the function,
2741 // statically stack allocate the space.
2743 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
2744 if (I.getParent() == I.getParent()->getParent()->begin()) {
2745 TySize *= CUI->getValue(); // Get total allocated size...
2746 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
2748 // Create a new stack object using the frame manager...
2749 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
2750 addFrameReference(BuildMI(BB, X86::LEA32r, 5, getReg(I)), FrameIdx);
2755 // Create a register to hold the temporary result of multiplying the type size
2756 // constant by the variable amount.
2757 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2758 unsigned SrcReg1 = getReg(I.getArraySize());
2760 // TotalSizeReg = mul <numelements>, <TypeSize>
2761 MachineBasicBlock::iterator MBBI = BB->end();
2762 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2764 // AddedSize = add <TotalSizeReg>, 15
2765 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2766 BuildMI(BB, X86::ADD32ri, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
2768 // AlignedSize = and <AddedSize>, ~15
2769 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2770 BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
2772 // Subtract size from stack pointer, thereby allocating some space.
2773 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
2775 // Put a pointer to the space into the result register, by copying
2776 // the stack pointer.
2777 BuildMI(BB, X86::MOV32rr, 1, getReg(I)).addReg(X86::ESP);
2779 // Inform the Frame Information that we have just allocated a variable-sized
2781 F->getFrameInfo()->CreateVariableSizedObject();
2784 /// visitMallocInst - Malloc instructions are code generated into direct calls
2785 /// to the library malloc.
2787 void ISel::visitMallocInst(MallocInst &I) {
2788 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2791 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2792 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2794 Arg = makeAnotherReg(Type::UIntTy);
2795 unsigned Op0Reg = getReg(I.getOperand(0));
2796 MachineBasicBlock::iterator MBBI = BB->end();
2797 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2800 std::vector<ValueRecord> Args;
2801 Args.push_back(ValueRecord(Arg, Type::UIntTy));
2802 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2803 1).addExternalSymbol("malloc", true);
2804 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
2808 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2811 void ISel::visitFreeInst(FreeInst &I) {
2812 std::vector<ValueRecord> Args;
2813 Args.push_back(ValueRecord(I.getOperand(0)));
2814 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
2815 1).addExternalSymbol("free", true);
2816 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
2819 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
2820 /// into a machine code representation is a very simple peep-hole fashion. The
2821 /// generated code sucks but the implementation is nice and simple.
2823 FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
2824 return new ISel(TM);