Several changes to Mips backend, experimental fp support being the most
[oota-llvm.git] / lib / Target / Mips / MipsISelLowering.cpp
1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "mips-lower"
16
17 #include "MipsISelLowering.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsTargetMachine.h"
20 #include "MipsSubtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/CodeGen/CallingConvLower.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAGISel.h"
31 #include "llvm/CodeGen/ValueTypes.h"
32 #include "llvm/Support/Debug.h"
33 #include <queue>
34 #include <set>
35
36 using namespace llvm;
37
38 const char *MipsTargetLowering::
39 getTargetNodeName(unsigned Opcode) const 
40 {
41   switch (Opcode) 
42   {
43     case MipsISD::JmpLink   : return "MipsISD::JmpLink";
44     case MipsISD::Hi        : return "MipsISD::Hi";
45     case MipsISD::Lo        : return "MipsISD::Lo";
46     case MipsISD::Ret       : return "MipsISD::Ret";
47     case MipsISD::SelectCC  : return "MipsISD::SelectCC";
48     case MipsISD::FPBrcond  : return "MipsISD::FPBrcond";
49     case MipsISD::FPCmp     : return "MipsISD::FPCmp";
50     default                 : return NULL;
51   }
52 }
53
54 MipsTargetLowering::
55 MipsTargetLowering(MipsTargetMachine &TM): TargetLowering(TM) 
56 {
57   Subtarget = &TM.getSubtarget<MipsSubtarget>();
58
59   // Mips does not have i1 type, so use i32 for
60   // setcc operations results (slt, sgt, ...). 
61   setSetCCResultContents(ZeroOrOneSetCCResult);
62
63   // JumpTable targets must use GOT when using PIC_
64   setUsesGlobalOffsetTable(true);
65
66   // Set up the register classes
67   addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
68
69   // When dealing with single precision only, use libcalls
70   if (!Subtarget->isSingleFloat()) {
71     addRegisterClass(MVT::f32, Mips::AFGR32RegisterClass);
72     if (!Subtarget->isFP64bit())
73       addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
74   } else 
75     addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
76
77   // Custom
78   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
79   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
80   setOperationAction(ISD::RET, MVT::Other, Custom);
81   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
82   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
83   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
84
85   if (Subtarget->isSingleFloat()) 
86     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
87
88   // Load extented operations for i1 types must be promoted 
89   setLoadXAction(ISD::EXTLOAD,  MVT::i1,  Promote);
90   setLoadXAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
91   setLoadXAction(ISD::SEXTLOAD, MVT::i1,  Promote);
92
93   // Mips does not have these NodeTypes below.
94   setOperationAction(ISD::BR_JT,     MVT::Other, Expand);
95   setOperationAction(ISD::BR_CC,     MVT::Other, Expand);
96   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
97   setOperationAction(ISD::SELECT,    MVT::i32,   Expand);
98   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
99
100   if (!Subtarget->isAllegrex()) {
101     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
102     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
103   }
104
105   // Mips not supported intrinsics.
106   setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
107
108   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
109   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
110   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
111   setOperationAction(ISD::ROTL , MVT::i32, Expand);
112   setOperationAction(ISD::ROTR , MVT::i32, Expand);
113   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
114
115   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
116   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
117   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
118
119   // We don't have line number support yet.
120   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
121   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
122   setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
123   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
124
125   // Use the default for now
126   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
127   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
128
129   setStackPointerRegisterToSaveRestore(Mips::SP);
130   computeRegisterProperties();
131 }
132
133
134 MVT MipsTargetLowering::getSetCCResultType(const SDOperand &) const {
135   return MVT::i32;
136 }
137
138
139 SDOperand MipsTargetLowering::
140 LowerOperation(SDOperand Op, SelectionDAG &DAG) 
141 {
142   switch (Op.getOpcode()) 
143   {
144     case ISD::CALL:             return LowerCALL(Op, DAG);
145     case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
146     case ISD::RET:              return LowerRET(Op, DAG);
147     case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
148     case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
149     case ISD::JumpTable:        return LowerJumpTable(Op, DAG);
150     case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
151   }
152   return SDOperand();
153 }
154
155 MachineBasicBlock *
156 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
157                                                 MachineBasicBlock *BB) 
158 {
159   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
160   switch (MI->getOpcode()) {
161   default: assert(false && "Unexpected instr type to insert");
162   case Mips::Select_CC: {
163     // To "insert" a SELECT_CC instruction, we actually have to insert the
164     // diamond control-flow pattern.  The incoming instruction knows the
165     // destination vreg to set, the condition code register to branch on, the
166     // true/false values to select between, and a branch opcode to use.
167     const BasicBlock *LLVM_BB = BB->getBasicBlock();
168     ilist<MachineBasicBlock>::iterator It = BB;
169     ++It;
170
171     //  thisMBB:
172     //  ...
173     //   TrueVal = ...
174     //   setcc r1, r2, r3
175     //   bNE   r1, r0, copy1MBB
176     //   fallthrough --> copy0MBB
177     MachineBasicBlock *thisMBB  = BB;
178     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
179     MachineBasicBlock *sinkMBB  = new MachineBasicBlock(LLVM_BB);
180     BuildMI(BB, TII->get(Mips::BNE)).addReg(MI->getOperand(1).getReg())
181       .addReg(Mips::ZERO).addMBB(sinkMBB);
182     MachineFunction *F = BB->getParent();
183     F->getBasicBlockList().insert(It, copy0MBB);
184     F->getBasicBlockList().insert(It, sinkMBB);
185     // Update machine-CFG edges by first adding all successors of the current
186     // block to the new block which will contain the Phi node for the select.
187     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
188         e = BB->succ_end(); i != e; ++i)
189       sinkMBB->addSuccessor(*i);
190     // Next, remove all successors of the current block, and add the true
191     // and fallthrough blocks as its successors.
192     while(!BB->succ_empty())
193       BB->removeSuccessor(BB->succ_begin());
194     BB->addSuccessor(copy0MBB);
195     BB->addSuccessor(sinkMBB);
196
197     //  copy0MBB:
198     //   %FalseValue = ...
199     //   # fallthrough to sinkMBB
200     BB = copy0MBB;
201
202     // Update machine-CFG edges
203     BB->addSuccessor(sinkMBB);
204
205     //  sinkMBB:
206     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
207     //  ...
208     BB = sinkMBB;
209     BuildMI(BB, TII->get(Mips::PHI), MI->getOperand(0).getReg())
210       .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
211       .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB);
212
213     delete MI;   // The pseudo instruction is gone now.
214     return BB;
215   }
216   }
217 }
218
219 //===----------------------------------------------------------------------===//
220 //  Lower helper functions
221 //===----------------------------------------------------------------------===//
222
223 // AddLiveIn - This helper function adds the specified physical register to the
224 // MachineFunction as a live in value.  It also creates a corresponding
225 // virtual register for it.
226 static unsigned
227 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC) 
228 {
229   assert(RC->contains(PReg) && "Not the correct regclass!");
230   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
231   MF.getRegInfo().addLiveIn(PReg, VReg);
232   return VReg;
233 }
234
235 //===----------------------------------------------------------------------===//
236 //  Misc Lower Operation implementation
237 //===----------------------------------------------------------------------===//
238 SDOperand MipsTargetLowering::
239 LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) 
240 {
241   SDOperand ResNode;
242   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
243   SDOperand GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
244   bool isPIC = (getTargetMachine().getRelocationModel() == Reloc::PIC_);
245
246   SDOperand HiPart; 
247   if (!isPIC) {
248     const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
249     SDOperand Ops[] = { GA };
250     HiPart = DAG.getNode(MipsISD::Hi, VTs, 1, Ops, 1);
251   } else // Emit Load from Global Pointer
252     HiPart = DAG.getLoad(MVT::i32, DAG.getEntryNode(), GA, NULL, 0);
253
254   // On functions and global targets not internal linked only
255   // a load from got/GP is necessary for PIC to work.
256   if ((isPIC) && ((!GV->hasInternalLinkage()) || (isa<Function>(GV))))
257     return HiPart;
258
259   SDOperand Lo = DAG.getNode(MipsISD::Lo, MVT::i32, GA);
260   ResNode = DAG.getNode(ISD::ADD, MVT::i32, HiPart, Lo);
261
262   return ResNode;
263 }
264
265 SDOperand MipsTargetLowering::
266 LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG)
267 {
268   assert(0 && "TLS not implemented for MIPS.");
269   return SDOperand(); // Not reached
270 }
271
272 SDOperand MipsTargetLowering::
273 LowerSELECT_CC(SDOperand Op, SelectionDAG &DAG) 
274 {
275   SDOperand LHS   = Op.getOperand(0); 
276   SDOperand RHS   = Op.getOperand(1); 
277   SDOperand True  = Op.getOperand(2);
278   SDOperand False = Op.getOperand(3);
279   SDOperand CC    = Op.getOperand(4);
280
281   const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
282   SDOperand Ops[] = { LHS, RHS, CC };
283   SDOperand SetCCRes = DAG.getNode(ISD::SETCC, VTs, 1, Ops, 3); 
284
285   return DAG.getNode(MipsISD::SelectCC, True.getValueType(), 
286                      SetCCRes, True, False);
287 }
288
289 SDOperand MipsTargetLowering::
290 LowerJumpTable(SDOperand Op, SelectionDAG &DAG) 
291 {
292   SDOperand ResNode;
293   SDOperand HiPart; 
294
295   MVT PtrVT = Op.getValueType();
296   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
297   SDOperand JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
298
299   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
300     const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
301     SDOperand Ops[] = { JTI };
302     HiPart = DAG.getNode(MipsISD::Hi, VTs, 1, Ops, 1);
303   } else // Emit Load from Global Pointer
304     HiPart = DAG.getLoad(MVT::i32, DAG.getEntryNode(), JTI, NULL, 0);
305
306   SDOperand Lo = DAG.getNode(MipsISD::Lo, MVT::i32, JTI);
307   ResNode = DAG.getNode(ISD::ADD, MVT::i32, HiPart, Lo);
308
309   return ResNode;
310 }
311
312 //===----------------------------------------------------------------------===//
313 //                      Calling Convention Implementation
314 //
315 //  The lower operations present on calling convention works on this order:
316 //      LowerCALL (virt regs --> phys regs, virt regs --> stack) 
317 //      LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
318 //      LowerRET (virt regs --> phys regs)
319 //      LowerCALL (phys regs --> virt regs)
320 //
321 //===----------------------------------------------------------------------===//
322
323 #include "MipsGenCallingConv.inc"
324
325 //===----------------------------------------------------------------------===//
326 //                  CALL Calling Convention Implementation
327 //===----------------------------------------------------------------------===//
328
329 /// Mips custom CALL implementation
330 SDOperand MipsTargetLowering::
331 LowerCALL(SDOperand Op, SelectionDAG &DAG)
332 {
333   unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
334
335   // By now, only CallingConv::C implemented
336   switch (CallingConv) {
337     default:
338       assert(0 && "Unsupported calling convention");
339     case CallingConv::Fast:
340     case CallingConv::C:
341       return LowerCCCCallTo(Op, DAG, CallingConv);
342   }
343 }
344
345 /// LowerCCCCallTo - functions arguments are copied from virtual
346 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
347 /// CALLSEQ_END are emitted.
348 /// TODO: isVarArg, isTailCall.
349 SDOperand MipsTargetLowering::
350 LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG, unsigned CC) 
351 {
352   MachineFunction &MF = DAG.getMachineFunction();
353
354   SDOperand Chain  = Op.getOperand(0);
355   SDOperand Callee = Op.getOperand(4);
356   bool isVarArg    = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
357
358   MachineFrameInfo *MFI = MF.getFrameInfo();
359
360   // Analyze operands of the call, assigning locations to each operand.
361   SmallVector<CCValAssign, 16> ArgLocs;
362   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
363
364   // To meet ABI, Mips must always allocate 16 bytes on
365   // the stack (even if less than 4 are used as arguments)
366   int VTsize = MVT(MVT::i32).getSizeInBits()/8;
367   MFI->CreateFixedObject(VTsize, (VTsize*3));
368
369   CCInfo.AnalyzeCallOperands(Op.Val, CC_Mips);
370   
371   // Get a count of how many bytes are to be pushed on the stack.
372   unsigned NumBytes = CCInfo.getNextStackOffset();
373   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, 
374                                  getPointerTy()));
375
376   // With EABI is it possible to have 16 args on registers.
377   SmallVector<std::pair<unsigned, SDOperand>, 16> RegsToPass;
378   SmallVector<SDOperand, 8> MemOpChains;
379
380   // First/LastArgStackLoc contains the first/last 
381   // "at stack" argument location.
382   int LastArgStackLoc = 0;
383   unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
384
385   // Walk the register/memloc assignments, inserting copies/loads.
386   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
387     CCValAssign &VA = ArgLocs[i];
388
389     // Arguments start after the 5 first operands of ISD::CALL
390     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
391     
392     // Promote the value if needed.
393     switch (VA.getLocInfo()) {
394     default: assert(0 && "Unknown loc info!");
395     case CCValAssign::Full: break;
396     case CCValAssign::SExt:
397       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
398       break;
399     case CCValAssign::ZExt:
400       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
401       break;
402     case CCValAssign::AExt:
403       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
404       break;
405     }
406     
407     // Arguments that can be passed on register must be kept at 
408     // RegsToPass vector
409     if (VA.isRegLoc()) {
410       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
411       continue;
412     }
413     
414     // Register cant get to this point...
415     assert(VA.isMemLoc());
416     
417     // Create the frame index object for this incoming parameter
418     // This guarantees that when allocating Local Area the firsts
419     // 16 bytes which are alwayes reserved won't be overwritten
420     // if O32 ABI is used. For EABI the first address is zero.
421     LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
422     int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
423                                     LastArgStackLoc);
424
425     SDOperand PtrOff = DAG.getFrameIndex(FI,getPointerTy());
426
427     // emit ISD::STORE whichs stores the 
428     // parameter value to a stack Location
429     MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
430   }
431
432   // Transform all store nodes into one single node because all store
433   // nodes are independent of each other.
434   if (!MemOpChains.empty())     
435     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, 
436                         &MemOpChains[0], MemOpChains.size());
437
438   // Build a sequence of copy-to-reg nodes chained together with token 
439   // chain and flag operands which copy the outgoing args into registers.
440   // The InFlag in necessary since all emited instructions must be
441   // stuck together.
442   SDOperand InFlag;
443   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
444     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, 
445                              RegsToPass[i].second, InFlag);
446     InFlag = Chain.getValue(1);
447   }
448
449   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
450   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 
451   // node so that legalize doesn't hack it. 
452   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 
453     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
454   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
455     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
456
457
458   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
459   //             = Chain, Callee, Reg#1, Reg#2, ...  
460   //
461   // Returns a chain & a flag for retval copy to use.
462   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
463   SmallVector<SDOperand, 8> Ops;
464   Ops.push_back(Chain);
465   Ops.push_back(Callee);
466
467   // Add argument registers to the end of the list so that they are 
468   // known live into the call.
469   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
470     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
471                                   RegsToPass[i].second.getValueType()));
472
473   if (InFlag.Val)
474     Ops.push_back(InFlag);
475
476   Chain  = DAG.getNode(MipsISD::JmpLink, NodeTys, &Ops[0], Ops.size());
477   InFlag = Chain.getValue(1);
478
479   // Create the CALLSEQ_END node.
480   Chain = DAG.getCALLSEQ_END(Chain,
481                              DAG.getConstant(NumBytes, getPointerTy()),
482                              DAG.getConstant(0, getPointerTy()),
483                              InFlag);
484   InFlag = Chain.getValue(1);
485
486   // Create a stack location to hold GP when PIC is used. This stack 
487   // location is used on function prologue to save GP and also after all 
488   // emited CALL's to restore GP. 
489   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
490       // Function can have an arbitrary number of calls, so 
491       // hold the LastArgStackLoc with the biggest offset.
492       int FI;
493       MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
494       if (LastArgStackLoc >= MipsFI->getGPStackOffset()) {
495         LastArgStackLoc = (!LastArgStackLoc) ? (16) : (LastArgStackLoc+4);
496         // Create the frame index only once. SPOffset here can be anything 
497         // (this will be fixed on processFunctionBeforeFrameFinalized)
498         if (MipsFI->getGPStackOffset() == -1) {
499           FI = MFI->CreateFixedObject(4, 0);
500           MipsFI->setGPFI(FI);
501         }
502         MipsFI->setGPStackOffset(LastArgStackLoc);
503       }
504
505       // Reload GP value.
506       FI = MipsFI->getGPFI();
507       SDOperand FIN = DAG.getFrameIndex(FI,getPointerTy());
508       SDOperand GPLoad = DAG.getLoad(MVT::i32, Chain, FIN, NULL, 0);
509       Chain = GPLoad.getValue(1);
510       Chain = DAG.getCopyToReg(Chain, DAG.getRegister(Mips::GP, MVT::i32), 
511                                GPLoad, SDOperand(0,0));
512       InFlag = Chain.getValue(1);
513   }      
514
515   // Handle result values, copying them out of physregs into vregs that we
516   // return.
517   return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
518 }
519
520 /// LowerCallResult - Lower the result values of an ISD::CALL into the
521 /// appropriate copies out of appropriate physical registers.  This assumes that
522 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
523 /// being lowered. Returns a SDNode with the same number of values as the 
524 /// ISD::CALL.
525 SDNode *MipsTargetLowering::
526 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall, 
527         unsigned CallingConv, SelectionDAG &DAG) {
528   
529   bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
530
531   // Assign locations to each value returned by this call.
532   SmallVector<CCValAssign, 16> RVLocs;
533   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
534
535   CCInfo.AnalyzeCallResult(TheCall, RetCC_Mips);
536   SmallVector<SDOperand, 8> ResultVals;
537
538   // Copy all of the result registers out of their specified physreg.
539   for (unsigned i = 0; i != RVLocs.size(); ++i) {
540     Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
541                                  RVLocs[i].getValVT(), InFlag).getValue(1);
542     InFlag = Chain.getValue(2);
543     ResultVals.push_back(Chain.getValue(0));
544   }
545   
546   ResultVals.push_back(Chain);
547
548   // Merge everything together with a MERGE_VALUES node.
549   return DAG.getMergeValues(TheCall->getVTList(), &ResultVals[0],
550                             ResultVals.size()).Val;
551 }
552
553 //===----------------------------------------------------------------------===//
554 //             FORMAL_ARGUMENTS Calling Convention Implementation
555 //===----------------------------------------------------------------------===//
556
557 /// Mips custom FORMAL_ARGUMENTS implementation
558 SDOperand MipsTargetLowering::
559 LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) 
560 {
561   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
562   switch(CC) 
563   {
564     default:
565       assert(0 && "Unsupported calling convention");
566     case CallingConv::C:
567       return LowerCCCArguments(Op, DAG);
568   }
569 }
570
571 /// LowerCCCArguments - transform physical registers into
572 /// virtual registers and generate load operations for
573 /// arguments places on the stack.
574 /// TODO: isVarArg
575 SDOperand MipsTargetLowering::
576 LowerCCCArguments(SDOperand Op, SelectionDAG &DAG) 
577 {
578   SDOperand Root        = Op.getOperand(0);
579   MachineFunction &MF   = DAG.getMachineFunction();
580   MachineFrameInfo *MFI = MF.getFrameInfo();
581   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
582
583   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
584   unsigned CC   = DAG.getMachineFunction().getFunction()->getCallingConv();
585
586   unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
587
588   // GP holds the GOT address on PIC calls.
589   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
590     AddLiveIn(MF, Mips::GP, Mips::CPURegsRegisterClass);
591
592   // Assign locations to all of the incoming arguments.
593   SmallVector<CCValAssign, 16> ArgLocs;
594   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
595
596   CCInfo.AnalyzeFormalArguments(Op.Val, CC_Mips);
597   SmallVector<SDOperand, 16> ArgValues;
598   SDOperand StackPtr;
599
600   unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
601
602   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
603
604     CCValAssign &VA = ArgLocs[i];
605
606     // Arguments stored on registers
607     if (VA.isRegLoc()) {
608       MVT RegVT = VA.getLocVT();
609       TargetRegisterClass *RC;
610             
611       if (RegVT == MVT::i32)
612         RC = Mips::CPURegsRegisterClass; 
613       else if (RegVT == MVT::f32) {
614         if (Subtarget->isSingleFloat())
615           RC = Mips::FGR32RegisterClass;
616         else
617           RC = Mips::AFGR32RegisterClass;
618       } else if (RegVT == MVT::f64) {
619         if (!Subtarget->isSingleFloat()) 
620           RC = Mips::AFGR64RegisterClass;
621       } else  
622         assert(0 && "RegVT not supported by FORMAL_ARGUMENTS Lowering");
623
624       // Transform the arguments stored on 
625       // physical registers into virtual ones
626       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
627       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
628       
629       // If this is an 8 or 16-bit value, it is really passed promoted 
630       // to 32 bits.  Insert an assert[sz]ext to capture this, then 
631       // truncate to the right size.
632       if (VA.getLocInfo() == CCValAssign::SExt)
633         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
634                                DAG.getValueType(VA.getValVT()));
635       else if (VA.getLocInfo() == CCValAssign::ZExt)
636         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
637                                DAG.getValueType(VA.getValVT()));
638       
639       if (VA.getLocInfo() != CCValAssign::Full)
640         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
641
642       ArgValues.push_back(ArgValue);
643
644       // To meet ABI, when VARARGS are passed on registers, the registers
645       // must have their values written to the caller stack frame. 
646       if ((isVarArg) && (Subtarget->isABI_O32())) {
647         if (StackPtr.Val == 0)
648           StackPtr = DAG.getRegister(StackReg, getPointerTy());
649      
650         // The stack pointer offset is relative to the caller stack frame. 
651         // Since the real stack size is unknown here, a negative SPOffset 
652         // is used so there's a way to adjust these offsets when the stack
653         // size get known (on EliminateFrameIndex). A dummy SPOffset is 
654         // used instead of a direct negative address (which is recorded to
655         // be used on emitPrologue) to avoid mis-calc of the first stack 
656         // offset on PEI::calculateFrameObjectOffsets.
657         // Arguments are always 32-bit.
658         int FI = MFI->CreateFixedObject(4, 0);
659         MipsFI->recordStoreVarArgsFI(FI, -(4+(i*4)));
660         SDOperand PtrOff = DAG.getFrameIndex(FI, getPointerTy());
661       
662         // emit ISD::STORE whichs stores the 
663         // parameter value to a stack Location
664         ArgValues.push_back(DAG.getStore(Root, ArgValue, PtrOff, NULL, 0));
665       }
666
667     } else { // VA.isRegLoc()
668
669       // sanity check
670       assert(VA.isMemLoc());
671       
672       // The stack pointer offset is relative to the caller stack frame. 
673       // Since the real stack size is unknown here, a negative SPOffset 
674       // is used so there's a way to adjust these offsets when the stack
675       // size get known (on EliminateFrameIndex). A dummy SPOffset is 
676       // used instead of a direct negative address (which is recorded to
677       // be used on emitPrologue) to avoid mis-calc of the first stack 
678       // offset on PEI::calculateFrameObjectOffsets.
679       // Arguments are always 32-bit.
680       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
681       int FI = MFI->CreateFixedObject(ArgSize, 0);
682       MipsFI->recordLoadArgsFI(FI, -(ArgSize+
683         (FirstStackArgLoc + VA.getLocMemOffset())));
684
685       // Create load nodes to retrieve arguments from the stack
686       SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
687       ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
688     }
689   }
690
691   // The mips ABIs for returning structs by value requires that we copy
692   // the sret argument into $v0 for the return. Save the argument into
693   // a virtual register so that we can access it from the return points.
694   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
695     unsigned Reg = MipsFI->getSRetReturnReg();
696     if (!Reg) {
697       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
698       MipsFI->setSRetReturnReg(Reg);
699     }
700     SDOperand Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
701     Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
702   }
703
704   ArgValues.push_back(Root);
705
706   // Return the new list of results.
707   return DAG.getMergeValues(Op.Val->getVTList(), &ArgValues[0],
708                             ArgValues.size()).getValue(Op.ResNo);
709 }
710
711 //===----------------------------------------------------------------------===//
712 //               Return Value Calling Convention Implementation
713 //===----------------------------------------------------------------------===//
714
715 SDOperand MipsTargetLowering::
716 LowerRET(SDOperand Op, SelectionDAG &DAG)
717 {
718   // CCValAssign - represent the assignment of
719   // the return value to a location
720   SmallVector<CCValAssign, 16> RVLocs;
721   unsigned CC   = DAG.getMachineFunction().getFunction()->getCallingConv();
722   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
723
724   // CCState - Info about the registers and stack slot.
725   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
726
727   // Analize return values of ISD::RET
728   CCInfo.AnalyzeReturn(Op.Val, RetCC_Mips);
729
730   // If this is the first return lowered for this function, add 
731   // the regs to the liveout set for the function.
732   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
733     for (unsigned i = 0; i != RVLocs.size(); ++i)
734       if (RVLocs[i].isRegLoc())
735         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
736   }
737
738   // The chain is always operand #0
739   SDOperand Chain = Op.getOperand(0);
740   SDOperand Flag;
741
742   // Copy the result values into the output registers.
743   for (unsigned i = 0; i != RVLocs.size(); ++i) {
744     CCValAssign &VA = RVLocs[i];
745     assert(VA.isRegLoc() && "Can only return in registers!");
746
747     // ISD::RET => ret chain, (regnum1,val1), ...
748     // So i*2+1 index only the regnums
749     Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1), Flag);
750
751     // guarantee that all emitted copies are
752     // stuck together, avoiding something bad
753     Flag = Chain.getValue(1);
754   }
755
756   // The mips ABIs for returning structs by value requires that we copy
757   // the sret argument into $v0 for the return. We saved the argument into
758   // a virtual register in the entry block, so now we copy the value out
759   // and into $v0.
760   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
761     MachineFunction &MF      = DAG.getMachineFunction();
762     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
763     unsigned Reg = MipsFI->getSRetReturnReg();
764
765     if (!Reg) 
766       assert(0 && "sret virtual register not created in the entry block");
767     SDOperand Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
768
769     Chain = DAG.getCopyToReg(Chain, Mips::V0, Val, Flag);
770     Flag = Chain.getValue(1);
771   }
772
773   // Return on Mips is always a "jr $ra"
774   if (Flag.Val)
775     return DAG.getNode(MipsISD::Ret, MVT::Other, 
776                        Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
777   else // Return Void
778     return DAG.getNode(MipsISD::Ret, MVT::Other, 
779                        Chain, DAG.getRegister(Mips::RA, MVT::i32));
780 }
781
782 //===----------------------------------------------------------------------===//
783 //                           Mips Inline Assembly Support
784 //===----------------------------------------------------------------------===//
785
786 /// getConstraintType - Given a constraint letter, return the type of
787 /// constraint it is for this target.
788 MipsTargetLowering::ConstraintType MipsTargetLowering::
789 getConstraintType(const std::string &Constraint) const 
790 {
791   // Mips specific constrainy 
792   // GCC config/mips/constraints.md
793   //
794   // 'd' : An address register. Equivalent to r 
795   //       unless generating MIPS16 code. 
796   // 'y' : Equivalent to r; retained for 
797   //       backwards compatibility. 
798   // 'f' : Float Point registers.      
799   if (Constraint.size() == 1) {
800     switch (Constraint[0]) {
801       default : break;
802       case 'd':     
803       case 'y': 
804       case 'f':
805         return C_RegisterClass;
806         break;
807     }
808   }
809   return TargetLowering::getConstraintType(Constraint);
810 }
811
812 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
813 /// return a list of registers that can be used to satisfy the constraint.
814 /// This should only be used for C_RegisterClass constraints.
815 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
816 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
817 {
818   if (Constraint.size() == 1) {
819     switch (Constraint[0]) {
820     case 'r':
821       return std::make_pair(0U, Mips::CPURegsRegisterClass);
822     case 'f':
823       if (VT == MVT::f32)
824         if (Subtarget->isSingleFloat())
825           return std::make_pair(0U, Mips::FGR32RegisterClass);
826         else
827           return std::make_pair(0U, Mips::AFGR32RegisterClass);
828       if (VT == MVT::f64)    
829         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
830           return std::make_pair(0U, Mips::AFGR64RegisterClass);
831     }
832   }
833   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
834 }
835
836 /// Given a register class constraint, like 'r', if this corresponds directly
837 /// to an LLVM register class, return a register of 0 and the register class
838 /// pointer.
839 std::vector<unsigned> MipsTargetLowering::
840 getRegClassForInlineAsmConstraint(const std::string &Constraint,
841                                   MVT VT) const
842 {
843   if (Constraint.size() != 1)
844     return std::vector<unsigned>();
845
846   switch (Constraint[0]) {         
847     default : break;
848     case 'r':
849     // GCC Mips Constraint Letters
850     case 'd':     
851     case 'y': 
852       return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3, 
853              Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1, 
854              Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7, 
855              Mips::T8, 0);
856
857     case 'f':
858       if (VT == MVT::f32)
859         if (Subtarget->isSingleFloat())
860           return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
861                  Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
862                  Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
863                  Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
864                  Mips::F30, Mips::F31, 0);
865         else
866           return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8, 
867                  Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26, 
868                  Mips::F28, Mips::F30, 0);
869
870       if (VT == MVT::f64)    
871         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
872           return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4, 
873                  Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13, 
874                  Mips::D14, Mips::D15, 0);
875   }
876   return std::vector<unsigned>();
877 }