1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
3 // This file defines a simple peephole instruction selector for the x86 target
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/CodeGen/SSARegMap.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/InstVisitor.h"
27 #include "llvm/Target/MRegisterInfo.h"
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 assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
39 MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
40 I = MBB->insert(I, MI)+1;
41 return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
44 /// BMI - A special BuildMI variant that takes an iterator to insert the
45 /// instruction at as well as a basic block.
46 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
47 MachineBasicBlock::iterator &I,
49 unsigned NumOperands) {
50 assert(I > MBB->begin() && I <= MBB->end() && "Bad iterator!");
51 MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
52 I = MBB->insert(I, MI)+1;
53 return MachineInstrBuilder(MI);
58 struct ISel : public FunctionPass, InstVisitor<ISel> {
60 MachineFunction *F; // The function we are compiling into
61 MachineBasicBlock *BB; // The current MBB we are compiling
63 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
65 // MBBMap - Mapping between LLVM BB -> Machine BB
66 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
68 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
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 // Create all of the machine basic blocks for the function...
77 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
78 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
81 LoadArgumentsToVirtualRegs(Fn);
83 // Instruction select everything except PHI nodes
86 // Select the PHI nodes
92 return false; // We never modify the LLVM itself.
95 virtual const char *getPassName() const {
96 return "X86 Simple Instruction Selection";
99 /// visitBasicBlock - This method is called when we are visiting a new basic
100 /// block. This simply creates a new MachineBasicBlock to emit code into
101 /// and adds it to the current MachineFunction. Subsequent visit* for
102 /// instructions will be invoked for all instructions in the basic block.
104 void visitBasicBlock(BasicBlock &LLVM_BB) {
105 BB = MBBMap[&LLVM_BB];
108 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
109 /// from the stack into virtual registers.
111 void LoadArgumentsToVirtualRegs(Function &F);
113 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
114 /// because we have to generate our sources into the source basic blocks,
115 /// not the current one.
117 void SelectPHINodes();
119 // Visitation methods for various instructions. These methods simply emit
120 // fixed X86 code for each instruction.
123 // Control flow operators
124 void visitReturnInst(ReturnInst &RI);
125 void visitBranchInst(BranchInst &BI);
130 ValueRecord(unsigned R, const Type *T) : Reg(R), Ty(T) {}
132 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
133 const std::vector<ValueRecord> &Args);
134 void visitCallInst(CallInst &I);
136 // Arithmetic operators
137 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
138 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
139 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
140 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
141 unsigned DestReg, const Type *DestTy,
142 unsigned Op0Reg, unsigned Op1Reg);
143 void visitMul(BinaryOperator &B);
145 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
146 void visitRem(BinaryOperator &B) { visitDivRem(B); }
147 void visitDivRem(BinaryOperator &B);
150 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
151 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
152 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
154 // Comparison operators...
155 void visitSetCondInst(SetCondInst &I);
156 bool EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1);
158 // Memory Instructions
159 MachineInstr *doFPLoad(MachineBasicBlock *MBB,
160 MachineBasicBlock::iterator &MBBI,
161 const Type *Ty, unsigned DestReg);
162 void visitLoadInst(LoadInst &I);
163 void doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg);
164 void visitStoreInst(StoreInst &I);
165 void visitGetElementPtrInst(GetElementPtrInst &I);
166 void visitAllocaInst(AllocaInst &I);
167 void visitMallocInst(MallocInst &I);
168 void visitFreeInst(FreeInst &I);
171 void visitShiftInst(ShiftInst &I);
172 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
173 void visitCastInst(CastInst &I);
175 void visitInstruction(Instruction &I) {
176 std::cerr << "Cannot instruction select: " << I;
180 /// promote32 - Make a value 32-bits wide, and put it somewhere.
182 void promote32(unsigned targetReg, const ValueRecord &VR);
184 /// EmitByteSwap - Byteswap SrcReg into DestReg.
186 void EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class);
188 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
189 /// constant expression GEP support.
191 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
192 Value *Src, User::op_iterator IdxBegin,
193 User::op_iterator IdxEnd, unsigned TargetReg);
195 /// copyConstantToRegister - Output the instructions required to put the
196 /// specified constant into the specified register.
198 void copyConstantToRegister(MachineBasicBlock *MBB,
199 MachineBasicBlock::iterator &MBBI,
200 Constant *C, unsigned Reg);
202 /// makeAnotherReg - This method returns the next register number we haven't
205 /// Long values are handled somewhat specially. They are always allocated
206 /// as pairs of 32 bit integer values. The register number returned is the
207 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
208 /// of the long value.
210 unsigned makeAnotherReg(const Type *Ty) {
211 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
212 const TargetRegisterClass *RC =
213 TM.getRegisterInfo()->getRegClassForType(Type::IntTy);
214 // Create the lower part
215 F->getSSARegMap()->createVirtualRegister(RC);
216 // Create the upper part.
217 return F->getSSARegMap()->createVirtualRegister(RC)-1;
220 // Add the mapping of regnumber => reg class to MachineFunction
221 const TargetRegisterClass *RC =
222 TM.getRegisterInfo()->getRegClassForType(Ty);
223 return F->getSSARegMap()->createVirtualRegister(RC);
226 /// getReg - This method turns an LLVM value into a register number. This
227 /// is guaranteed to produce the same register number for a particular value
228 /// every time it is queried.
230 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
231 unsigned getReg(Value *V) {
232 // Just append to the end of the current bb.
233 MachineBasicBlock::iterator It = BB->end();
234 return getReg(V, BB, It);
236 unsigned getReg(Value *V, MachineBasicBlock *MBB,
237 MachineBasicBlock::iterator &IPt) {
238 unsigned &Reg = RegMap[V];
240 Reg = makeAnotherReg(V->getType());
244 // If this operand is a constant, emit the code to copy the constant into
245 // the register here...
247 if (Constant *C = dyn_cast<Constant>(V)) {
248 copyConstantToRegister(MBB, IPt, C, Reg);
249 RegMap.erase(V); // Assign a new name to this constant if ref'd again
250 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
251 // Move the address of the global into the register
252 BMI(MBB, IPt, X86::MOVir32, 1, Reg).addGlobalAddress(GV);
253 RegMap.erase(V); // Assign a new name to this address if ref'd again
261 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
265 cByte, cShort, cInt, cFP, cLong
268 /// getClass - Turn a primitive type into a "class" number which is based on the
269 /// size of the type, and whether or not it is floating point.
271 static inline TypeClass getClass(const Type *Ty) {
272 switch (Ty->getPrimitiveID()) {
273 case Type::SByteTyID:
274 case Type::UByteTyID: return cByte; // Byte operands are class #0
275 case Type::ShortTyID:
276 case Type::UShortTyID: return cShort; // Short operands are class #1
279 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
281 case Type::FloatTyID:
282 case Type::DoubleTyID: return cFP; // Floating Point is #3
285 case Type::ULongTyID: return cLong; // Longs are class #4
287 assert(0 && "Invalid type to getClass!");
288 return cByte; // not reached
292 // getClassB - Just like getClass, but treat boolean values as bytes.
293 static inline TypeClass getClassB(const Type *Ty) {
294 if (Ty == Type::BoolTy) return cByte;
299 /// copyConstantToRegister - Output the instructions required to put the
300 /// specified constant into the specified register.
302 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
303 MachineBasicBlock::iterator &IP,
304 Constant *C, unsigned R) {
305 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
306 if (CE->getOpcode() == Instruction::GetElementPtr) {
307 emitGEPOperation(MBB, IP, CE->getOperand(0),
308 CE->op_begin()+1, CE->op_end(), R);
312 std::cerr << "Offending expr: " << C << "\n";
313 assert(0 && "Constant expressions not yet handled!\n");
316 if (C->getType()->isIntegral()) {
317 unsigned Class = getClassB(C->getType());
319 if (Class == cLong) {
320 // Copy the value into the register pair.
322 if (C->getType()->isSigned())
323 Val = cast<ConstantSInt>(C)->getValue();
325 Val = cast<ConstantUInt>(C)->getValue();
327 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(Val & 0xFFFFFFFF);
328 BMI(MBB, IP, X86::MOVir32, 1, R+1).addZImm(Val >> 32);
332 assert(Class <= cInt && "Type not handled yet!");
334 static const unsigned IntegralOpcodeTab[] = {
335 X86::MOVir8, X86::MOVir16, X86::MOVir32
338 if (C->getType() == Type::BoolTy) {
339 BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
340 } else if (C->getType()->isSigned()) {
341 ConstantSInt *CSI = cast<ConstantSInt>(C);
342 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CSI->getValue());
344 ConstantUInt *CUI = cast<ConstantUInt>(C);
345 BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
347 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
348 double Value = CFP->getValue();
350 BMI(MBB, IP, X86::FLD0, 0, R);
351 else if (Value == +1.0)
352 BMI(MBB, IP, X86::FLD1, 0, R);
354 // Otherwise we need to spill the constant to memory...
355 MachineConstantPool *CP = F->getConstantPool();
356 unsigned CPI = CP->getConstantPoolIndex(CFP);
357 addConstantPoolReference(doFPLoad(MBB, IP, CFP->getType(), R), CPI);
360 } else if (isa<ConstantPointerNull>(C)) {
361 // Copy zero (null pointer) to the register.
362 BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
363 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
364 unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
365 BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
367 std::cerr << "Offending constant: " << C << "\n";
368 assert(0 && "Type not handled yet!");
372 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
373 /// the stack into virtual registers.
375 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
376 // Emit instructions to load the arguments... On entry to a function on the
377 // X86, the stack frame looks like this:
379 // [ESP] -- return address
380 // [ESP + 4] -- first argument (leftmost lexically)
381 // [ESP + 8] -- second argument, if first argument is four bytes in size
384 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
385 MachineFrameInfo *MFI = F->getFrameInfo();
387 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
388 unsigned Reg = getReg(*I);
390 int FI; // Frame object index
391 switch (getClassB(I->getType())) {
393 FI = MFI->CreateFixedObject(1, ArgOffset);
394 addFrameReference(BuildMI(BB, X86::MOVmr8, 4, Reg), FI);
397 FI = MFI->CreateFixedObject(2, ArgOffset);
398 addFrameReference(BuildMI(BB, X86::MOVmr16, 4, Reg), FI);
401 FI = MFI->CreateFixedObject(4, ArgOffset);
402 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
405 FI = MFI->CreateFixedObject(8, ArgOffset);
406 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg), FI);
407 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, Reg+1), FI, 4);
408 ArgOffset += 4; // longs require 4 additional bytes
412 if (I->getType() == Type::FloatTy) {
413 Opcode = X86::FLDr32;
414 FI = MFI->CreateFixedObject(4, ArgOffset);
416 Opcode = X86::FLDr64;
417 FI = MFI->CreateFixedObject(8, ArgOffset);
418 ArgOffset += 4; // doubles require 4 additional bytes
420 addFrameReference(BuildMI(BB, Opcode, 4, Reg), FI);
423 assert(0 && "Unhandled argument type!");
425 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
430 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
431 /// because we have to generate our sources into the source basic blocks, not
434 void ISel::SelectPHINodes() {
435 const TargetInstrInfo &TII = TM.getInstrInfo();
436 const Function &LF = *F->getFunction(); // The LLVM function...
437 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
438 const BasicBlock *BB = I;
439 MachineBasicBlock *MBB = MBBMap[I];
441 // Loop over all of the PHI nodes in the LLVM basic block...
442 unsigned NumPHIs = 0;
443 for (BasicBlock::const_iterator I = BB->begin();
444 PHINode *PN = (PHINode*)dyn_cast<PHINode>(&*I); ++I) {
446 // Create a new machine instr PHI node, and insert it.
447 unsigned PHIReg = getReg(*PN);
448 MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
449 MBB->insert(MBB->begin()+NumPHIs++, PhiMI);
451 MachineInstr *LongPhiMI = 0;
452 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
453 LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
454 MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
457 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
458 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
460 // Get the incoming value into a virtual register. If it is not already
461 // available in a virtual register, insert the computation code into
464 MachineBasicBlock::iterator PI = PredMBB->end();
465 while (PI != PredMBB->begin() &&
466 TII.isTerminatorInstr((*(PI-1))->getOpcode()))
468 unsigned ValReg = getReg(PN->getIncomingValue(i), PredMBB, PI);
469 PhiMI->addRegOperand(ValReg);
470 PhiMI->addMachineBasicBlockOperand(PredMBB);
472 LongPhiMI->addRegOperand(ValReg+1);
473 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
480 // canFoldSetCCIntoBranch - Return the setcc instruction if we can fold it into
481 // the conditional branch instruction which is the only user of the cc
482 // instruction. This is the case if the conditional branch is the only user of
483 // the setcc, and if the setcc is in the same basic block as the conditional
484 // branch. We also don't handle long arguments below, so we reject them here as
487 static SetCondInst *canFoldSetCCIntoBranch(Value *V) {
488 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
489 if (SCI->use_size() == 1 && isa<BranchInst>(SCI->use_back()) &&
490 SCI->getParent() == cast<BranchInst>(SCI->use_back())->getParent()) {
491 const Type *Ty = SCI->getOperand(0)->getType();
492 if (Ty != Type::LongTy && Ty != Type::ULongTy)
498 // Return a fixed numbering for setcc instructions which does not depend on the
499 // order of the opcodes.
501 static unsigned getSetCCNumber(unsigned Opcode) {
503 default: assert(0 && "Unknown setcc instruction!");
504 case Instruction::SetEQ: return 0;
505 case Instruction::SetNE: return 1;
506 case Instruction::SetLT: return 2;
507 case Instruction::SetGE: return 3;
508 case Instruction::SetGT: return 4;
509 case Instruction::SetLE: return 5;
513 // LLVM -> X86 signed X86 unsigned
514 // ----- ---------- ------------
515 // seteq -> sete sete
516 // setne -> setne setne
517 // setlt -> setl setb
518 // setge -> setge setae
519 // setgt -> setg seta
520 // setle -> setle setbe
521 static const unsigned SetCCOpcodeTab[2][6] = {
522 {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr},
523 {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr},
526 bool ISel::EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1) {
528 // The arguments are already supposed to be of the same type.
529 const Type *CompTy = Op0->getType();
530 bool isSigned = CompTy->isSigned();
531 unsigned reg1 = getReg(Op0);
532 unsigned reg2 = getReg(Op1);
534 unsigned Class = getClassB(CompTy);
536 default: assert(0 && "Unknown type class!");
537 // Emit: cmp <var1>, <var2> (do the comparison). We can
538 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
541 BuildMI(BB, X86::CMPrr8, 2).addReg(reg1).addReg(reg2);
544 BuildMI(BB, X86::CMPrr16, 2).addReg(reg1).addReg(reg2);
547 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
550 BuildMI(BB, X86::FpUCOM, 2).addReg(reg1).addReg(reg2);
551 BuildMI(BB, X86::FNSTSWr8, 0);
552 BuildMI(BB, X86::SAHF, 1);
553 isSigned = false; // Compare with unsigned operators
557 if (OpNum < 2) { // seteq, setne
558 unsigned LoTmp = makeAnotherReg(Type::IntTy);
559 unsigned HiTmp = makeAnotherReg(Type::IntTy);
560 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
561 BuildMI(BB, X86::XORrr32, 2, LoTmp).addReg(reg1).addReg(reg2);
562 BuildMI(BB, X86::XORrr32, 2, HiTmp).addReg(reg1+1).addReg(reg2+1);
563 BuildMI(BB, X86::ORrr32, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
564 break; // Allow the sete or setne to be generated from flags set by OR
566 // Emit a sequence of code which compares the high and low parts once
567 // each, then uses a conditional move to handle the overflow case. For
568 // example, a setlt for long would generate code like this:
570 // AL = lo(op1) < lo(op2) // Signedness depends on operands
571 // BL = hi(op1) < hi(op2) // Always unsigned comparison
572 // dest = hi(op1) == hi(op2) ? AL : BL;
575 // FIXME: This would be much better if we had hierarchical register
576 // classes! Until then, hardcode registers so that we can deal with their
577 // aliases (because we don't have conditional byte moves).
579 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1).addReg(reg2);
580 BuildMI(BB, SetCCOpcodeTab[0][OpNum], 0, X86::AL);
581 BuildMI(BB, X86::CMPrr32, 2).addReg(reg1+1).addReg(reg2+1);
582 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, X86::BL);
583 BuildMI(BB, X86::CMOVErr16, 2, X86::BX).addReg(X86::BX).addReg(X86::AX);
584 // NOTE: visitSetCondInst knows that the value is dumped into the BL
585 // register at this point for long values...
593 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
594 /// register, then move it to wherever the result should be.
596 void ISel::visitSetCondInst(SetCondInst &I) {
597 if (canFoldSetCCIntoBranch(&I)) return; // Fold this into a branch...
599 unsigned OpNum = getSetCCNumber(I.getOpcode());
600 unsigned DestReg = getReg(I);
601 bool isSigned = EmitComparisonGetSignedness(OpNum, I.getOperand(0),
604 if (getClassB(I.getOperand(0)->getType()) != cLong || OpNum < 2) {
605 // Handle normal comparisons with a setcc instruction...
606 BuildMI(BB, SetCCOpcodeTab[isSigned][OpNum], 0, DestReg);
608 // Handle long comparisons by copying the value which is already in BL into
609 // the register we want...
610 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(X86::BL);
614 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
615 /// operand, in the specified target register.
616 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
617 bool isUnsigned = VR.Ty->isUnsigned();
618 switch (getClassB(VR.Ty)) {
620 // Extend value into target register (8->32)
622 BuildMI(BB, X86::MOVZXr32r8, 1, targetReg).addReg(VR.Reg);
624 BuildMI(BB, X86::MOVSXr32r8, 1, targetReg).addReg(VR.Reg);
627 // Extend value into target register (16->32)
629 BuildMI(BB, X86::MOVZXr32r16, 1, targetReg).addReg(VR.Reg);
631 BuildMI(BB, X86::MOVSXr32r16, 1, targetReg).addReg(VR.Reg);
634 // Move value into target register (32->32)
635 BuildMI(BB, X86::MOVrr32, 1, targetReg).addReg(VR.Reg);
638 assert(0 && "Unpromotable operand class in promote32");
642 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
643 /// we have the following possibilities:
645 /// ret void: No return value, simply emit a 'ret' instruction
646 /// ret sbyte, ubyte : Extend value into EAX and return
647 /// ret short, ushort: Extend value into EAX and return
648 /// ret int, uint : Move value into EAX and return
649 /// ret pointer : Move value into EAX and return
650 /// ret long, ulong : Move value into EAX/EDX and return
651 /// ret float/double : Top of FP stack
653 void ISel::visitReturnInst(ReturnInst &I) {
654 if (I.getNumOperands() == 0) {
655 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
659 Value *RetVal = I.getOperand(0);
660 unsigned RetReg = getReg(RetVal);
661 switch (getClassB(RetVal->getType())) {
662 case cByte: // integral return values: extend or move into EAX and return
665 promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
667 case cFP: // Floats & Doubles: Return in ST(0)
668 BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
671 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
672 BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
677 // Emit a 'ret' instruction
678 BuildMI(BB, X86::RET, 0);
681 // getBlockAfter - Return the basic block which occurs lexically after the
683 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
684 Function::iterator I = BB; ++I; // Get iterator to next block
685 return I != BB->getParent()->end() ? &*I : 0;
688 /// visitBranchInst - Handle conditional and unconditional branches here. Note
689 /// that since code layout is frozen at this point, that if we are trying to
690 /// jump to a block that is the immediate successor of the current block, we can
691 /// just make a fall-through (but we don't currently).
693 void ISel::visitBranchInst(BranchInst &BI) {
694 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
696 if (!BI.isConditional()) { // Unconditional branch?
697 if (BI.getSuccessor(0) != NextBB)
698 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
702 // See if we can fold the setcc into the branch itself...
703 SetCondInst *SCI = canFoldSetCCIntoBranch(BI.getCondition());
705 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
706 // computed some other way...
707 unsigned condReg = getReg(BI.getCondition());
708 BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
709 if (BI.getSuccessor(1) == NextBB) {
710 if (BI.getSuccessor(0) != NextBB)
711 BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
713 BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
715 if (BI.getSuccessor(0) != NextBB)
716 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
721 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
722 bool isSigned = EmitComparisonGetSignedness(OpNum, SCI->getOperand(0),
725 // LLVM -> X86 signed X86 unsigned
726 // ----- ---------- ------------
733 static const unsigned OpcodeTab[2][6] = {
734 { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE },
735 { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE },
738 if (BI.getSuccessor(0) != NextBB) {
739 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
740 if (BI.getSuccessor(1) != NextBB)
741 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
743 // Change to the inverse condition...
744 if (BI.getSuccessor(1) != NextBB) {
746 BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
752 /// doCall - This emits an abstract call instruction, setting up the arguments
753 /// and the return value as appropriate. For the actual function call itself,
754 /// it inserts the specified CallMI instruction into the stream.
756 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
757 const std::vector<ValueRecord> &Args) {
759 // Count how many bytes are to be pushed on the stack...
760 unsigned NumBytes = 0;
763 for (unsigned i = 0, e = Args.size(); i != e; ++i)
764 switch (getClassB(Args[i].Ty)) {
765 case cByte: case cShort: case cInt:
766 NumBytes += 4; break;
768 NumBytes += 8; break;
770 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
772 default: assert(0 && "Unknown class!");
775 // Adjust the stack pointer for the new arguments...
776 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(NumBytes);
778 // Arguments go on the stack in reverse order, as specified by the ABI.
779 unsigned ArgOffset = 0;
780 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
781 unsigned ArgReg = Args[i].Reg;
782 switch (getClassB(Args[i].Ty)) {
785 // Promote arg to 32 bits wide into a temporary register...
786 unsigned R = makeAnotherReg(Type::UIntTy);
787 promote32(R, Args[i]);
788 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
789 X86::ESP, ArgOffset).addReg(R);
793 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
794 X86::ESP, ArgOffset).addReg(ArgReg);
797 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
798 X86::ESP, ArgOffset).addReg(ArgReg);
799 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
800 X86::ESP, ArgOffset+4).addReg(ArgReg+1);
801 ArgOffset += 4; // 8 byte entry, not 4.
805 if (Args[i].Ty == Type::FloatTy) {
806 addRegOffset(BuildMI(BB, X86::FSTr32, 5),
807 X86::ESP, ArgOffset).addReg(ArgReg);
809 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
810 addRegOffset(BuildMI(BB, X86::FSTr64, 5),
811 X86::ESP, ArgOffset).addReg(ArgReg);
812 ArgOffset += 4; // 8 byte entry, not 4.
816 default: assert(0 && "Unknown class!");
821 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addZImm(0);
824 BB->push_back(CallMI);
826 BuildMI(BB, X86::ADJCALLSTACKUP, 1).addZImm(NumBytes);
828 // If there is a return value, scavenge the result from the location the call
831 if (Ret.Ty != Type::VoidTy) {
832 unsigned DestClass = getClassB(Ret.Ty);
837 // Integral results are in %eax, or the appropriate portion
839 static const unsigned regRegMove[] = {
840 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
842 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
843 BuildMI(BB, regRegMove[DestClass], 1, Ret.Reg).addReg(AReg[DestClass]);
846 case cFP: // Floating-point return values live in %ST(0)
847 BuildMI(BB, X86::FpGETRESULT, 1, Ret.Reg);
849 case cLong: // Long values are left in EDX:EAX
850 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg).addReg(X86::EAX);
851 BuildMI(BB, X86::MOVrr32, 1, Ret.Reg+1).addReg(X86::EDX);
853 default: assert(0 && "Unknown class!");
859 /// visitCallInst - Push args on stack and do a procedure call instruction.
860 void ISel::visitCallInst(CallInst &CI) {
861 MachineInstr *TheCall;
862 if (Function *F = CI.getCalledFunction()) {
863 // Emit a CALL instruction with PC-relative displacement.
864 TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
865 } else { // Emit an indirect call...
866 unsigned Reg = getReg(CI.getCalledValue());
867 TheCall = BuildMI(X86::CALLr32, 1).addReg(Reg);
870 std::vector<ValueRecord> Args;
871 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
872 Args.push_back(ValueRecord(getReg(CI.getOperand(i)),
873 CI.getOperand(i)->getType()));
875 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
876 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
880 /// visitSimpleBinary - Implement simple binary operators for integral types...
881 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
884 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
885 unsigned Class = getClassB(B.getType());
887 static const unsigned OpcodeTab[][4] = {
888 // Arithmetic operators
889 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, X86::FpADD }, // ADD
890 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, X86::FpSUB }, // SUB
893 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
894 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
895 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
899 if (Class == cLong) {
901 Class = cInt; // Bottom 32 bits are handled just like ints
904 unsigned Opcode = OpcodeTab[OperatorClass][Class];
905 assert(Opcode && "Floating point arguments to logical inst?");
906 unsigned Op0r = getReg(B.getOperand(0));
907 unsigned Op1r = getReg(B.getOperand(1));
908 unsigned DestReg = getReg(B);
909 BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
911 if (isLong) { // Handle the upper 32 bits of long values...
912 static const unsigned TopTab[] = {
913 X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
915 BuildMI(BB, TopTab[OperatorClass], 2,
916 DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
920 /// doMultiply - Emit appropriate instructions to multiply together the
921 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
922 /// result should be given as DestTy.
924 /// FIXME: doMultiply should use one of the two address IMUL instructions!
926 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI,
927 unsigned DestReg, const Type *DestTy,
928 unsigned op0Reg, unsigned op1Reg) {
929 unsigned Class = getClass(DestTy);
931 case cFP: // Floating point multiply
932 BMI(BB, MBBI, X86::FpMUL, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
935 case cLong: assert(0 && "doMultiply cannot operate on LONG values!");
938 case cInt: // Small integerals, handled below...
942 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
943 static const unsigned MulOpcode[]={ X86::MULr8 , X86::MULr16 , X86::MULr32 };
944 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
945 unsigned Reg = Regs[Class];
947 // Emit a MOV to put the first operand into the appropriately-sized
949 BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg(op0Reg);
951 // Emit the appropriate multiply instruction.
952 BMI(MBB, MBBI, MulOpcode[Class], 1).addReg(op1Reg);
954 // Emit another MOV to put the result into the destination register.
955 BMI(MBB, MBBI, MovOpcode[Class], 1, DestReg).addReg(Reg);
958 /// visitMul - Multiplies are not simple binary operators because they must deal
959 /// with the EAX register explicitly.
961 void ISel::visitMul(BinaryOperator &I) {
962 unsigned Op0Reg = getReg(I.getOperand(0));
963 unsigned Op1Reg = getReg(I.getOperand(1));
964 unsigned DestReg = getReg(I);
966 // Simple scalar multiply?
967 if (I.getType() != Type::LongTy && I.getType() != Type::ULongTy) {
968 MachineBasicBlock::iterator MBBI = BB->end();
969 doMultiply(BB, MBBI, DestReg, I.getType(), Op0Reg, Op1Reg);
971 // Long value. We have to do things the hard way...
972 // Multiply the two low parts... capturing carry into EDX
973 BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(Op0Reg);
974 BuildMI(BB, X86::MULr32, 1).addReg(Op1Reg); // AL*BL
976 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
977 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(X86::EAX); // AL*BL
978 BuildMI(BB, X86::MOVrr32, 1, OverflowReg).addReg(X86::EDX); // AL*BL >> 32
980 MachineBasicBlock::iterator MBBI = BB->end();
981 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
982 doMultiply(BB, MBBI, AHBLReg, Type::UIntTy, Op0Reg+1, Op1Reg); // AH*BL
984 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
985 BuildMI(BB, X86::ADDrr32, 2, // AH*BL+(AL*BL >> 32)
986 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
989 unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
990 doMultiply(BB, MBBI, ALBHReg, Type::UIntTy, Op0Reg, Op1Reg+1); // AL*BH
992 BuildMI(BB, X86::ADDrr32, 2, // AL*BH + AH*BL + (AL*BL >> 32)
993 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
998 /// visitDivRem - Handle division and remainder instructions... these
999 /// instruction both require the same instructions to be generated, they just
1000 /// select the result from a different register. Note that both of these
1001 /// instructions work differently for signed and unsigned operands.
1003 void ISel::visitDivRem(BinaryOperator &I) {
1004 unsigned Class = getClass(I.getType());
1005 unsigned Op0Reg = getReg(I.getOperand(0));
1006 unsigned Op1Reg = getReg(I.getOperand(1));
1007 unsigned ResultReg = getReg(I);
1010 case cFP: // Floating point divide
1011 if (I.getOpcode() == Instruction::Div)
1012 BuildMI(BB, X86::FpDIV, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
1013 else { // Floating point remainder...
1014 MachineInstr *TheCall =
1015 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol("fmod", true);
1016 std::vector<ValueRecord> Args;
1017 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1018 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1019 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1023 static const char *FnName[] =
1024 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1026 unsigned NameIdx = I.getType()->isUnsigned()*2;
1027 NameIdx += I.getOpcode() == Instruction::Div;
1028 MachineInstr *TheCall =
1029 BuildMI(X86::CALLpcrel32, 1).addExternalSymbol(FnName[NameIdx], true);
1031 std::vector<ValueRecord> Args;
1032 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1033 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1034 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1037 case cByte: case cShort: case cInt:
1038 break; // Small integerals, handled below...
1039 default: assert(0 && "Unknown class!");
1042 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
1043 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
1044 static const unsigned ExtOpcode[]={ X86::CBW , X86::CWD , X86::CDQ };
1045 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
1046 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
1048 static const unsigned DivOpcode[][4] = {
1049 { X86::DIVr8 , X86::DIVr16 , X86::DIVr32 , 0 }, // Unsigned division
1050 { X86::IDIVr8, X86::IDIVr16, X86::IDIVr32, 0 }, // Signed division
1053 bool isSigned = I.getType()->isSigned();
1054 unsigned Reg = Regs[Class];
1055 unsigned ExtReg = ExtRegs[Class];
1057 // Put the first operand into one of the A registers...
1058 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
1061 // Emit a sign extension instruction...
1062 BuildMI(BB, ExtOpcode[Class], 0);
1064 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
1065 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
1068 // Emit the appropriate divide or remainder instruction...
1069 BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
1071 // Figure out which register we want to pick the result out of...
1072 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
1074 // Put the result into the destination register...
1075 BuildMI(BB, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
1079 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
1080 /// for constant immediate shift values, and for constant immediate
1081 /// shift values equal to 1. Even the general case is sort of special,
1082 /// because the shift amount has to be in CL, not just any old register.
1084 void ISel::visitShiftInst(ShiftInst &I) {
1085 unsigned SrcReg = getReg(I.getOperand(0));
1086 unsigned DestReg = getReg(I);
1087 bool isLeftShift = I.getOpcode() == Instruction::Shl;
1088 bool isSigned = I.getType()->isSigned();
1089 unsigned Class = getClass(I.getType());
1091 static const unsigned ConstantOperand[][4] = {
1092 { X86::SHRir8, X86::SHRir16, X86::SHRir32, X86::SHRDir32 }, // SHR
1093 { X86::SARir8, X86::SARir16, X86::SARir32, X86::SHRDir32 }, // SAR
1094 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SHL
1095 { X86::SHLir8, X86::SHLir16, X86::SHLir32, X86::SHLDir32 }, // SAL = SHL
1098 static const unsigned NonConstantOperand[][4] = {
1099 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32 }, // SHR
1100 { X86::SARrr8, X86::SARrr16, X86::SARrr32 }, // SAR
1101 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SHL
1102 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32 }, // SAL = SHL
1105 // Longs, as usual, are handled specially...
1106 if (Class == cLong) {
1107 // If we have a constant shift, we can generate much more efficient code
1108 // than otherwise...
1110 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1111 unsigned Amount = CUI->getValue();
1113 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1115 BuildMI(BB, Opc[3], 3,
1116 DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addZImm(Amount);
1117 BuildMI(BB, Opc[2], 2, DestReg).addReg(SrcReg).addZImm(Amount);
1119 BuildMI(BB, Opc[3], 3,
1120 DestReg).addReg(SrcReg ).addReg(SrcReg+1).addZImm(Amount);
1121 BuildMI(BB, Opc[2], 2, DestReg+1).addReg(SrcReg+1).addZImm(Amount);
1123 } else { // Shifting more than 32 bits
1126 BuildMI(BB, X86::SHLir32, 2,DestReg+1).addReg(SrcReg).addZImm(Amount);
1127 BuildMI(BB, X86::MOVir32, 1,DestReg ).addZImm(0);
1129 unsigned Opcode = isSigned ? X86::SARir32 : X86::SHRir32;
1130 BuildMI(BB, Opcode, 2, DestReg).addReg(SrcReg+1).addZImm(Amount);
1131 BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1135 visitInstruction(I); // FIXME: Implement long shift by non-constant
1140 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getOperand(1))) {
1141 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
1142 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
1144 const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
1145 BuildMI(BB, Opc[Class], 2, DestReg).addReg(SrcReg).addZImm(CUI->getValue());
1146 } else { // The shift amount is non-constant.
1147 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
1149 const unsigned *Opc = NonConstantOperand[isLeftShift*2+isSigned];
1150 BuildMI(BB, Opc[Class], 1, DestReg).addReg(SrcReg);
1155 /// doFPLoad - This method is used to load an FP value from memory using the
1156 /// current endianness. NOTE: This method returns a partially constructed load
1157 /// instruction which needs to have the memory source filled in still.
1159 MachineInstr *ISel::doFPLoad(MachineBasicBlock *MBB,
1160 MachineBasicBlock::iterator &MBBI,
1161 const Type *Ty, unsigned DestReg) {
1162 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1163 unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLDr32 : X86::FLDr64;
1165 if (TM.getTargetData().isLittleEndian()) // fast path...
1166 return BMI(MBB, MBBI, LoadOpcode, 4, DestReg);
1168 // If we are big-endian, start by creating an LEA instruction to represent the
1169 // address of the memory location to load from...
1171 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1172 MachineInstr *Result = BMI(MBB, MBBI, X86::LEAr32, 5, SrcAddrReg);
1174 // Allocate a temporary stack slot to transform the value into...
1175 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1177 // Perform the bswaps 32 bits at a time...
1178 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1179 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1180 addDirectMem(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1181 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1182 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1183 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32, 5),
1184 FrameIdx, Offset).addReg(TmpReg2);
1186 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1187 TmpReg1 = makeAnotherReg(Type::UIntTy);
1188 TmpReg2 = makeAnotherReg(Type::UIntTy);
1190 addRegOffset(BMI(MBB, MBBI, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1191 BMI(MBB, MBBI, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1192 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1193 addFrameReference(BMI(MBB, MBBI, X86::MOVrm32,5), FrameIdx).addReg(TmpReg2);
1196 // Now we can reload the final byteswapped result into the final destination.
1197 addFrameReference(BMI(MBB, MBBI, LoadOpcode, 4, DestReg), FrameIdx);
1201 /// EmitByteSwap - Byteswap SrcReg into DestReg.
1203 void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
1204 // Emit the byte swap instruction...
1207 // No byteswap neccesary for 8 bit value...
1208 BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(SrcReg);
1211 // Use the 32 bit bswap instruction to do a 32 bit swap...
1212 BuildMI(BB, X86::BSWAPr32, 1, DestReg).addReg(SrcReg);
1216 // For 16 bit we have to use an xchg instruction, because there is no
1217 // 16-bit bswap. XCHG is neccesarily not in SSA form, so we force things
1218 // into AX to do the xchg.
1220 BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(SrcReg);
1221 BuildMI(BB, X86::XCHGrr8, 2).addReg(X86::AL, MOTy::UseAndDef)
1222 .addReg(X86::AH, MOTy::UseAndDef);
1223 BuildMI(BB, X86::MOVrr16, 1, DestReg).addReg(X86::AX);
1225 default: assert(0 && "Cannot byteswap this class!");
1230 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
1231 /// instruction. The load and store instructions are the only place where we
1232 /// need to worry about the memory layout of the target machine.
1234 void ISel::visitLoadInst(LoadInst &I) {
1235 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1236 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1237 unsigned SrcAddrReg = getReg(I.getOperand(0));
1238 unsigned DestReg = getReg(I);
1240 unsigned Class = getClass(I.getType());
1243 MachineBasicBlock::iterator MBBI = BB->end();
1244 addDirectMem(doFPLoad(BB, MBBI, I.getType(), DestReg), SrcAddrReg);
1247 case cLong: case cInt: case cShort: case cByte:
1248 break; // Integers of various sizes handled below
1249 default: assert(0 && "Unknown memory class!");
1252 // We need to adjust the input pointer if we are emulating a big-endian
1253 // long-pointer target. On these systems, the pointer that we are interested
1254 // in is in the upper part of the eight byte memory image of the pointer. It
1255 // also happens to be byte-swapped, but this will be handled later.
1257 if (!isLittleEndian && hasLongPointers && isa<PointerType>(I.getType())) {
1258 unsigned R = makeAnotherReg(Type::UIntTy);
1259 BuildMI(BB, X86::ADDri32, 2, R).addReg(SrcAddrReg).addZImm(4);
1263 unsigned IReg = DestReg;
1264 if (!isLittleEndian) // If big endian we need an intermediate stage
1265 DestReg = makeAnotherReg(Class != cLong ? I.getType() : Type::UIntTy);
1267 static const unsigned Opcode[] = {
1268 X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, 0, X86::MOVmr32
1270 addDirectMem(BuildMI(BB, Opcode[Class], 4, DestReg), SrcAddrReg);
1272 // Handle long values now...
1273 if (Class == cLong) {
1274 if (isLittleEndian) {
1275 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), SrcAddrReg, 4);
1277 EmitByteSwap(IReg+1, DestReg, cInt);
1278 unsigned TempReg = makeAnotherReg(Type::IntTy);
1279 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TempReg), SrcAddrReg, 4);
1280 EmitByteSwap(IReg, TempReg, cInt);
1285 if (!isLittleEndian)
1286 EmitByteSwap(IReg, DestReg, Class);
1290 /// doFPStore - This method is used to store an FP value to memory using the
1291 /// current endianness.
1293 void ISel::doFPStore(const Type *Ty, unsigned DestAddrReg, unsigned SrcReg) {
1294 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1295 unsigned StoreOpcode = Ty == Type::FloatTy ? X86::FSTr32 : X86::FSTr64;
1297 if (TM.getTargetData().isLittleEndian()) { // fast path...
1298 addDirectMem(BuildMI(BB, StoreOpcode,5), DestAddrReg).addReg(SrcReg);
1302 // Allocate a temporary stack slot to transform the value into...
1303 int FrameIdx = F->getFrameInfo()->CreateStackObject(Ty, TM.getTargetData());
1304 unsigned SrcAddrReg = makeAnotherReg(Type::UIntTy);
1305 addFrameReference(BuildMI(BB, X86::LEAr32, 5, SrcAddrReg), FrameIdx);
1307 // Store the value into a temporary stack slot...
1308 addDirectMem(BuildMI(BB, StoreOpcode, 5), SrcAddrReg).addReg(SrcReg);
1310 // Perform the bswaps 32 bits at a time...
1311 unsigned TmpReg1 = makeAnotherReg(Type::UIntTy);
1312 unsigned TmpReg2 = makeAnotherReg(Type::UIntTy);
1313 addDirectMem(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg);
1314 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1315 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1316 addRegOffset(BuildMI(BB, X86::MOVrm32, 5),
1317 DestAddrReg, Offset).addReg(TmpReg2);
1319 if (Ty == Type::DoubleTy) { // Swap the other 32 bits of a double value...
1320 TmpReg1 = makeAnotherReg(Type::UIntTy);
1321 TmpReg2 = makeAnotherReg(Type::UIntTy);
1323 addRegOffset(BuildMI(BB, X86::MOVmr32, 4, TmpReg1), SrcAddrReg, 4);
1324 BuildMI(BB, X86::BSWAPr32, 1, TmpReg2).addReg(TmpReg1);
1325 unsigned Offset = (Ty == Type::DoubleTy) << 2;
1326 addDirectMem(BuildMI(BB, X86::MOVrm32, 5), DestAddrReg).addReg(TmpReg2);
1331 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
1334 void ISel::visitStoreInst(StoreInst &I) {
1335 bool isLittleEndian = TM.getTargetData().isLittleEndian();
1336 bool hasLongPointers = TM.getTargetData().getPointerSize() == 8;
1337 unsigned ValReg = getReg(I.getOperand(0));
1338 unsigned AddressReg = getReg(I.getOperand(1));
1340 unsigned Class = getClass(I.getOperand(0)->getType());
1343 if (isLittleEndian) {
1344 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(ValReg);
1345 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4),
1346 AddressReg, 4).addReg(ValReg+1);
1348 unsigned T1 = makeAnotherReg(Type::IntTy);
1349 unsigned T2 = makeAnotherReg(Type::IntTy);
1350 EmitByteSwap(T1, ValReg , cInt);
1351 EmitByteSwap(T2, ValReg+1, cInt);
1352 addDirectMem(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg).addReg(T2);
1353 addRegOffset(BuildMI(BB, X86::MOVrm32, 1+4), AddressReg, 4).addReg(T1);
1357 doFPStore(I.getOperand(0)->getType(), AddressReg, ValReg);
1359 case cInt: case cShort: case cByte:
1360 break; // Integers of various sizes handled below
1361 default: assert(0 && "Unknown memory class!");
1364 if (!isLittleEndian && hasLongPointers &&
1365 isa<PointerType>(I.getOperand(0)->getType())) {
1366 unsigned R = makeAnotherReg(Type::UIntTy);
1367 BuildMI(BB, X86::ADDri32, 2, R).addReg(AddressReg).addZImm(4);
1371 if (!isLittleEndian && Class != cByte) {
1372 unsigned R = makeAnotherReg(I.getOperand(0)->getType());
1373 EmitByteSwap(R, ValReg, Class);
1377 static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1378 addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
1382 /// visitCastInst - Here we have various kinds of copying with or without
1383 /// sign extension going on.
1384 void ISel::visitCastInst(CastInst &CI) {
1385 const Type *DestTy = CI.getType();
1386 Value *Src = CI.getOperand(0);
1387 unsigned SrcReg = getReg(Src);
1388 const Type *SrcTy = Src->getType();
1389 unsigned SrcClass = getClassB(SrcTy);
1390 unsigned DestReg = getReg(CI);
1391 unsigned DestClass = getClassB(DestTy);
1393 // Implement casts to bool by using compare on the operand followed by set if
1394 // not zero on the result.
1395 if (DestTy == Type::BoolTy) {
1396 if (SrcClass == cFP || SrcClass == cLong)
1397 visitInstruction(CI);
1399 BuildMI(BB, X86::CMPri8, 2).addReg(SrcReg).addZImm(0);
1400 BuildMI(BB, X86::SETNEr, 1, DestReg);
1404 static const unsigned RegRegMove[] = {
1405 X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV, X86::MOVrr32
1408 // Implement casts between values of the same type class (as determined by
1409 // getClass) by using a register-to-register move.
1410 if (SrcClass == DestClass) {
1411 if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
1412 BuildMI(BB, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
1413 } else if (SrcClass == cFP) {
1414 if (SrcTy == Type::FloatTy) { // double -> float
1415 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
1416 BuildMI(BB, X86::FpMOV, 1, DestReg).addReg(SrcReg);
1417 } else { // float -> double
1418 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
1419 "Unknown cFP member!");
1420 // Truncate from double to float by storing to memory as short, then
1422 unsigned FltAlign = TM.getTargetData().getFloatAlignment();
1423 int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
1424 addFrameReference(BuildMI(BB, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
1425 addFrameReference(BuildMI(BB, X86::FLDr32, 5, DestReg), FrameIdx);
1427 } else if (SrcClass == cLong) {
1428 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1429 BuildMI(BB, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
1431 visitInstruction(CI);
1436 // Handle cast of SMALLER int to LARGER int using a move with sign extension
1437 // or zero extension, depending on whether the source type was signed.
1438 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
1439 SrcClass < DestClass) {
1440 bool isLong = DestClass == cLong;
1441 if (isLong) DestClass = cInt;
1443 static const unsigned Opc[][4] = {
1444 { X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16, X86::MOVrr32 }, // s
1445 { X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16, X86::MOVrr32 } // u
1448 bool isUnsigned = SrcTy->isUnsigned();
1449 BuildMI(BB, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
1450 DestReg).addReg(SrcReg);
1452 if (isLong) { // Handle upper 32 bits as appropriate...
1453 if (isUnsigned) // Zero out top bits...
1454 BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
1455 else // Sign extend bottom half...
1456 BuildMI(BB, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
1461 // Special case long -> int ...
1462 if (SrcClass == cLong && DestClass == cInt) {
1463 BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
1467 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
1468 // move out of AX or AL.
1469 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
1470 && SrcClass > DestClass) {
1471 static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
1472 BuildMI(BB, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
1473 BuildMI(BB, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
1477 // Handle casts from integer to floating point now...
1478 if (DestClass == cFP) {
1479 // unsigned int -> load as 64 bit int.
1480 // unsigned long long -> more complex
1481 if (SrcTy->isUnsigned() && SrcTy != Type::UByteTy)
1482 visitInstruction(CI); // don't handle unsigned src yet!
1484 // We don't have the facilities for directly loading byte sized data from
1485 // memory. Promote it to 16 bits.
1486 if (SrcClass == cByte) {
1487 unsigned TmpReg = makeAnotherReg(Type::ShortTy);
1488 BuildMI(BB, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
1489 1, TmpReg).addReg(SrcReg);
1490 SrcTy = Type::ShortTy; // Pretend the short is our input now!
1495 // Spill the integer to memory and reload it from there...
1497 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
1499 if (SrcClass == cLong) {
1500 if (SrcTy == Type::ULongTy) visitInstruction(CI);
1501 addFrameReference(BuildMI(BB, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
1502 addFrameReference(BuildMI(BB, X86::MOVrm32, 5),
1503 FrameIdx, 4).addReg(SrcReg+1);
1505 static const unsigned Op1[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
1506 addFrameReference(BuildMI(BB, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
1509 static const unsigned Op2[] =
1510 { 0, X86::FILDr16, X86::FILDr32, 0, X86::FILDr64 };
1511 addFrameReference(BuildMI(BB, Op2[SrcClass], 5, DestReg), FrameIdx);
1515 // Handle casts from floating point to integer now...
1516 if (SrcClass == cFP) {
1517 // Change the floating point control register to use "round towards zero"
1518 // mode when truncating to an integer value.
1520 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
1521 addFrameReference(BuildMI(BB, X86::FNSTCWm16, 4), CWFrameIdx);
1523 // Load the old value of the high byte of the control word...
1524 unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
1525 addFrameReference(BuildMI(BB, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
1527 // Set the high part to be round to zero...
1528 addFrameReference(BuildMI(BB, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
1530 // Reload the modified control word now...
1531 addFrameReference(BuildMI(BB, X86::FLDCWm16, 4), CWFrameIdx);
1533 // Restore the memory image of control word to original value
1534 addFrameReference(BuildMI(BB, X86::MOVrm8, 5),
1535 CWFrameIdx, 1).addReg(HighPartOfCW);
1537 // We don't have the facilities for directly storing byte sized data to
1538 // memory. Promote it to 16 bits. We also must promote unsigned values to
1539 // larger classes because we only have signed FP stores.
1540 unsigned StoreClass = DestClass;
1541 const Type *StoreTy = DestTy;
1542 if (StoreClass == cByte || DestTy->isUnsigned())
1543 switch (StoreClass) {
1544 case cByte: StoreTy = Type::ShortTy; StoreClass = cShort; break;
1545 case cShort: StoreTy = Type::IntTy; StoreClass = cInt; break;
1546 case cInt: StoreTy = Type::LongTy; StoreClass = cLong; break;
1547 case cLong: visitInstruction(CI); // unsigned long long -> more complex
1548 default: assert(0 && "Unknown store class!");
1551 // Spill the integer to memory and reload it from there...
1553 F->getFrameInfo()->CreateStackObject(StoreTy, TM.getTargetData());
1555 static const unsigned Op1[] =
1556 { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
1557 addFrameReference(BuildMI(BB, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
1559 if (DestClass == cLong) {
1560 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, DestReg), FrameIdx);
1561 addFrameReference(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
1563 static const unsigned Op2[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
1564 addFrameReference(BuildMI(BB, Op2[DestClass], 4, DestReg), FrameIdx);
1567 // Reload the original control word now...
1568 addFrameReference(BuildMI(BB, X86::FLDCWm16, 4), CWFrameIdx);
1572 // Anything we haven't handled already, we can't (yet) handle at all.
1573 visitInstruction (CI);
1576 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1577 // returns zero when the input is not exactly a power of two.
1578 static unsigned ExactLog2(unsigned Val) {
1579 if (Val == 0) return 0;
1582 if (Val & 1) return 0;
1589 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
1590 unsigned outputReg = getReg(I);
1591 MachineBasicBlock::iterator MI = BB->end();
1592 emitGEPOperation(BB, MI, I.getOperand(0),
1593 I.op_begin()+1, I.op_end(), outputReg);
1596 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
1597 MachineBasicBlock::iterator &IP,
1598 Value *Src, User::op_iterator IdxBegin,
1599 User::op_iterator IdxEnd, unsigned TargetReg) {
1600 const TargetData &TD = TM.getTargetData();
1601 const Type *Ty = Src->getType();
1602 unsigned BaseReg = getReg(Src, MBB, IP);
1604 // GEPs have zero or more indices; we must perform a struct access
1605 // or array access for each one.
1606 for (GetElementPtrInst::op_iterator oi = IdxBegin,
1607 oe = IdxEnd; oi != oe; ++oi) {
1609 unsigned NextReg = BaseReg;
1610 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1611 // It's a struct access. idx is the index into the structure,
1612 // which names the field. This index must have ubyte type.
1613 const ConstantUInt *CUI = cast<ConstantUInt>(idx);
1614 assert(CUI->getType() == Type::UByteTy
1615 && "Funny-looking structure index in GEP");
1616 // Use the TargetData structure to pick out what the layout of
1617 // the structure is in memory. Since the structure index must
1618 // be constant, we can get its value and use it to find the
1619 // right byte offset from the StructLayout class's list of
1620 // structure member offsets.
1621 unsigned idxValue = CUI->getValue();
1622 unsigned FieldOff = TD.getStructLayout(StTy)->MemberOffsets[idxValue];
1624 NextReg = makeAnotherReg(Type::UIntTy);
1625 // Emit an ADD to add FieldOff to the basePtr.
1626 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(FieldOff);
1628 // The next type is the member of the structure selected by the
1630 Ty = StTy->getElementTypes()[idxValue];
1631 } else if (const SequentialType *SqTy = cast<SequentialType>(Ty)) {
1632 // It's an array or pointer access: [ArraySize x ElementType].
1634 // idx is the index into the array. Unlike with structure
1635 // indices, we may not know its actual value at code-generation
1637 assert(idx->getType() == Type::LongTy && "Bad GEP array index!");
1639 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
1640 // must find the size of the pointed-to type (Not coincidentally, the next
1641 // type is the type of the elements in the array).
1642 Ty = SqTy->getElementType();
1643 unsigned elementSize = TD.getTypeSize(Ty);
1645 // If idxReg is a constant, we don't need to perform the multiply!
1646 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
1647 if (!CSI->isNullValue()) {
1648 unsigned Offset = elementSize*CSI->getValue();
1649 NextReg = makeAnotherReg(Type::UIntTy);
1650 BMI(MBB, IP, X86::ADDri32, 2,NextReg).addReg(BaseReg).addZImm(Offset);
1652 } else if (elementSize == 1) {
1653 // If the element size is 1, we don't have to multiply, just add
1654 unsigned idxReg = getReg(idx, MBB, IP);
1655 NextReg = makeAnotherReg(Type::UIntTy);
1656 BMI(MBB, IP, X86::ADDrr32, 2, NextReg).addReg(BaseReg).addReg(idxReg);
1658 unsigned idxReg = getReg(idx, MBB, IP);
1659 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
1660 if (unsigned Shift = ExactLog2(elementSize)) {
1661 // If the element size is exactly a power of 2, use a shift to get it.
1662 BMI(MBB, IP, X86::SHLir32, 2,
1663 OffsetReg).addReg(idxReg).addZImm(Shift-1);
1665 // Most general case, emit a multiply...
1666 unsigned elementSizeReg = makeAnotherReg(Type::LongTy);
1667 BMI(MBB, IP, X86::MOVir32, 1, elementSizeReg).addZImm(elementSize);
1669 // Emit a MUL to multiply the register holding the index by
1670 // elementSize, putting the result in OffsetReg.
1671 doMultiply(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSizeReg);
1673 // Emit an ADD to add OffsetReg to the basePtr.
1674 NextReg = makeAnotherReg(Type::UIntTy);
1675 BMI(MBB, IP, X86::ADDrr32, 2,NextReg).addReg(BaseReg).addReg(OffsetReg);
1678 // Now that we are here, further indices refer to subtypes of this
1679 // one, so we don't need to worry about BaseReg itself, anymore.
1682 // After we have processed all the indices, the result is left in
1683 // BaseReg. Move it to the register where we were expected to
1684 // put the answer. A 32-bit move should do it, because we are in
1686 BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg(BaseReg);
1690 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
1691 /// frame manager, otherwise do it the hard way.
1693 void ISel::visitAllocaInst(AllocaInst &I) {
1694 // Find the data size of the alloca inst's getAllocatedType.
1695 const Type *Ty = I.getAllocatedType();
1696 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
1698 // If this is a fixed size alloca in the entry block for the function,
1699 // statically stack allocate the space.
1701 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
1702 if (I.getParent() == I.getParent()->getParent()->begin()) {
1703 TySize *= CUI->getValue(); // Get total allocated size...
1704 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
1706 // Create a new stack object using the frame manager...
1707 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
1708 addFrameReference(BuildMI(BB, X86::LEAr32, 5, getReg(I)), FrameIdx);
1713 // Create a register to hold the temporary result of multiplying the type size
1714 // constant by the variable amount.
1715 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
1716 unsigned SrcReg1 = getReg(I.getArraySize());
1717 unsigned SizeReg = makeAnotherReg(Type::UIntTy);
1718 BuildMI(BB, X86::MOVir32, 1, SizeReg).addZImm(TySize);
1720 // TotalSizeReg = mul <numelements>, <TypeSize>
1721 MachineBasicBlock::iterator MBBI = BB->end();
1722 doMultiply(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, SizeReg);
1724 // AddedSize = add <TotalSizeReg>, 15
1725 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
1726 BuildMI(BB, X86::ADDri32, 2, AddedSizeReg).addReg(TotalSizeReg).addZImm(15);
1728 // AlignedSize = and <AddedSize>, ~15
1729 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
1730 BuildMI(BB, X86::ANDri32, 2, AlignedSize).addReg(AddedSizeReg).addZImm(~15);
1732 // Subtract size from stack pointer, thereby allocating some space.
1733 BuildMI(BB, X86::SUBrr32, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
1735 // Put a pointer to the space into the result register, by copying
1736 // the stack pointer.
1737 BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
1739 // Inform the Frame Information that we have just allocated a variable sized
1741 F->getFrameInfo()->CreateVariableSizedObject();
1744 /// visitMallocInst - Malloc instructions are code generated into direct calls
1745 /// to the library malloc.
1747 void ISel::visitMallocInst(MallocInst &I) {
1748 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
1751 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
1752 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
1754 Arg = makeAnotherReg(Type::UIntTy);
1755 unsigned Op0Reg = getReg(ConstantUInt::get(Type::UIntTy, AllocSize));
1756 unsigned Op1Reg = getReg(I.getOperand(0));
1757 MachineBasicBlock::iterator MBBI = BB->end();
1758 doMultiply(BB, MBBI, Arg, Type::UIntTy, Op0Reg, Op1Reg);
1763 std::vector<ValueRecord> Args;
1764 Args.push_back(ValueRecord(Arg, Type::UIntTy));
1765 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1766 1).addExternalSymbol("malloc", true);
1767 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
1771 /// visitFreeInst - Free instructions are code gen'd to call the free libc
1774 void ISel::visitFreeInst(FreeInst &I) {
1775 std::vector<ValueRecord> Args;
1776 Args.push_back(ValueRecord(getReg(I.getOperand(0)),
1777 I.getOperand(0)->getType()));
1778 MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
1779 1).addExternalSymbol("free", true);
1780 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
1784 /// createSimpleX86InstructionSelector - This pass converts an LLVM function
1785 /// into a machine code representation is a very simple peep-hole fashion. The
1786 /// generated code sucks but the implementation is nice and simple.
1788 Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1789 return new ISel(TM);