1 //===-- InstSelectSimple.cpp - A simple instruction selector for SparcV8 --===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a simple peephole instruction selector for the V8 target
12 //===----------------------------------------------------------------------===//
15 #include "SparcV8InstrInfo.h"
16 #include "Support/Debug.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/IntrinsicLowering.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Constants.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/SSARegMap.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/GetElementPtrTypeIterator.h"
27 #include "llvm/Support/InstVisitor.h"
28 #include "llvm/Support/CFG.h"
32 struct V8ISel : public FunctionPass, public InstVisitor<V8ISel> {
34 MachineFunction *F; // The function we are compiling into
35 MachineBasicBlock *BB; // The current MBB we are compiling
37 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
39 // MBBMap - Mapping between LLVM BB -> Machine BB
40 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
42 V8ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
44 /// runOnFunction - Top level implementation of instruction selection for
45 /// the entire function.
47 bool runOnFunction(Function &Fn);
49 virtual const char *getPassName() const {
50 return "SparcV8 Simple Instruction Selection";
53 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
54 /// constant expression GEP support.
56 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
57 Value *Src, User::op_iterator IdxBegin,
58 User::op_iterator IdxEnd, unsigned TargetReg);
60 /// visitBasicBlock - This method is called when we are visiting a new basic
61 /// block. This simply creates a new MachineBasicBlock to emit code into
62 /// and adds it to the current MachineFunction. Subsequent visit* for
63 /// instructions will be invoked for all instructions in the basic block.
65 void visitBasicBlock(BasicBlock &LLVM_BB) {
66 BB = MBBMap[&LLVM_BB];
69 void visitBinaryOperator(Instruction &I);
70 void visitShiftInst (ShiftInst &SI) { visitBinaryOperator (SI); }
71 void visitSetCondInst(Instruction &I);
72 void visitCallInst(CallInst &I);
73 void visitReturnInst(ReturnInst &I);
74 void visitBranchInst(BranchInst &I);
75 void visitCastInst(CastInst &I);
76 void visitLoadInst(LoadInst &I);
77 void visitStoreInst(StoreInst &I);
78 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
79 void visitGetElementPtrInst(GetElementPtrInst &I);
83 void visitInstruction(Instruction &I) {
84 std::cerr << "Unhandled instruction: " << I;
88 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
89 /// function, lowering any calls to unknown intrinsic functions into the
90 /// equivalent LLVM code.
91 void LowerUnknownIntrinsicFunctionCalls(Function &F);
92 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI);
94 void LoadArgumentsToVirtualRegs(Function *F);
96 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
97 /// because we have to generate our sources into the source basic blocks,
98 /// not the current one.
100 void SelectPHINodes();
102 /// copyConstantToRegister - Output the instructions required to put the
103 /// specified constant into the specified register.
105 void copyConstantToRegister(MachineBasicBlock *MBB,
106 MachineBasicBlock::iterator IP,
107 Constant *C, unsigned R);
109 /// makeAnotherReg - This method returns the next register number we haven't
112 /// Long values are handled somewhat specially. They are always allocated
113 /// as pairs of 32 bit integer values. The register number returned is the
114 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
115 /// of the long value.
117 unsigned makeAnotherReg(const Type *Ty) {
118 assert(dynamic_cast<const SparcV8RegisterInfo*>(TM.getRegisterInfo()) &&
119 "Current target doesn't have SparcV8 reg info??");
120 const SparcV8RegisterInfo *MRI =
121 static_cast<const SparcV8RegisterInfo*>(TM.getRegisterInfo());
122 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
123 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
124 // Create the lower part
125 F->getSSARegMap()->createVirtualRegister(RC);
126 // Create the upper part.
127 return F->getSSARegMap()->createVirtualRegister(RC)-1;
130 // Add the mapping of regnumber => reg class to MachineFunction
131 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
132 return F->getSSARegMap()->createVirtualRegister(RC);
135 unsigned getReg(Value &V) { return getReg (&V); } // allow refs.
136 unsigned getReg(Value *V) {
137 // Just append to the end of the current bb.
138 MachineBasicBlock::iterator It = BB->end();
139 return getReg(V, BB, It);
141 unsigned getReg(Value *V, MachineBasicBlock *MBB,
142 MachineBasicBlock::iterator IPt) {
143 unsigned &Reg = RegMap[V];
145 Reg = makeAnotherReg(V->getType());
148 // If this operand is a constant, emit the code to copy the constant into
149 // the register here...
151 if (Constant *C = dyn_cast<Constant>(V)) {
152 copyConstantToRegister(MBB, IPt, C, Reg);
153 RegMap.erase(V); // Assign a new name to this constant if ref'd again
154 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
155 // Move the address of the global into the register
156 unsigned TmpReg = makeAnotherReg(V->getType());
157 BuildMI (*MBB, IPt, V8::SETHIi, 1, TmpReg).addGlobalAddress (GV);
158 BuildMI (*MBB, IPt, V8::ORri, 2, Reg).addReg (TmpReg)
159 .addGlobalAddress (GV);
160 RegMap.erase(V); // Assign a new name to this address if ref'd again
169 FunctionPass *llvm::createSparcV8SimpleInstructionSelector(TargetMachine &TM) {
170 return new V8ISel(TM);
174 cByte, cShort, cInt, cLong, cFloat, cDouble
177 static TypeClass getClass (const Type *T) {
178 switch (T->getTypeID()) {
179 case Type::UByteTyID: case Type::SByteTyID: return cByte;
180 case Type::UShortTyID: case Type::ShortTyID: return cShort;
181 case Type::PointerTyID:
182 case Type::UIntTyID: case Type::IntTyID: return cInt;
183 case Type::ULongTyID: case Type::LongTyID: return cLong;
184 case Type::FloatTyID: return cFloat;
185 case Type::DoubleTyID: return cDouble;
187 assert (0 && "Type of unknown class passed to getClass?");
191 static TypeClass getClassB(const Type *T) {
192 if (T == Type::BoolTy) return cByte;
198 /// copyConstantToRegister - Output the instructions required to put the
199 /// specified constant into the specified register.
201 void V8ISel::copyConstantToRegister(MachineBasicBlock *MBB,
202 MachineBasicBlock::iterator IP,
203 Constant *C, unsigned R) {
204 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
205 switch (CE->getOpcode()) {
206 case Instruction::GetElementPtr:
207 emitGEPOperation(MBB, IP, CE->getOperand(0),
208 CE->op_begin()+1, CE->op_end(), R);
211 std::cerr << "Copying this constant expr not yet handled: " << *CE;
216 if (C->getType()->isIntegral ()) {
218 unsigned Class = getClassB (C->getType ());
219 if (Class == cLong) {
220 unsigned TmpReg = makeAnotherReg (Type::IntTy);
221 unsigned TmpReg2 = makeAnotherReg (Type::IntTy);
222 // Copy the value into the register pair.
223 // R = top(more-significant) half, R+1 = bottom(less-significant) half
224 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
225 unsigned topHalf = Val & 0xffffffffU;
226 unsigned bottomHalf = Val >> 32;
227 unsigned HH = topHalf >> 10;
228 unsigned HM = topHalf & 0x03ff;
229 unsigned LM = bottomHalf >> 10;
230 unsigned LO = bottomHalf & 0x03ff;
231 BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addImm(HH);
232 BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (TmpReg)
234 BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg2).addImm(LM);
235 BuildMI (*MBB, IP, V8::ORri, 2, R+1).addReg (TmpReg2)
240 assert(Class <= cInt && "Type not handled yet!");
242 if (C->getType() == Type::BoolTy) {
243 Val = (C == ConstantBool::True);
245 ConstantInt *CI = dyn_cast<ConstantInt> (C);
246 Val = CI->getRawValue ();
250 BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (V8::G0).addImm((uint8_t)Val);
253 unsigned TmpReg = makeAnotherReg (C->getType ());
254 BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg)
255 .addImm (((uint16_t) Val) >> 10);
256 BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (TmpReg)
257 .addImm (((uint16_t) Val) & 0x03ff);
261 unsigned TmpReg = makeAnotherReg (C->getType ());
262 BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addImm(((uint32_t)Val) >> 10);
263 BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (TmpReg)
264 .addImm (((uint32_t) Val) & 0x03ff);
268 std::cerr << "Offending constant: " << *C << "\n";
269 assert (0 && "Can't copy this kind of constant into register yet");
272 } else if (isa<ConstantPointerNull>(C)) {
273 // Copy zero (null pointer) to the register.
274 BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (V8::G0).addImm (0);
275 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
276 // Copy it with a SETHI/OR pair; the JIT + asmwriter should recognize
277 // that SETHI %reg,global == SETHI %reg,%hi(global) and
278 // OR %reg,global,%reg == OR %reg,%lo(global),%reg.
279 unsigned TmpReg = makeAnotherReg (C->getType ());
280 BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addGlobalAddress (CPR->getValue());
281 BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (TmpReg)
282 .addGlobalAddress (CPR->getValue ());
284 std::cerr << "Offending constant: " << *C << "\n";
285 assert (0 && "Can't copy this kind of constant into register yet");
289 void V8ISel::LoadArgumentsToVirtualRegs (Function *F) {
290 unsigned ArgOffset = 0;
291 static const unsigned IncomingArgRegs[] = { V8::I0, V8::I1, V8::I2,
292 V8::I3, V8::I4, V8::I5 };
293 assert (F->asize () < 7
294 && "Can't handle loading excess call args off the stack yet");
296 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I) {
297 unsigned Reg = getReg(*I);
298 switch (getClassB(I->getType())) {
302 BuildMI(BB, V8::ORrr, 2, Reg).addReg (V8::G0)
303 .addReg (IncomingArgRegs[ArgOffset]);
306 assert (0 && "Only <=32-bit, integral arguments currently handled");
313 void V8ISel::SelectPHINodes() {
314 const TargetInstrInfo &TII = *TM.getInstrInfo();
315 const Function &LF = *F->getFunction(); // The LLVM function...
316 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
317 const BasicBlock *BB = I;
318 MachineBasicBlock &MBB = *MBBMap[I];
320 // Loop over all of the PHI nodes in the LLVM basic block...
321 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
322 for (BasicBlock::const_iterator I = BB->begin();
323 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
325 // Create a new machine instr PHI node, and insert it.
326 unsigned PHIReg = getReg(*PN);
327 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
328 V8::PHI, PN->getNumOperands(), PHIReg);
330 MachineInstr *LongPhiMI = 0;
331 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
332 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
333 V8::PHI, PN->getNumOperands(), PHIReg+1);
335 // PHIValues - Map of blocks to incoming virtual registers. We use this
336 // so that we only initialize one incoming value for a particular block,
337 // even if the block has multiple entries in the PHI node.
339 std::map<MachineBasicBlock*, unsigned> PHIValues;
341 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
342 MachineBasicBlock *PredMBB = 0;
343 for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
344 PE = MBB.pred_end (); PI != PE; ++PI)
345 if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
349 assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
352 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
353 PHIValues.lower_bound(PredMBB);
355 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
356 // We already inserted an initialization of the register for this
357 // predecessor. Recycle it.
358 ValReg = EntryIt->second;
361 // Get the incoming value into a virtual register.
363 Value *Val = PN->getIncomingValue(i);
365 // If this is a constant or GlobalValue, we may have to insert code
366 // into the basic block to compute it into a virtual register.
367 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
368 isa<GlobalValue>(Val)) {
369 // Simple constants get emitted at the end of the basic block,
370 // before any terminator instructions. We "know" that the code to
371 // move a constant into a register will never clobber any flags.
372 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
374 // Because we don't want to clobber any values which might be in
375 // physical registers with the computation of this constant (which
376 // might be arbitrarily complex if it is a constant expression),
377 // just insert the computation at the top of the basic block.
378 MachineBasicBlock::iterator PI = PredMBB->begin();
380 // Skip over any PHI nodes though!
381 while (PI != PredMBB->end() && PI->getOpcode() == V8::PHI)
384 ValReg = getReg(Val, PredMBB, PI);
387 // Remember that we inserted a value for this PHI for this predecessor
388 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
391 PhiMI->addRegOperand(ValReg);
392 PhiMI->addMachineBasicBlockOperand(PredMBB);
394 LongPhiMI->addRegOperand(ValReg+1);
395 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
399 // Now that we emitted all of the incoming values for the PHI node, make
400 // sure to reposition the InsertPoint after the PHI that we just added.
401 // This is needed because we might have inserted a constant into this
402 // block, right after the PHI's which is before the old insert point!
403 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
409 bool V8ISel::runOnFunction(Function &Fn) {
410 // First pass over the function, lower any unknown intrinsic functions
411 // with the IntrinsicLowering class.
412 LowerUnknownIntrinsicFunctionCalls(Fn);
414 F = &MachineFunction::construct(&Fn, TM);
416 // Create all of the machine basic blocks for the function...
417 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
418 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
422 // Set up a frame object for the return address. This is used by the
423 // llvm.returnaddress & llvm.frameaddress intrinisics.
424 //ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
426 // Copy incoming arguments off of the stack and out of fixed registers.
427 LoadArgumentsToVirtualRegs(&Fn);
429 // Instruction select everything except PHI nodes
432 // Select the PHI nodes
438 // We always build a machine code representation for the function
442 void V8ISel::visitCastInst(CastInst &I) {
443 unsigned SrcReg = getReg (I.getOperand (0));
444 unsigned DestReg = getReg (I);
445 const Type *oldTy = I.getOperand (0)->getType ();
446 const Type *newTy = I.getType ();
447 unsigned oldTyClass = getClassB (oldTy);
448 unsigned newTyClass = getClassB (newTy);
450 if (oldTyClass < cLong && newTyClass < cLong) {
451 if (oldTyClass >= newTyClass) {
452 // Emit a reg->reg copy to do a equal-size or narrowing cast,
453 // and do sign/zero extension (necessary if we change signedness).
454 unsigned TmpReg1 = makeAnotherReg (newTy);
455 unsigned TmpReg2 = makeAnotherReg (newTy);
456 BuildMI (BB, V8::ORrr, 2, TmpReg1).addReg (V8::G0).addReg (SrcReg);
457 unsigned shiftWidth = 32 - (8 * TM.getTargetData ().getTypeSize (newTy));
458 BuildMI (BB, V8::SLLri, 2, TmpReg2).addZImm (shiftWidth).addReg(TmpReg1);
459 if (newTy->isSigned ()) { // sign-extend with SRA
460 BuildMI(BB, V8::SRAri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg2);
461 } else { // zero-extend with SRL
462 BuildMI(BB, V8::SRLri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg2);
465 unsigned TmpReg1 = makeAnotherReg (oldTy);
466 unsigned TmpReg2 = makeAnotherReg (newTy);
467 unsigned TmpReg3 = makeAnotherReg (newTy);
468 // Widening integer cast. Make sure it's fully sign/zero-extended
469 // wrt the input type, then make sure it's fully sign/zero-extended wrt
470 // the output type. Kind of stupid, but simple...
471 unsigned shiftWidth = 32 - (8 * TM.getTargetData ().getTypeSize (oldTy));
472 BuildMI (BB, V8::SLLri, 2, TmpReg1).addZImm (shiftWidth).addReg(SrcReg);
473 if (oldTy->isSigned ()) { // sign-extend with SRA
474 BuildMI(BB, V8::SRAri, 2, TmpReg2).addZImm (shiftWidth).addReg(TmpReg1);
475 } else { // zero-extend with SRL
476 BuildMI(BB, V8::SRLri, 2, TmpReg2).addZImm (shiftWidth).addReg(TmpReg1);
478 shiftWidth = 32 - (8 * TM.getTargetData ().getTypeSize (newTy));
479 BuildMI (BB, V8::SLLri, 2, TmpReg3).addZImm (shiftWidth).addReg(TmpReg2);
480 if (newTy->isSigned ()) { // sign-extend with SRA
481 BuildMI(BB, V8::SRAri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg3);
482 } else { // zero-extend with SRL
483 BuildMI(BB, V8::SRLri, 2, DestReg).addZImm (shiftWidth).addReg(TmpReg3);
487 std::cerr << "Casts w/ long, fp, double still unsupported: " << I;
492 void V8ISel::visitLoadInst(LoadInst &I) {
493 unsigned DestReg = getReg (I);
494 unsigned PtrReg = getReg (I.getOperand (0));
495 switch (getClassB (I.getType ())) {
497 if (I.getType ()->isSigned ())
498 BuildMI (BB, V8::LDSBmr, 1, DestReg).addReg (PtrReg).addSImm(0);
500 BuildMI (BB, V8::LDUBmr, 1, DestReg).addReg (PtrReg).addSImm(0);
503 if (I.getType ()->isSigned ())
504 BuildMI (BB, V8::LDSHmr, 1, DestReg).addReg (PtrReg).addSImm(0);
506 BuildMI (BB, V8::LDUHmr, 1, DestReg).addReg (PtrReg).addSImm(0);
509 BuildMI (BB, V8::LDmr, 1, DestReg).addReg (PtrReg).addSImm(0);
512 BuildMI (BB, V8::LDDmr, 1, DestReg).addReg (PtrReg).addSImm(0);
515 std::cerr << "Load instruction not handled: " << I;
521 void V8ISel::visitStoreInst(StoreInst &I) {
522 Value *SrcVal = I.getOperand (0);
523 unsigned SrcReg = getReg (SrcVal);
524 unsigned PtrReg = getReg (I.getOperand (1));
525 switch (getClassB (SrcVal->getType ())) {
527 BuildMI (BB, V8::STBrm, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
530 BuildMI (BB, V8::STHrm, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
533 BuildMI (BB, V8::STrm, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
536 BuildMI (BB, V8::STDrm, 3).addReg (PtrReg).addSImm (0).addReg (SrcReg);
539 std::cerr << "Store instruction not handled: " << I;
545 void V8ISel::visitCallInst(CallInst &I) {
546 assert (I.getNumOperands () < 8
547 && "Can't handle pushing excess call args on the stack yet");
548 static const unsigned OutgoingArgRegs[] = { V8::O0, V8::O1, V8::O2, V8::O3,
550 for (unsigned i = 1; i < 7; ++i)
551 if (i < I.getNumOperands ()) {
552 unsigned ArgReg = getReg (I.getOperand (i));
553 // Schlep it over into the incoming arg register
554 BuildMI (BB, V8::ORrr, 2, OutgoingArgRegs[i - 1]).addReg (V8::G0)
558 BuildMI (BB, V8::CALL, 1).addGlobalAddress(I.getCalledFunction (), true);
559 if (I.getType () == Type::VoidTy)
561 unsigned DestReg = getReg (I);
562 // Deal w/ return value
563 switch (getClass (I.getType ())) {
567 // Schlep it over into the destination register
568 BuildMI (BB, V8::ORrr, 2, DestReg).addReg(V8::G0).addReg(V8::O0);
571 std::cerr << "Return type of call instruction not handled: " << I;
576 void V8ISel::visitReturnInst(ReturnInst &I) {
577 if (I.getNumOperands () == 1) {
578 unsigned RetValReg = getReg (I.getOperand (0));
579 switch (getClass (I.getOperand (0)->getType ())) {
583 // Schlep it over into i0 (where it will become o0 after restore).
584 BuildMI (BB, V8::ORrr, 2, V8::I0).addReg(V8::G0).addReg(RetValReg);
587 std::cerr << "Return instruction of this type not handled: " << I;
592 // Just emit a 'retl' instruction to return.
593 BuildMI(BB, V8::RETL, 0);
597 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
598 Function::iterator I = BB; ++I; // Get iterator to next block
599 return I != BB->getParent()->end() ? &*I : 0;
602 /// visitBranchInst - Handles conditional and unconditional branches.
604 void V8ISel::visitBranchInst(BranchInst &I) {
605 BasicBlock *takenSucc = I.getSuccessor (0);
606 MachineBasicBlock *takenSuccMBB = MBBMap[takenSucc];
607 BB->addSuccessor (takenSuccMBB);
608 if (I.isConditional()) { // conditional branch
609 BasicBlock *notTakenSucc = I.getSuccessor (1);
610 MachineBasicBlock *notTakenSuccMBB = MBBMap[notTakenSucc];
611 BB->addSuccessor (notTakenSuccMBB);
613 // CondReg=(<condition>);
614 // If (CondReg==0) goto notTakenSuccMBB;
615 unsigned CondReg = getReg (I.getCondition ());
616 BuildMI (BB, V8::CMPri, 2).addSImm (0).addReg (CondReg);
617 BuildMI (BB, V8::BE, 1).addMBB (notTakenSuccMBB);
619 // goto takenSuccMBB;
620 BuildMI (BB, V8::BA, 1).addMBB (takenSuccMBB);
623 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
624 /// constant expression GEP support.
626 void V8ISel::emitGEPOperation (MachineBasicBlock *MBB,
627 MachineBasicBlock::iterator IP,
628 Value *Src, User::op_iterator IdxBegin,
629 User::op_iterator IdxEnd, unsigned TargetReg) {
630 const TargetData &TD = TM.getTargetData ();
631 const Type *Ty = Src->getType ();
632 unsigned basePtrReg = getReg (Src);
634 // GEPs have zero or more indices; we must perform a struct access
635 // or array access for each one.
636 for (GetElementPtrInst::op_iterator oi = IdxBegin, oe = IdxEnd; oi != oe;
639 unsigned nextBasePtrReg = makeAnotherReg (Type::UIntTy);
640 if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
641 // It's a struct access. idx is the index into the structure,
642 // which names the field. Use the TargetData structure to
643 // pick out what the layout of the structure is in memory.
644 // Use the (constant) structure index's value to find the
645 // right byte offset from the StructLayout class's list of
646 // structure member offsets.
647 unsigned fieldIndex = cast<ConstantUInt> (idx)->getValue ();
648 unsigned memberOffset =
649 TD.getStructLayout (StTy)->MemberOffsets[fieldIndex];
650 // Emit an ADD to add memberOffset to the basePtr.
651 BuildMI (*MBB, IP, V8::ADDri, 2,
652 nextBasePtrReg).addReg (basePtrReg).addZImm (memberOffset);
653 // The next type is the member of the structure selected by the
655 Ty = StTy->getElementType (fieldIndex);
656 } else if (const SequentialType *SqTy = dyn_cast<SequentialType> (Ty)) {
657 // It's an array or pointer access: [ArraySize x ElementType].
658 // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
659 // must find the size of the pointed-to type (Not coincidentally, the next
660 // type is the type of the elements in the array).
661 Ty = SqTy->getElementType ();
662 unsigned elementSize = TD.getTypeSize (Ty);
663 unsigned idxReg = getReg (idx, MBB, IP);
664 unsigned OffsetReg = makeAnotherReg (Type::IntTy);
665 unsigned elementSizeReg = makeAnotherReg (Type::UIntTy);
666 BuildMI (*MBB, IP, V8::ORri, 2,
667 elementSizeReg).addZImm (elementSize).addReg (V8::G0);
668 // Emit a SMUL to multiply the register holding the index by
669 // elementSize, putting the result in OffsetReg.
670 BuildMI (*MBB, IP, V8::SMULrr, 2,
671 OffsetReg).addReg (elementSizeReg).addReg (idxReg);
672 // Emit an ADD to add OffsetReg to the basePtr.
673 BuildMI (*MBB, IP, V8::ADDrr, 2,
674 nextBasePtrReg).addReg (basePtrReg).addReg (OffsetReg);
676 basePtrReg = nextBasePtrReg;
678 // After we have processed all the indices, the result is left in
679 // basePtrReg. Move it to the register where we were expected to
681 BuildMI (BB, V8::ORrr, 1, TargetReg).addReg (V8::G0).addReg (basePtrReg);
684 void V8ISel::visitGetElementPtrInst (GetElementPtrInst &I) {
685 unsigned outputReg = getReg (I);
686 emitGEPOperation (BB, BB->end (), I.getOperand (0),
687 I.op_begin ()+1, I.op_end (), outputReg);
691 void V8ISel::visitBinaryOperator (Instruction &I) {
692 unsigned DestReg = getReg (I);
693 unsigned Op0Reg = getReg (I.getOperand (0));
694 unsigned Op1Reg = getReg (I.getOperand (1));
696 unsigned ResultReg = DestReg;
697 if (getClassB(I.getType()) != cInt)
698 ResultReg = makeAnotherReg (I.getType ());
699 unsigned OpCase = ~0;
701 // FIXME: support long, ulong, fp.
702 switch (I.getOpcode ()) {
703 case Instruction::Add: OpCase = 0; break;
704 case Instruction::Sub: OpCase = 1; break;
705 case Instruction::Mul: OpCase = 2; break;
706 case Instruction::And: OpCase = 3; break;
707 case Instruction::Or: OpCase = 4; break;
708 case Instruction::Xor: OpCase = 5; break;
709 case Instruction::Shl: OpCase = 6; break;
710 case Instruction::Shr: OpCase = 7+I.getType()->isSigned(); break;
712 case Instruction::Div:
713 case Instruction::Rem: {
714 unsigned Dest = ResultReg;
715 if (I.getOpcode() == Instruction::Rem)
716 Dest = makeAnotherReg(I.getType());
718 // FIXME: this is probably only right for 32 bit operands.
719 if (I.getType ()->isSigned()) {
720 unsigned Tmp = makeAnotherReg (I.getType ());
721 // Sign extend into the Y register
722 BuildMI (BB, V8::SRAri, 2, Tmp).addReg (Op0Reg).addZImm (31);
723 BuildMI (BB, V8::WRrr, 2, V8::Y).addReg (Tmp).addReg (V8::G0);
724 BuildMI (BB, V8::SDIVrr, 2, Dest).addReg (Op0Reg).addReg (Op1Reg);
726 // Zero extend into the Y register, ie, just set it to zero
727 BuildMI (BB, V8::WRrr, 2, V8::Y).addReg (V8::G0).addReg (V8::G0);
728 BuildMI (BB, V8::UDIVrr, 2, Dest).addReg (Op0Reg).addReg (Op1Reg);
731 if (I.getOpcode() == Instruction::Rem) {
732 unsigned Tmp = makeAnotherReg (I.getType ());
733 BuildMI (BB, V8::SMULrr, 2, Tmp).addReg(Dest).addReg(Op1Reg);
734 BuildMI (BB, V8::SUBrr, 2, ResultReg).addReg(Op0Reg).addReg(Tmp);
739 visitInstruction (I);
744 static const unsigned Opcodes[] = {
745 V8::ADDrr, V8::SUBrr, V8::SMULrr, V8::ANDrr, V8::ORrr, V8::XORrr,
746 V8::SLLrr, V8::SRLrr, V8::SRArr
748 BuildMI (BB, Opcodes[OpCase], 2, ResultReg).addReg (Op0Reg).addReg (Op1Reg);
751 switch (getClass (I.getType ())) {
753 if (I.getType ()->isSigned ()) { // add byte
754 BuildMI (BB, V8::ANDri, 2, DestReg).addReg (ResultReg).addZImm (0xff);
755 } else { // add ubyte
756 unsigned TmpReg = makeAnotherReg (I.getType ());
757 BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (24);
758 BuildMI (BB, V8::SRAri, 2, DestReg).addReg (TmpReg).addZImm (24);
762 if (I.getType ()->isSigned ()) { // add short
763 unsigned TmpReg = makeAnotherReg (I.getType ());
764 BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (16);
765 BuildMI (BB, V8::SRAri, 2, DestReg).addReg (TmpReg).addZImm (16);
766 } else { // add ushort
767 unsigned TmpReg = makeAnotherReg (I.getType ());
768 BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (16);
769 BuildMI (BB, V8::SRLri, 2, DestReg).addReg (TmpReg).addZImm (16);
773 // Nothing todo here.
776 visitInstruction (I);
781 void V8ISel::visitSetCondInst(Instruction &I) {
782 unsigned Op0Reg = getReg (I.getOperand (0));
783 unsigned Op1Reg = getReg (I.getOperand (1));
784 unsigned DestReg = getReg (I);
785 const Type *Ty = I.getOperand (0)->getType ();
787 // Compare the two values.
788 BuildMI(BB, V8::SUBCCrr, 2, V8::G0).addReg(Op0Reg).addReg(Op1Reg);
791 switch (I.getOpcode()) {
792 default: assert(0 && "Unknown setcc instruction!");
793 case Instruction::SetEQ: BranchIdx = 0; break;
794 case Instruction::SetNE: BranchIdx = 1; break;
795 case Instruction::SetLT: BranchIdx = 2; break;
796 case Instruction::SetGT: BranchIdx = 3; break;
797 case Instruction::SetLE: BranchIdx = 4; break;
798 case Instruction::SetGE: BranchIdx = 5; break;
800 static unsigned OpcodeTab[12] = {
803 V8::BE, V8::BE, // seteq = be be
804 V8::BNE, V8::BNE, // setne = bne bne
805 V8::BCS, V8::BL, // setlt = bcs bl
806 V8::BGU, V8::BG, // setgt = bgu bg
807 V8::BLEU, V8::BLE, // setle = bleu ble
808 V8::BCC, V8::BGE // setge = bcc bge
810 unsigned Opcode = OpcodeTab[2*BranchIdx + (Ty->isSigned() ? 1 : 0)];
812 MachineBasicBlock *thisMBB = BB;
813 const BasicBlock *LLVM_BB = BB->getBasicBlock ();
816 // subcc %reg0, %reg1, %g0
820 // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
821 // if we could insert other, non-terminator instructions after the
822 // bCC. But MBB->getFirstTerminator() can't understand this.
823 MachineBasicBlock *copy1MBB = new MachineBasicBlock (LLVM_BB);
824 F->getBasicBlockList ().push_back (copy1MBB);
825 BuildMI (BB, Opcode, 1).addMBB (copy1MBB);
826 MachineBasicBlock *copy0MBB = new MachineBasicBlock (LLVM_BB);
827 F->getBasicBlockList ().push_back (copy0MBB);
828 BuildMI (BB, V8::BA, 1).addMBB (copy0MBB);
829 // Update machine-CFG edges
830 BB->addSuccessor (copy1MBB);
831 BB->addSuccessor (copy0MBB);
834 // %FalseValue = or %G0, 0
837 unsigned FalseValue = makeAnotherReg (I.getType ());
838 BuildMI (BB, V8::ORri, 2, FalseValue).addReg (V8::G0).addZImm (0);
839 MachineBasicBlock *sinkMBB = new MachineBasicBlock (LLVM_BB);
840 F->getBasicBlockList ().push_back (sinkMBB);
841 BuildMI (BB, V8::BA, 1).addMBB (sinkMBB);
842 // Update machine-CFG edges
843 BB->addSuccessor (sinkMBB);
845 DEBUG (std::cerr << "thisMBB is at " << (void*)thisMBB << "\n");
846 DEBUG (std::cerr << "copy1MBB is at " << (void*)copy1MBB << "\n");
847 DEBUG (std::cerr << "copy0MBB is at " << (void*)copy0MBB << "\n");
848 DEBUG (std::cerr << "sinkMBB is at " << (void*)sinkMBB << "\n");
851 // %TrueValue = or %G0, 1
854 unsigned TrueValue = makeAnotherReg (I.getType ());
855 BuildMI (BB, V8::ORri, 2, TrueValue).addReg (V8::G0).addZImm (1);
856 BuildMI (BB, V8::BA, 1).addMBB (sinkMBB);
857 // Update machine-CFG edges
858 BB->addSuccessor (sinkMBB);
861 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
864 BuildMI (BB, V8::PHI, 4, DestReg).addReg (FalseValue)
865 .addMBB (copy0MBB).addReg (TrueValue).addMBB (copy1MBB);
870 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
871 /// function, lowering any calls to unknown intrinsic functions into the
872 /// equivalent LLVM code.
873 void V8ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
874 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
875 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
876 if (CallInst *CI = dyn_cast<CallInst>(I++))
877 if (Function *F = CI->getCalledFunction())
878 switch (F->getIntrinsicID()) {
879 case Intrinsic::not_intrinsic: break;
881 // All other intrinsic calls we must lower.
882 Instruction *Before = CI->getPrev();
883 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
884 if (Before) { // Move iterator to instruction after call
893 void V8ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
894 unsigned TmpReg1, TmpReg2;
896 default: assert(0 && "Intrinsic not supported!");