1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
3 // This file defines a simple peephole instruction selector for the x86 platform
5 //===----------------------------------------------------------------------===//
8 #include "X86InstrInfo.h"
9 #include "X86InstrBuilder.h"
10 #include "llvm/Function.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iOperators.h"
13 #include "llvm/iOther.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/iMemory.h"
16 #include "llvm/Type.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Pass.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Support/InstVisitor.h"
24 #include "llvm/Target/MRegisterInfo.h"
27 using namespace MOTy; // Get Use, Def, UseAndDef
30 /// BMI - A special BuildMI variant that takes an iterator to insert the
31 /// instruction at as well as a basic block.
32 /// this is the version for when you have a destination register in mind.
33 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
34 MachineBasicBlock::iterator &I,
38 MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
39 I = ++MBB->insert(I, MI);
40 return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
43 /// BMI - A special BuildMI variant that takes an iterator to insert the
44 /// instruction at as well as a basic block.
45 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
46 MachineBasicBlock::iterator &I,
48 unsigned NumOperands) {
49 MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
50 I = ++MBB->insert(I, MI);
51 return MachineInstrBuilder(MI);
56 struct ISel : public FunctionPass, InstVisitor<ISel> {
58 MachineFunction *F; // The function we are compiling into
59 MachineBasicBlock *BB; // The current MBB we are compiling
62 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
64 // MBBMap - Mapping between LLVM BB -> Machine BB
65 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
67 ISel(TargetMachine &tm)
68 : TM(tm), F(0), BB(0), CurReg(MRegisterInfo::FirstVirtualRegister) {}
70 /// runOnFunction - Top level implementation of instruction selection for
71 /// the entire function.
73 bool runOnFunction(Function &Fn) {
74 F = &MachineFunction::construct(&Fn, TM);
76 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
77 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
79 // Instruction select everything except PHI nodes
82 // Select the PHI nodes
87 CurReg = MRegisterInfo::FirstVirtualRegister;
89 return false; // We never modify the LLVM itself.
92 /// visitBasicBlock - This method is called when we are visiting a new basic
93 /// block. This simply creates a new MachineBasicBlock to emit code into
94 /// and adds it to the current MachineFunction. Subsequent visit* for
95 /// instructions will be invoked for all instructions in the basic block.
97 void visitBasicBlock(BasicBlock &LLVM_BB) {
98 BB = MBBMap[&LLVM_BB];
102 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
103 /// because we have to generate our sources into the source basic blocks,
104 /// not the current one.
106 void SelectPHINodes();
108 // Visitation methods for various instructions. These methods simply emit
109 // fixed X86 code for each instruction.
112 // Control flow operators
113 void visitReturnInst(ReturnInst &RI);
114 void visitBranchInst(BranchInst &BI);
115 void visitCallInst(CallInst &I);
117 // Arithmetic operators
118 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
119 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
120 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
121 void doMultiply(unsigned destReg, const Type *resultType,
122 unsigned op0Reg, unsigned op1Reg,
123 MachineBasicBlock *MBB,
124 MachineBasicBlock::iterator &MBBI);
125 void visitMul(BinaryOperator &B);
127 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
128 void visitRem(BinaryOperator &B) { visitDivRem(B); }
129 void visitDivRem(BinaryOperator &B);
132 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
133 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
134 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
136 // Binary comparison operators
137 void visitSetCCInst(SetCondInst &I, unsigned OpNum);
138 void visitSetEQ(SetCondInst &I) { visitSetCCInst(I, 0); }
139 void visitSetNE(SetCondInst &I) { visitSetCCInst(I, 1); }
140 void visitSetLT(SetCondInst &I) { visitSetCCInst(I, 2); }
141 void visitSetGT(SetCondInst &I) { visitSetCCInst(I, 3); }
142 void visitSetLE(SetCondInst &I) { visitSetCCInst(I, 4); }
143 void visitSetGE(SetCondInst &I) { visitSetCCInst(I, 5); }
145 // Memory Instructions
146 void visitLoadInst(LoadInst &I);
147 void visitStoreInst(StoreInst &I);
148 void visitGetElementPtrInst(GetElementPtrInst &I);
149 void visitMallocInst(MallocInst &I);
150 void visitFreeInst(FreeInst &I);
151 void visitAllocaInst(AllocaInst &I);
154 void visitShiftInst(ShiftInst &I);
155 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
156 void visitCastInst(CastInst &I);
158 void visitInstruction(Instruction &I) {
159 std::cerr << "Cannot instruction select: " << I;
163 /// promote32 - Make a value 32-bits wide, and put it somewhere.
164 void promote32 (const unsigned targetReg, Value *v);
166 // emitGEPOperation - Common code shared between visitGetElementPtrInst and
167 // constant expression GEP support.
169 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
170 Value *Src, User::op_iterator IdxBegin,
171 User::op_iterator IdxEnd, unsigned TargetReg);
173 /// copyConstantToRegister - Output the instructions required to put the
174 /// specified constant into the specified register.
176 void copyConstantToRegister(Constant *C, unsigned Reg,
177 MachineBasicBlock *MBB,
178 MachineBasicBlock::iterator &MBBI);
180 /// makeAnotherReg - This method returns the next register number
181 /// we haven't yet used.
182 unsigned makeAnotherReg(const Type *Ty) {
183 // Add the mapping of regnumber => reg class to MachineFunction
184 F->addRegMap(CurReg, TM.getRegisterInfo()->getRegClassForType(Ty));
188 /// getReg - This method turns an LLVM value into a register number. This
189 /// is guaranteed to produce the same register number for a particular value
190 /// every time it is queried.
192 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
193 unsigned getReg(Value *V) {
194 // Just append to the end of the current bb.
195 MachineBasicBlock::iterator It = BB->end();
196 return getReg(V, BB, It);
198 unsigned getReg(Value *V, MachineBasicBlock *MBB,
199 MachineBasicBlock::iterator &IPt) {
200 unsigned &Reg = RegMap[V];
202 Reg = makeAnotherReg(V->getType());
206 // If this operand is a constant, emit the code to copy the constant into
207 // the register here...
209 if (Constant *C = dyn_cast<Constant>(V)) {
210 copyConstantToRegister(C, Reg, BB, IPt);
211 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
212 // Move the address of the global into the register
213 BMI(MBB, IPt, X86::MOVir32, 1, Reg).addReg(GV);
214 } else if (Argument *A = dyn_cast<Argument>(V)) {
215 // Find the position of the argument in the argument list.
216 const Function *f = F->getFunction ();
217 // The function's arguments look like this:
218 // [EBP] -- copy of old EBP
219 // [EBP + 4] -- return address
220 // [EBP + 8] -- first argument (leftmost lexically)
221 // So we want to start with counter = 2.
222 int counter = 2, argPos = -1;
223 for (Function::const_aiterator ai = f->abegin (), ae = f->aend ();
227 break; // Only need to find it once. ;-)
232 && "Argument not found in current function's argument list");
233 // Load it out of the stack frame at EBP + 4*argPos.
234 addRegOffset(BMI(MBB, IPt, X86::MOVmr32, 4, Reg), X86::EBP, 4*argPos);
242 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
246 cByte, cShort, cInt, cLong, cFloat, cDouble
249 /// getClass - Turn a primitive type into a "class" number which is based on the
250 /// size of the type, and whether or not it is floating point.
252 static inline TypeClass getClass(const Type *Ty) {
253 switch (Ty->getPrimitiveID()) {
254 case Type::SByteTyID:
255 case Type::UByteTyID: return cByte; // Byte operands are class #0
256 case Type::ShortTyID:
257 case Type::UShortTyID: return cShort; // Short operands are class #1
260 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
263 case Type::ULongTyID: //return cLong; // Longs are class #3
264 return cInt; // FIXME: LONGS ARE TREATED AS INTS!
266 case Type::FloatTyID: return cFloat; // Float is class #4
267 case Type::DoubleTyID: return cDouble; // Doubles are class #5
269 assert(0 && "Invalid type to getClass!");
270 return cByte; // not reached
275 /// copyConstantToRegister - Output the instructions required to put the
276 /// specified constant into the specified register.
278 void ISel::copyConstantToRegister(Constant *C, unsigned R,
279 MachineBasicBlock *MBB,
280 MachineBasicBlock::iterator &IP) {
281 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
282 if (CE->getOpcode() == Instruction::GetElementPtr) {
283 emitGEPOperation(BB, IP, CE->getOperand(0),
284 CE->op_begin()+1, CE->op_end(), R);
288 std::cerr << "Offending expr: " << C << "\n";
289 assert (0 && "Constant expressions not yet handled!\n");
292 if (C->getType()->isIntegral()) {
293 unsigned Class = getClass(C->getType());
294 assert(Class != 3 && "Type not handled yet!");
296 static const unsigned IntegralOpcodeTab[] = {
297 X86::MOVir8, X86::MOVir16, X86::MOVir32
300 if (C->getType()->isSigned()) {
301 ConstantSInt *CSI = cast<ConstantSInt>(C);
302 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addSImm(CSI->getValue());
304 ConstantUInt *CUI = cast<ConstantUInt>(C);
305 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
307 } else if (isa<ConstantPointerNull>(C)) {
308 // Copy zero (null pointer) to the register.
309 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
310 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
311 unsigned SrcReg = getReg(CPR->getValue(), BB, IP);
312 BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
314 std::cerr << "Offending constant: " << C << "\n";
315 assert(0 && "Type not handled yet!");
319 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
320 /// because we have to generate our sources into the source basic blocks, not
323 void ISel::SelectPHINodes() {
324 const Function &LF = *F->getFunction(); // The LLVM function...
325 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
326 const BasicBlock *BB = I;
327 MachineBasicBlock *MBB = MBBMap[I];
329 // Loop over all of the PHI nodes in the LLVM basic block...
330 unsigned NumPHIs = 0;
331 for (BasicBlock::const_iterator I = BB->begin();
332 PHINode *PN = (PHINode*)dyn_cast<PHINode>(&*I); ++I) {
333 // Create a new machine instr PHI node, and insert it.
334 MachineInstr *MI = BuildMI(X86::PHI, PN->getNumOperands(), getReg(*PN));
335 MBB->insert(MBB->begin()+NumPHIs++, MI); // Insert it at the top of the BB
337 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
338 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
340 // Get the incoming value into a virtual register. If it is not already
341 // available in a virtual register, insert the computation code into
343 MachineBasicBlock::iterator PI = PredMBB->end()-1;
344 MI->addRegOperand(getReg(PN->getIncomingValue(i), PredMBB, PI));
347 // FIXME: Pass in the MachineBasicBlocks instead of the basic blocks...
348 MI->addPCDispOperand(PN->getIncomingBlock(i)); // PredMBB
356 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
357 /// register, then move it to wherever the result should be.
358 /// We handle FP setcc instructions by pushing them, doing a
359 /// compare-and-pop-twice, and then copying the concodes to the main
360 /// processor's concodes (I didn't make this up, it's in the Intel manual)
362 void ISel::visitSetCCInst(SetCondInst &I, unsigned OpNum) {
363 // The arguments are already supposed to be of the same type.
364 const Type *CompTy = I.getOperand(0)->getType();
365 unsigned reg1 = getReg(I.getOperand(0));
366 unsigned reg2 = getReg(I.getOperand(1));
368 unsigned Class = getClass(CompTy);
370 // Emit: cmp <var1>, <var2> (do the comparison). We can
371 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
374 BuildMI (BB, X86::CMPrr8, 2).addReg (reg1).addReg (reg2);
377 BuildMI (BB, X86::CMPrr16, 2).addReg (reg1).addReg (reg2);
380 BuildMI (BB, X86::CMPrr32, 2).addReg (reg1).addReg (reg2);
383 // Push the variables on the stack with fldl opcodes.
384 // FIXME: assuming var1, var2 are in memory, if not, spill to
386 case cFloat: // Floats
387 BuildMI (BB, X86::FLDr32, 1).addReg (reg1);
388 BuildMI (BB, X86::FLDr32, 1).addReg (reg2);
390 case cDouble: // Doubles
391 BuildMI (BB, X86::FLDr64, 1).addReg (reg1);
392 BuildMI (BB, X86::FLDr64, 1).addReg (reg2);
399 if (CompTy->isFloatingPoint()) {
400 // (Non-trapping) compare and pop twice.
401 BuildMI (BB, X86::FUCOMPP, 0);
402 // Move fp status word (concodes) to ax.
403 BuildMI (BB, X86::FNSTSWr8, 1, X86::AX);
404 // Load real concodes from ax.
405 BuildMI (BB, X86::SAHF, 1).addReg(X86::AH);
408 // Emit setOp instruction (extract concode; clobbers ax),
409 // using the following mapping:
410 // LLVM -> X86 signed X86 unsigned
412 // seteq -> sete sete
413 // setne -> setne setne
414 // setlt -> setl setb
415 // setgt -> setg seta
416 // setle -> setle setbe
417 // setge -> setge setae
419 static const unsigned OpcodeTab[2][6] = {
420 {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAr, X86::SETBEr, X86::SETAEr},
421 {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGr, X86::SETLEr, X86::SETGEr},
424 BuildMI(BB, OpcodeTab[CompTy->isSigned()][OpNum], 0, X86::AL);
426 // Put it in the result using a move.
427 BuildMI (BB, X86::MOVrr8, 1, getReg(I)).addReg(X86::AL);
430 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
431 /// operand, in the specified target register.
433 ISel::promote32 (unsigned targetReg, Value *v)
435 unsigned vReg = getReg (v);
436 unsigned Class = getClass (v->getType ());
437 bool isUnsigned = v->getType ()->isUnsigned ();
438 assert (((Class == cByte) || (Class == cShort) || (Class == cInt))
439 && "Unpromotable operand class in promote32");
443 // Extend value into target register (8->32)
445 BuildMI (BB, X86::MOVZXr32r8, 1, targetReg).addReg (vReg);
447 BuildMI (BB, X86::MOVSXr32r8, 1, targetReg).addReg (vReg);
450 // Extend value into target register (16->32)
452 BuildMI (BB, X86::MOVZXr32r16, 1, targetReg).addReg (vReg);
454 BuildMI (BB, X86::MOVSXr32r16, 1, targetReg).addReg (vReg);
457 // Move value into target register (32->32)
458 BuildMI (BB, X86::MOVrr32, 1, targetReg).addReg (vReg);
463 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
464 /// we have the following possibilities:
466 /// ret void: No return value, simply emit a 'ret' instruction
467 /// ret sbyte, ubyte : Extend value into EAX and return
468 /// ret short, ushort: Extend value into EAX and return
469 /// ret int, uint : Move value into EAX and return
470 /// ret pointer : Move value into EAX and return
471 /// ret long, ulong : Move value into EAX/EDX and return
472 /// ret float/double : Top of FP stack
475 ISel::visitReturnInst (ReturnInst &I)
477 if (I.getNumOperands () == 0)
479 // Emit a 'ret' instruction
480 BuildMI (BB, X86::RET, 0);
483 Value *rv = I.getOperand (0);
484 unsigned Class = getClass (rv->getType ());
487 // integral return values: extend or move into EAX and return.
491 promote32 (X86::EAX, rv);
493 // ret float/double: top of FP stack
495 case cFloat: // Floats
496 BuildMI (BB, X86::FLDr32, 1).addReg (getReg (rv));
498 case cDouble: // Doubles
499 BuildMI (BB, X86::FLDr64, 1).addReg (getReg (rv));
502 // ret long: use EAX(least significant 32 bits)/EDX (most
503 // significant 32)...uh, I think so Brain, but how do i call
504 // up the two parts of the value from inside this mouse
507 visitInstruction (I);
509 // Emit a 'ret' instruction
510 BuildMI (BB, X86::RET, 0);
513 /// visitBranchInst - Handle conditional and unconditional branches here. Note
514 /// that since code layout is frozen at this point, that if we are trying to
515 /// jump to a block that is the immediate successor of the current block, we can
516 /// just make a fall-through. (but we don't currently).
519 ISel::visitBranchInst (BranchInst & BI)
521 if (BI.isConditional ())
523 BasicBlock *ifTrue = BI.getSuccessor (0);
524 BasicBlock *ifFalse = BI.getSuccessor (1); // this is really unobvious
526 // simplest thing I can think of: compare condition with zero,
527 // followed by jump-if-equal to ifFalse, and jump-if-nonequal to
529 unsigned int condReg = getReg (BI.getCondition ());
530 BuildMI (BB, X86::CMPri8, 2).addReg (condReg).addZImm (0);
531 BuildMI (BB, X86::JNE, 1).addPCDisp (BI.getSuccessor (0));
532 BuildMI (BB, X86::JE, 1).addPCDisp (BI.getSuccessor (1));
534 else // unconditional branch
536 BuildMI (BB, X86::JMP, 1).addPCDisp (BI.getSuccessor (0));
540 /// visitCallInst - Push args on stack and do a procedure call instruction.
542 ISel::visitCallInst (CallInst & CI)
544 // keep a counter of how many bytes we pushed on the stack
545 unsigned bytesPushed = 0;
547 // Push the arguments on the stack in reverse order, as specified by
549 for (unsigned i = CI.getNumOperands()-1; i >= 1; --i)
551 Value *v = CI.getOperand (i);
552 switch (getClass (v->getType ()))
556 // Promote V to 32 bits wide, and move the result into EAX,
558 promote32 (X86::EAX, v);
559 BuildMI (BB, X86::PUSHr32, 1).addReg (X86::EAX);
564 unsigned Reg = getReg(v);
565 BuildMI (BB, X86::PUSHr32, 1).addReg(Reg);
570 // FIXME: long/ulong/double args not handled.
571 visitInstruction (CI);
575 // Emit a CALL instruction with PC-relative displacement.
576 BuildMI (BB, X86::CALLpcrel32, 1).addPCDisp (CI.getCalledValue ());
578 // Adjust the stack by `bytesPushed' amount if non-zero
580 BuildMI (BB, X86::ADDri32, 2).addReg(X86::ESP).addZImm(bytesPushed);
582 // If there is a return value, scavenge the result from the location the call
585 if (CI.getType() != Type::VoidTy) {
586 unsigned resultTypeClass = getClass (CI.getType ());
587 switch (resultTypeClass) {
591 // Integral results are in %eax, or the appropriate portion
593 static const unsigned regRegMove[] = {
594 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
596 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
597 BuildMI (BB, regRegMove[resultTypeClass], 1,
598 getReg (CI)).addReg (AReg[resultTypeClass]);
602 // Floating-point return values live in %st(0) (i.e., the top of
603 // the FP stack.) The general way to approach this is to do a
604 // FSTP to save the top of the FP stack on the real stack, then
605 // do a MOV to load the top of the real stack into the target
607 visitInstruction (CI); // FIXME: add the right args for the calls below
608 // BuildMI (BB, X86::FSTPm32, 0);
609 // BuildMI (BB, X86::MOVmr32, 0);
612 std::cerr << "Cannot get return value for call of type '"
613 << *CI.getType() << "'\n";
614 visitInstruction(CI);
619 /// visitSimpleBinary - Implement simple binary operators for integral types...
620 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
623 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
624 if (B.getType() == Type::BoolTy) // FIXME: Handle bools for logicals
627 unsigned Class = getClass(B.getType());
628 if (Class > 2) // FIXME: Handle longs
631 static const unsigned OpcodeTab[][4] = {
632 // Arithmetic operators
633 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, 0 }, // ADD
634 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, 0 }, // SUB
637 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
638 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
639 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
642 unsigned Opcode = OpcodeTab[OperatorClass][Class];
643 unsigned Op0r = getReg(B.getOperand(0));
644 unsigned Op1r = getReg(B.getOperand(1));
645 BuildMI(BB, Opcode, 2, getReg(B)).addReg(Op0r).addReg(Op1r);
648 /// doMultiply - Emit appropriate instructions to multiply together
649 /// the registers op0Reg and op1Reg, and put the result in destReg.
650 /// The type of the result should be given as resultType.
652 ISel::doMultiply(unsigned destReg, const Type *resultType,
653 unsigned op0Reg, unsigned op1Reg,
654 MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI)
656 unsigned Class = getClass (resultType);
659 assert (Class <= 2 && "Someday, we will learn how to multiply"
660 "longs and floating-point numbers. This is not that day.");
662 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
663 static const unsigned MulOpcode[]={ X86::MULrr8, X86::MULrr16, X86::MULrr32 };
664 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
665 unsigned Reg = Regs[Class];
667 // Emit a MOV to put the first operand into the appropriately-sized
669 BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg (op0Reg);
671 // Emit the appropriate multiply instruction.
672 BMI(MBB, MBBI, MulOpcode[Class], 1).addReg (op1Reg);
674 // Emit another MOV to put the result into the destination register.
675 BMI(MBB, MBBI, MovOpcode[Class], 1, destReg).addReg (Reg);
678 /// visitMul - Multiplies are not simple binary operators because they must deal
679 /// with the EAX register explicitly.
681 void ISel::visitMul(BinaryOperator &I) {
682 MachineBasicBlock::iterator MBBI = BB->end();
683 doMultiply (getReg (I), I.getType (),
684 getReg (I.getOperand (0)), getReg (I.getOperand (1)),
689 /// visitDivRem - Handle division and remainder instructions... these
690 /// instruction both require the same instructions to be generated, they just
691 /// select the result from a different register. Note that both of these
692 /// instructions work differently for signed and unsigned operands.
694 void ISel::visitDivRem(BinaryOperator &I) {
695 unsigned Class = getClass(I.getType());
696 if (Class > 2) // FIXME: Handle longs
699 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
700 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
701 static const unsigned ExtOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
702 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
703 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
705 static const unsigned DivOpcode[][4] = {
706 { X86::DIVrr8 , X86::DIVrr16 , X86::DIVrr32 , 0 }, // Unsigned division
707 { X86::IDIVrr8, X86::IDIVrr16, X86::IDIVrr32, 0 }, // Signed division
710 bool isSigned = I.getType()->isSigned();
711 unsigned Reg = Regs[Class];
712 unsigned ExtReg = ExtRegs[Class];
713 unsigned Op0Reg = getReg(I.getOperand(0));
714 unsigned Op1Reg = getReg(I.getOperand(1));
716 // Put the first operand into one of the A registers...
717 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
720 // Emit a sign extension instruction...
721 BuildMI(BB, ExtOpcode[Class], 0);
723 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
724 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
727 // Emit the appropriate divide or remainder instruction...
728 BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
730 // Figure out which register we want to pick the result out of...
731 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
733 // Put the result into the destination register...
734 BuildMI(BB, MovOpcode[Class], 1, getReg(I)).addReg(DestReg);
738 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
739 /// for constant immediate shift values, and for constant immediate
740 /// shift values equal to 1. Even the general case is sort of special,
741 /// because the shift amount has to be in CL, not just any old register.
743 void ISel::visitShiftInst (ShiftInst &I) {
744 unsigned Op0r = getReg (I.getOperand(0));
745 unsigned DestReg = getReg(I);
746 bool isLeftShift = I.getOpcode() == Instruction::Shl;
747 bool isOperandSigned = I.getType()->isUnsigned();
748 unsigned OperandClass = getClass(I.getType());
750 if (OperandClass > 2)
751 visitInstruction(I); // Can't handle longs yet!
753 if (ConstantUInt *CUI = dyn_cast <ConstantUInt> (I.getOperand (1)))
755 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
756 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
757 unsigned char shAmt = CUI->getValue();
759 static const unsigned ConstantOperand[][4] = {
760 { X86::SHRir8, X86::SHRir16, X86::SHRir32, 0 }, // SHR
761 { X86::SARir8, X86::SARir16, X86::SARir32, 0 }, // SAR
762 { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 }, // SHL
763 { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 }, // SAL = SHL
766 const unsigned *OpTab = // Figure out the operand table to use
767 ConstantOperand[isLeftShift*2+isOperandSigned];
769 // Emit: <insn> reg, shamt (shift-by-immediate opcode "ir" form.)
770 BuildMI(BB, OpTab[OperandClass], 2, DestReg).addReg(Op0r).addZImm(shAmt);
774 // The shift amount is non-constant.
776 // In fact, you can only shift with a variable shift amount if
777 // that amount is already in the CL register, so we have to put it
781 // Emit: move cl, shiftAmount (put the shift amount in CL.)
782 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
784 // This is a shift right (SHR).
785 static const unsigned NonConstantOperand[][4] = {
786 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32, 0 }, // SHR
787 { X86::SARrr8, X86::SARrr16, X86::SARrr32, 0 }, // SAR
788 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 }, // SHL
789 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 }, // SAL = SHL
792 const unsigned *OpTab = // Figure out the operand table to use
793 NonConstantOperand[isLeftShift*2+isOperandSigned];
795 BuildMI(BB, OpTab[OperandClass], 1, DestReg).addReg(Op0r);
800 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
803 void ISel::visitLoadInst(LoadInst &I) {
804 unsigned Class = getClass(I.getType());
805 if (Class > 2) // FIXME: Handle longs and others...
808 static const unsigned Opcode[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
810 unsigned AddressReg = getReg(I.getOperand(0));
811 addDirectMem(BuildMI(BB, Opcode[Class], 4, getReg(I)), AddressReg);
815 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
818 void ISel::visitStoreInst(StoreInst &I) {
819 unsigned Class = getClass(I.getOperand(0)->getType());
820 if (Class > 2) // FIXME: Handle longs and others...
823 static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
825 unsigned ValReg = getReg(I.getOperand(0));
826 unsigned AddressReg = getReg(I.getOperand(1));
827 addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
831 /// visitCastInst - Here we have various kinds of copying with or without
832 /// sign extension going on.
834 ISel::visitCastInst (CastInst &CI)
836 const Type *targetType = CI.getType ();
837 Value *operand = CI.getOperand (0);
838 unsigned int operandReg = getReg (operand);
839 const Type *sourceType = operand->getType ();
840 unsigned int destReg = getReg (CI);
842 // Currently we handle:
846 // 2) cast {sbyte, ubyte} to {sbyte, ubyte}
847 // cast {short, ushort} to {ushort, short}
848 // cast {int, uint, ptr} to {int, uint, ptr}
850 // 3) cast {sbyte, ubyte} to {ushort, short}
851 // cast {sbyte, ubyte} to {int, uint, ptr}
852 // cast {short, ushort} to {int, uint, ptr}
854 // 4) cast {int, uint, ptr} to {short, ushort}
855 // cast {int, uint, ptr} to {sbyte, ubyte}
856 // cast {short, ushort} to {sbyte, ubyte}
858 // 1) Implement casts to bool by using compare on the operand followed
859 // by set if not zero on the result.
860 if (targetType == Type::BoolTy)
862 BuildMI (BB, X86::CMPri8, 2).addReg (operandReg).addZImm (0);
863 BuildMI (BB, X86::SETNEr, 1, destReg);
867 // 2) Implement casts between values of the same type class (as determined
868 // by getClass) by using a register-to-register move.
869 unsigned srcClass = sourceType == Type::BoolTy ? cByte : getClass(sourceType);
870 unsigned targClass = getClass (targetType);
871 static const unsigned regRegMove[] = {
872 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
874 if ((srcClass < 3) && (targClass < 3) && (srcClass == targClass))
876 BuildMI (BB, regRegMove[srcClass], 1, destReg).addReg (operandReg);
879 // 3) Handle cast of SMALLER int to LARGER int using a move with sign
880 // extension or zero extension, depending on whether the source type
882 if ((srcClass < 3) && (targClass < 3) && (srcClass < targClass))
884 static const unsigned ops[] = {
885 X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16,
886 X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16
888 unsigned srcSigned = sourceType->isSigned ();
889 BuildMI (BB, ops[3 * srcSigned + srcClass + targClass - 1], 1,
890 destReg).addReg (operandReg);
893 // 4) Handle cast of LARGER int to SMALLER int using a move to EAX
894 // followed by a move out of AX or AL.
895 if ((srcClass < 3) && (targClass < 3) && (srcClass > targClass))
897 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
898 BuildMI (BB, regRegMove[srcClass], 1,
899 AReg[srcClass]).addReg (operandReg);
900 BuildMI (BB, regRegMove[targClass], 1, destReg).addReg (AReg[srcClass]);
903 // Anything we haven't handled already, we can't (yet) handle at all.
905 // FP to integral casts can be handled with FISTP to store onto the
906 // stack while converting to integer, followed by a MOV to load from
907 // the stack into the result register. Integral to FP casts can be
908 // handled with MOV to store onto the stack, followed by a FILD to
909 // load from the stack while converting to FP. For the moment, I
910 // can't quite get straight in my head how to borrow myself some
911 // stack space and write on it. Otherwise, this would be trivial.
912 visitInstruction (CI);
915 /// visitGetElementPtrInst - I don't know, most programs don't have
916 /// getelementptr instructions, right? That means we can put off
917 /// implementing this, right? Right. This method emits machine
918 /// instructions to perform type-safe pointer arithmetic. I am
919 /// guessing this could be cleaned up somewhat to use fewer temporary
922 ISel::visitGetElementPtrInst (GetElementPtrInst &I)
924 MachineBasicBlock::iterator MI = BB->end();
925 emitGEPOperation(BB, MI, I.getOperand(0),
926 I.op_begin()+1, I.op_end(), getReg(I));
929 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
930 MachineBasicBlock::iterator &IP,
931 Value *Src, User::op_iterator IdxBegin,
932 User::op_iterator IdxEnd, unsigned TargetReg) {
933 const TargetData &TD = TM.getTargetData();
934 const Type *Ty = Src->getType();
935 unsigned basePtrReg = getReg(Src, BB, IP);
937 // GEPs have zero or more indices; we must perform a struct access
938 // or array access for each one.
939 for (GetElementPtrInst::op_iterator oi = IdxBegin,
940 oe = IdxEnd; oi != oe; ++oi) {
942 unsigned nextBasePtrReg = makeAnotherReg(Type::UIntTy);
943 if (const StructType *StTy = dyn_cast <StructType> (Ty)) {
944 // It's a struct access. idx is the index into the structure,
945 // which names the field. This index must have ubyte type.
946 const ConstantUInt *CUI = cast <ConstantUInt> (idx);
947 assert (CUI->getType () == Type::UByteTy
948 && "Funny-looking structure index in GEP");
949 // Use the TargetData structure to pick out what the layout of
950 // the structure is in memory. Since the structure index must
951 // be constant, we can get its value and use it to find the
952 // right byte offset from the StructLayout class's list of
953 // structure member offsets.
954 unsigned idxValue = CUI->getValue ();
955 unsigned memberOffset =
956 TD.getStructLayout (StTy)->MemberOffsets[idxValue];
957 // Emit an ADD to add memberOffset to the basePtr.
958 BMI(MBB, IP, X86::ADDri32, 2,
959 nextBasePtrReg).addReg (basePtrReg).addZImm (memberOffset);
960 // The next type is the member of the structure selected by the
962 Ty = StTy->getElementTypes ()[idxValue];
963 } else if (const SequentialType *SqTy = cast <SequentialType> (Ty)) {
964 // It's an array or pointer access: [ArraySize x ElementType].
965 const Type *typeOfSequentialTypeIndex = SqTy->getIndexType ();
966 // idx is the index into the array. Unlike with structure
967 // indices, we may not know its actual value at code-generation
969 assert (idx->getType () == typeOfSequentialTypeIndex
970 && "Funny-looking array index in GEP");
971 // We want to add basePtrReg to (idxReg * sizeof
972 // ElementType). First, we must find the size of the pointed-to
973 // type. (Not coincidentally, the next type is the type of the
974 // elements in the array.)
975 Ty = SqTy->getElementType ();
976 unsigned elementSize = TD.getTypeSize (Ty);
977 unsigned elementSizeReg = makeAnotherReg(typeOfSequentialTypeIndex);
978 copyConstantToRegister(ConstantSInt::get(typeOfSequentialTypeIndex,
979 elementSize), elementSizeReg,
982 unsigned idxReg = getReg(idx, BB, IP);
983 // Emit a MUL to multiply the register holding the index by
984 // elementSize, putting the result in memberOffsetReg.
985 unsigned memberOffsetReg = makeAnotherReg(Type::UIntTy);
986 doMultiply (memberOffsetReg, typeOfSequentialTypeIndex,
987 elementSizeReg, idxReg, BB, IP);
988 // Emit an ADD to add memberOffsetReg to the basePtr.
989 BMI(MBB, IP, X86::ADDrr32, 2,
990 nextBasePtrReg).addReg (basePtrReg).addReg (memberOffsetReg);
992 // Now that we are here, further indices refer to subtypes of this
993 // one, so we don't need to worry about basePtrReg itself, anymore.
994 basePtrReg = nextBasePtrReg;
996 // After we have processed all the indices, the result is left in
997 // basePtrReg. Move it to the register where we were expected to
998 // put the answer. A 32-bit move should do it, because we are in
1000 BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg (basePtrReg);
1004 /// visitMallocInst - I know that personally, whenever I want to remember
1005 /// something, I have to clear off some space in my brain.
1007 ISel::visitMallocInst (MallocInst &I)
1009 // We assume that by this point, malloc instructions have been
1010 // lowered to calls, and dlsym will magically find malloc for us.
1011 // So we do not want to see malloc instructions here.
1012 visitInstruction (I);
1016 /// visitFreeInst - same story as MallocInst
1018 ISel::visitFreeInst (FreeInst &I)
1020 // We assume that by this point, free instructions have been
1021 // lowered to calls, and dlsym will magically find free for us.
1022 // So we do not want to see free instructions here.
1023 visitInstruction (I);
1027 /// visitAllocaInst - I want some stack space. Come on, man, I said I
1028 /// want some freakin' stack space.
1030 ISel::visitAllocaInst (AllocaInst &I)
1032 // Find the data size of the alloca inst's getAllocatedType.
1033 const Type *allocatedType = I.getAllocatedType ();
1034 const TargetData &TD = TM.DataLayout;
1035 unsigned allocatedTypeSize = TD.getTypeSize (allocatedType);
1036 // Keep stack 32-bit aligned.
1037 unsigned int allocatedTypeWords = allocatedTypeSize / 4;
1038 if (allocatedTypeSize % 4 != 0) { allocatedTypeWords++; }
1039 // Subtract size from stack pointer, thereby allocating some space.
1040 BuildMI (BB, X86::SUBri32, 1, X86::ESP).addZImm (allocatedTypeWords * 4);
1041 // Put a pointer to the space into the result register, by copying
1042 // the stack pointer.
1043 BuildMI (BB, X86::MOVrr32, 1, getReg (I)).addReg (X86::ESP);
1047 /// createSimpleX86InstructionSelector - This pass converts an LLVM function
1048 /// into a machine code representation is a very simple peep-hole fashion. The
1049 /// generated code sucks but the implementation is nice and simple.
1051 Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1052 return new ISel(TM);