0d51e01ae9076d723cbf85b0667031d0a467fa96
[oota-llvm.git] / lib / Target / Sparc / SparcV8ISelSimple.cpp
1 //===-- InstSelectSimple.cpp - A simple instruction selector for SparcV8 --===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a simple peephole instruction selector for the V8 target
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "SparcV8.h"
15 #include "SparcV8InstrInfo.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/IntrinsicLowering.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/SSARegMap.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Support/GetElementPtrTypeIterator.h"
25 #include "llvm/Support/InstVisitor.h"
26 #include "llvm/Support/CFG.h"
27 using namespace llvm;
28
29 namespace {
30   struct V8ISel : public FunctionPass, public InstVisitor<V8ISel> {
31     TargetMachine &TM;
32     MachineFunction *F;                 // The function we are compiling into
33     MachineBasicBlock *BB;              // The current MBB we are compiling
34
35     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
36
37     // MBBMap - Mapping between LLVM BB -> Machine BB
38     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
39
40     V8ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
41
42     /// runOnFunction - Top level implementation of instruction selection for
43     /// the entire function.
44     ///
45     bool runOnFunction(Function &Fn);
46
47     virtual const char *getPassName() const {
48       return "SparcV8 Simple Instruction Selection";
49     }
50
51     /// visitBasicBlock - This method is called when we are visiting a new basic
52     /// block.  This simply creates a new MachineBasicBlock to emit code into
53     /// and adds it to the current MachineFunction.  Subsequent visit* for
54     /// instructions will be invoked for all instructions in the basic block.
55     ///
56     void visitBasicBlock(BasicBlock &LLVM_BB) {
57       BB = MBBMap[&LLVM_BB];
58     }
59
60     void visitBinaryOperator(Instruction &I);
61     void visitShiftInstruction(Instruction &I) { visitBinaryOperator(I); }
62     void visitCallInst(CallInst &I);
63     void visitReturnInst(ReturnInst &RI);
64
65     void visitInstruction(Instruction &I) {
66       std::cerr << "Unhandled instruction: " << I;
67       abort();
68     }
69
70     /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
71     /// function, lowering any calls to unknown intrinsic functions into the
72     /// equivalent LLVM code.
73     void LowerUnknownIntrinsicFunctionCalls(Function &F);
74     void visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI);
75
76     /// copyConstantToRegister - Output the instructions required to put the
77     /// specified constant into the specified register.
78     ///
79     void copyConstantToRegister(MachineBasicBlock *MBB,
80                                 MachineBasicBlock::iterator IP,
81                                 Constant *C, unsigned R);
82
83     /// makeAnotherReg - This method returns the next register number we haven't
84     /// yet used.
85     ///
86     /// Long values are handled somewhat specially.  They are always allocated
87     /// as pairs of 32 bit integer values.  The register number returned is the
88     /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
89     /// of the long value.
90     ///
91     unsigned makeAnotherReg(const Type *Ty) {
92       assert(dynamic_cast<const SparcV8RegisterInfo*>(TM.getRegisterInfo()) &&
93              "Current target doesn't have SparcV8 reg info??");
94       const SparcV8RegisterInfo *MRI =
95         static_cast<const SparcV8RegisterInfo*>(TM.getRegisterInfo());
96       if (Ty == Type::LongTy || Ty == Type::ULongTy) {
97         const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
98         // Create the lower part
99         F->getSSARegMap()->createVirtualRegister(RC);
100         // Create the upper part.
101         return F->getSSARegMap()->createVirtualRegister(RC)-1;
102       }
103
104       // Add the mapping of regnumber => reg class to MachineFunction
105       const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
106       return F->getSSARegMap()->createVirtualRegister(RC);
107     }
108
109     unsigned getReg(Value &V) { return getReg (&V); } // allow refs.
110     unsigned getReg(Value *V) {
111       // Just append to the end of the current bb.
112       MachineBasicBlock::iterator It = BB->end();
113       return getReg(V, BB, It);
114     }
115     unsigned getReg(Value *V, MachineBasicBlock *MBB,
116                     MachineBasicBlock::iterator IPt) {
117       unsigned &Reg = RegMap[V];
118       if (Reg == 0) {
119         Reg = makeAnotherReg(V->getType());
120         RegMap[V] = Reg;
121       }
122       // If this operand is a constant, emit the code to copy the constant into
123       // the register here...
124       //
125       if (Constant *C = dyn_cast<Constant>(V)) {
126         copyConstantToRegister(MBB, IPt, C, Reg);
127         RegMap.erase(V);  // Assign a new name to this constant if ref'd again
128       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
129         // Move the address of the global into the register
130         unsigned TmpReg = makeAnotherReg(V->getType());
131         BuildMI (*MBB, IPt, V8::SETHIi, 1, TmpReg).addGlobalAddress (GV);
132         BuildMI (*MBB, IPt, V8::ORri, 2, Reg).addReg (TmpReg)
133           .addGlobalAddress (GV);
134         RegMap.erase(V);  // Assign a new name to this address if ref'd again
135       }
136
137       return Reg;
138     }
139
140   };
141 }
142
143 FunctionPass *llvm::createSparcV8SimpleInstructionSelector(TargetMachine &TM) {
144   return new V8ISel(TM);
145 }
146
147 enum TypeClass {
148   cByte, cShort, cInt, cLong, cFloat, cDouble
149 };
150
151 static TypeClass getClass (const Type *T) {
152   switch (T->getPrimitiveID ()) {
153     case Type::UByteTyID:  case Type::SByteTyID:  return cByte;
154     case Type::UShortTyID: case Type::ShortTyID:  return cShort;
155     case Type::UIntTyID:   case Type::IntTyID:    return cInt;
156     case Type::ULongTyID:  case Type::LongTyID:   return cLong;
157     case Type::FloatTyID:                         return cFloat;
158     case Type::DoubleTyID:                        return cDouble;
159     default:
160       assert (0 && "Type of unknown class passed to getClass?");
161       return cByte;
162   }
163 }
164 static TypeClass getClassB(const Type *T) {
165   if (T == Type::BoolTy) return cByte;
166   return getClass(T);
167 }
168
169
170
171 /// copyConstantToRegister - Output the instructions required to put the
172 /// specified constant into the specified register.
173 ///
174 void V8ISel::copyConstantToRegister(MachineBasicBlock *MBB,
175                                     MachineBasicBlock::iterator IP,
176                                     Constant *C, unsigned R) {
177   if (ConstantInt *CI = dyn_cast<ConstantInt> (C)) {
178     unsigned Class = getClass(C->getType());
179     uint64_t Val = CI->getRawValue ();
180     switch (Class) {
181       case cByte:
182         BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (V8::G0).addImm((uint8_t)Val);
183         return;
184       case cShort: {
185         unsigned TmpReg = makeAnotherReg (C->getType ());
186         BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg)
187           .addImm (((uint16_t) Val) >> 10);
188         BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (TmpReg)
189           .addImm (((uint16_t) Val) & 0x03ff);
190         return;
191       }
192       case cInt: {
193         unsigned TmpReg = makeAnotherReg (C->getType ());
194         BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addImm(((uint32_t)Val) >> 10);
195         BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (TmpReg)
196           .addImm (((uint32_t) Val) & 0x03ff);
197         return;
198       }
199       case cLong: {
200         unsigned TmpReg = makeAnotherReg (Type::UIntTy);
201         uint32_t topHalf = (uint32_t) (Val >> 32);
202         uint32_t bottomHalf = (uint32_t)Val;
203         BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addImm (topHalf >> 10);
204         BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (TmpReg)
205           .addImm (topHalf & 0x03ff);
206         BuildMI (*MBB, IP, V8::SETHIi, 1, TmpReg).addImm (bottomHalf >> 10);
207         BuildMI (*MBB, IP, V8::ORri, 2, R).addReg (TmpReg)
208           .addImm (bottomHalf & 0x03ff);
209         return;
210       }
211       default:
212         std::cerr << "Offending constant: " << *C << "\n";
213         assert (0 && "Can't copy this kind of constant into register yet");
214         return;
215     }
216   }
217
218   std::cerr << "Offending constant: " << *C << "\n";
219   assert (0 && "Can't copy this kind of constant into register yet");
220 }
221
222 bool V8ISel::runOnFunction(Function &Fn) {
223   // First pass over the function, lower any unknown intrinsic functions
224   // with the IntrinsicLowering class.
225   LowerUnknownIntrinsicFunctionCalls(Fn);
226   
227   F = &MachineFunction::construct(&Fn, TM);
228   
229   // Create all of the machine basic blocks for the function...
230   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
231     F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
232   
233   BB = &F->front();
234   
235   // Set up a frame object for the return address.  This is used by the
236   // llvm.returnaddress & llvm.frameaddress intrinisics.
237   //ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
238   
239   // Copy incoming arguments off of the stack and out of fixed registers.
240   //LoadArgumentsToVirtualRegs(Fn);
241   
242   // Instruction select everything except PHI nodes
243   visit(Fn);
244   
245   // Select the PHI nodes
246   //SelectPHINodes();
247   
248   RegMap.clear();
249   MBBMap.clear();
250   F = 0;
251   // We always build a machine code representation for the function
252   return true;
253 }
254
255 void V8ISel::visitCallInst(CallInst &I) {
256   assert (I.getNumOperands () == 1 && "Can't handle call args yet");
257   unsigned DestReg = getReg (I);
258   BuildMI (BB, V8::CALL, 1).addPCDisp (I.getOperand (0));
259   if (I.getType ()->getPrimitiveID () == Type::VoidTyID)
260     return;
261   // Deal w/ return value
262   switch (getClass (I.getType ())) {
263     case cByte:
264     case cShort:
265     case cInt:
266       // Schlep it over into the destination register
267       BuildMI (BB, V8::ORrr, 2, DestReg).addReg(V8::G0).addReg(V8::O0);
268       break;
269     default:
270       visitInstruction (I);
271       return;
272   }
273 }
274
275 void V8ISel::visitReturnInst(ReturnInst &I) {
276   if (I.getNumOperands () == 1) {
277     unsigned RetValReg = getReg (I.getOperand (0));
278     switch (getClass (I.getOperand (0)->getType ())) {
279       case cByte:
280       case cShort:
281       case cInt:
282         // Schlep it over into i0 (where it will become o0 after restore).
283         BuildMI (BB, V8::ORrr, 2, V8::I0).addReg(V8::G0).addReg(RetValReg);
284         break;
285       default:
286         visitInstruction (I);
287         return;
288     }
289   }
290
291   // Just emit a 'retl' instruction to return.
292   BuildMI(BB, V8::RETL, 0);
293   return;
294 }
295
296 void V8ISel::visitBinaryOperator (Instruction &I) {
297   unsigned DestReg = getReg (I);
298   unsigned Op0Reg = getReg (I.getOperand (0));
299   unsigned Op1Reg = getReg (I.getOperand (1));
300
301   unsigned ResultReg = DestReg;
302   if (getClassB(I.getType()) != cInt)
303     ResultReg = makeAnotherReg (I.getType ());
304   unsigned OpCase = ~0;
305
306   // FIXME: support long, ulong, fp.
307   switch (I.getOpcode ()) {
308   case Instruction::Add: OpCase = 0; break;
309   case Instruction::Sub: OpCase = 1; break;
310   case Instruction::Mul: OpCase = 2; break;
311   case Instruction::And: OpCase = 3; break;
312   case Instruction::Or:  OpCase = 4; break;
313   case Instruction::Xor: OpCase = 5; break;
314   case Instruction::Shl: OpCase = 6; break;
315   case Instruction::Shr: OpCase = 7+I.getType()->isSigned(); break;
316
317   case Instruction::Div:
318   case Instruction::Rem: {
319     unsigned Dest = ResultReg;
320     if (I.getOpcode() == Instruction::Rem)
321       Dest = makeAnotherReg(I.getType());
322
323     // FIXME: this is probably only right for 32 bit operands.
324     if (I.getType ()->isSigned()) {
325       unsigned Tmp = makeAnotherReg (I.getType ());
326       // Sign extend into the Y register
327       BuildMI (BB, V8::SRAri, 2, Tmp).addReg (Op0Reg).addZImm (31);
328       BuildMI (BB, V8::WRrr, 2, V8::Y).addReg (Tmp).addReg (V8::G0);
329       BuildMI (BB, V8::SDIVrr, 2, Dest).addReg (Op0Reg).addReg (Op1Reg);
330     } else {
331       // Zero extend into the Y register, ie, just set it to zero
332       BuildMI (BB, V8::WRrr, 2, V8::Y).addReg (V8::G0).addReg (V8::G0);
333       BuildMI (BB, V8::UDIVrr, 2, Dest).addReg (Op0Reg).addReg (Op1Reg);
334     }
335
336     if (I.getOpcode() == Instruction::Rem) {
337       unsigned Tmp = makeAnotherReg (I.getType ());
338       BuildMI (BB, V8::SMULrr, 2, Tmp).addReg(Dest).addReg(Op1Reg);
339       BuildMI (BB, V8::SUBrr, 2, ResultReg).addReg(Op0Reg).addReg(Tmp);
340     }
341     break;
342   }
343   default:
344     visitInstruction (I);
345     return;
346   }
347
348   if (OpCase != ~0U) {
349     static const unsigned Opcodes[] = {
350       V8::ADDrr, V8::SUBrr, V8::SMULrr, V8::ANDrr, V8::ORrr, V8::XORrr,
351       V8::SLLrr, V8::SRLrr, V8::SRArr
352     };
353     BuildMI (BB, Opcodes[OpCase], 2, ResultReg).addReg (Op0Reg).addReg (Op1Reg);
354   }
355
356   switch (getClass (I.getType ())) {
357     case cByte: 
358       if (I.getType ()->isSigned ()) { // add byte
359         BuildMI (BB, V8::ANDri, 2, DestReg).addReg (ResultReg).addZImm (0xff);
360       } else { // add ubyte
361         unsigned TmpReg = makeAnotherReg (I.getType ());
362         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (24);
363         BuildMI (BB, V8::SRAri, 2, DestReg).addReg (TmpReg).addZImm (24);
364       }
365       break;
366     case cShort:
367       if (I.getType ()->isSigned ()) { // add short
368         unsigned TmpReg = makeAnotherReg (I.getType ());
369         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (16);
370         BuildMI (BB, V8::SRAri, 2, DestReg).addReg (TmpReg).addZImm (16);
371       } else { // add ushort
372         unsigned TmpReg = makeAnotherReg (I.getType ());
373         BuildMI (BB, V8::SLLri, 2, TmpReg).addReg (ResultReg).addZImm (16);
374         BuildMI (BB, V8::SRLri, 2, DestReg).addReg (TmpReg).addZImm (16);
375       }
376       break;
377     case cInt:
378       // Nothing todo here.
379       break;
380     default:
381       visitInstruction (I);
382       return;
383   }
384 }
385
386
387 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
388 /// function, lowering any calls to unknown intrinsic functions into the
389 /// equivalent LLVM code.
390 void V8ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
391   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
392     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
393       if (CallInst *CI = dyn_cast<CallInst>(I++))
394         if (Function *F = CI->getCalledFunction())
395           switch (F->getIntrinsicID()) {
396           case Intrinsic::not_intrinsic: break;
397           default:
398             // All other intrinsic calls we must lower.
399             Instruction *Before = CI->getPrev();
400             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
401             if (Before) {        // Move iterator to instruction after call
402               I = Before;  ++I;
403             } else {
404               I = BB->begin();
405             }
406           }
407 }
408
409
410 void V8ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
411   unsigned TmpReg1, TmpReg2;
412   switch (ID) {
413   default: assert(0 && "Intrinsic not supported!");
414   }
415 }