Set an operation expansion, noticed while running
[oota-llvm.git] / lib / Target / Alpha / AlphaISelLowering.cpp
1 //===-- AlphaISelLowering.cpp - Alpha 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 implements the AlphaISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "AlphaISelLowering.h"
15 #include "AlphaTargetMachine.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Function.h"
24 #include "llvm/Module.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 using namespace llvm;
30
31 /// AddLiveIn - This helper function adds the specified physical register to the
32 /// MachineFunction as a live in value.  It also creates a corresponding virtual
33 /// register for it.
34 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
35                           TargetRegisterClass *RC) {
36   assert(RC->contains(PReg) && "Not the correct regclass!");
37   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
38   MF.getRegInfo().addLiveIn(PReg, VReg);
39   return VReg;
40 }
41
42 AlphaTargetLowering::AlphaTargetLowering(TargetMachine &TM) : TargetLowering(TM) {
43   // Set up the TargetLowering object.
44   //I am having problems with shr n i8 1
45   setShiftAmountType(MVT::i64);
46   setBooleanContents(ZeroOrOneBooleanContent);
47   
48   setUsesGlobalOffsetTable(true);
49   
50   addRegisterClass(MVT::i64, Alpha::GPRCRegisterClass);
51   addRegisterClass(MVT::f64, Alpha::F8RCRegisterClass);
52   addRegisterClass(MVT::f32, Alpha::F4RCRegisterClass);
53
54   // We want to custom lower some of our intrinsics.
55   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
56
57   setLoadExtAction(ISD::EXTLOAD, MVT::i1,  Promote);
58   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
59   
60   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
61   setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
62   
63   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
64   setLoadExtAction(ISD::SEXTLOAD, MVT::i8,  Expand);
65   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
66
67   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
68
69   //  setOperationAction(ISD::BRIND,        MVT::Other,   Expand);
70   setOperationAction(ISD::BR_JT,        MVT::Other, Expand);
71   setOperationAction(ISD::BR_CC,        MVT::Other, Expand);
72   setOperationAction(ISD::SELECT_CC,    MVT::Other, Expand);  
73
74   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
75
76   setOperationAction(ISD::FREM, MVT::f32, Expand);
77   setOperationAction(ISD::FREM, MVT::f64, Expand);
78   
79   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
80   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
81   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
82   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
83
84   if (!TM.getSubtarget<AlphaSubtarget>().hasCT()) {
85     setOperationAction(ISD::CTPOP    , MVT::i64  , Expand);
86     setOperationAction(ISD::CTTZ     , MVT::i64  , Expand);
87     setOperationAction(ISD::CTLZ     , MVT::i64  , Expand);
88   }
89   setOperationAction(ISD::BSWAP    , MVT::i64, Expand);
90   setOperationAction(ISD::ROTL     , MVT::i64, Expand);
91   setOperationAction(ISD::ROTR     , MVT::i64, Expand);
92   
93   setOperationAction(ISD::SREM     , MVT::i64, Custom);
94   setOperationAction(ISD::UREM     , MVT::i64, Custom);
95   setOperationAction(ISD::SDIV     , MVT::i64, Custom);
96   setOperationAction(ISD::UDIV     , MVT::i64, Custom);
97
98   setOperationAction(ISD::ADDC     , MVT::i64, Expand);
99   setOperationAction(ISD::ADDE     , MVT::i64, Expand);
100   setOperationAction(ISD::SUBC     , MVT::i64, Expand);
101   setOperationAction(ISD::SUBE     , MVT::i64, Expand);
102
103   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
104   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
105
106
107   // We don't support sin/cos/sqrt/pow
108   setOperationAction(ISD::FSIN , MVT::f64, Expand);
109   setOperationAction(ISD::FCOS , MVT::f64, Expand);
110   setOperationAction(ISD::FSIN , MVT::f32, Expand);
111   setOperationAction(ISD::FCOS , MVT::f32, Expand);
112
113   setOperationAction(ISD::FSQRT, MVT::f64, Expand);
114   setOperationAction(ISD::FSQRT, MVT::f32, Expand);
115
116   setOperationAction(ISD::FPOW , MVT::f32, Expand);
117   setOperationAction(ISD::FPOW , MVT::f64, Expand);
118
119   setOperationAction(ISD::SETCC, MVT::f32, Promote);
120
121   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Promote);
122
123   // We don't have line number support yet.
124   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
125   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
126   setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
127   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
128
129   // Not implemented yet.
130   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 
131   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
132   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
133
134   // We want to legalize GlobalAddress and ConstantPool and
135   // ExternalSymbols nodes into the appropriate instructions to
136   // materialize the address.
137   setOperationAction(ISD::GlobalAddress,  MVT::i64, Custom);
138   setOperationAction(ISD::ConstantPool,   MVT::i64, Custom);
139   setOperationAction(ISD::ExternalSymbol, MVT::i64, Custom);
140   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
141
142   setOperationAction(ISD::VASTART, MVT::Other, Custom);
143   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
144   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
145   setOperationAction(ISD::VAARG,   MVT::Other, Custom);
146   setOperationAction(ISD::VAARG,   MVT::i32,   Custom);
147
148   setOperationAction(ISD::RET,     MVT::Other, Custom);
149
150   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
151   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
152
153   setStackPointerRegisterToSaveRestore(Alpha::R30);
154
155   addLegalFPImmediate(APFloat(+0.0)); //F31
156   addLegalFPImmediate(APFloat(+0.0f)); //F31
157   addLegalFPImmediate(APFloat(-0.0)); //-F31
158   addLegalFPImmediate(APFloat(-0.0f)); //-F31
159
160   setJumpBufSize(272);
161   setJumpBufAlignment(16);
162
163   computeRegisterProperties();
164 }
165
166 MVT AlphaTargetLowering::getSetCCResultType(MVT VT) const {
167   return MVT::i64;
168 }
169
170 const char *AlphaTargetLowering::getTargetNodeName(unsigned Opcode) const {
171   switch (Opcode) {
172   default: return 0;
173   case AlphaISD::CVTQT_: return "Alpha::CVTQT_";
174   case AlphaISD::CVTQS_: return "Alpha::CVTQS_";
175   case AlphaISD::CVTTQ_: return "Alpha::CVTTQ_";
176   case AlphaISD::GPRelHi: return "Alpha::GPRelHi";
177   case AlphaISD::GPRelLo: return "Alpha::GPRelLo";
178   case AlphaISD::RelLit: return "Alpha::RelLit";
179   case AlphaISD::GlobalRetAddr: return "Alpha::GlobalRetAddr";
180   case AlphaISD::CALL:   return "Alpha::CALL";
181   case AlphaISD::DivCall: return "Alpha::DivCall";
182   case AlphaISD::RET_FLAG: return "Alpha::RET_FLAG";
183   case AlphaISD::COND_BRANCH_I: return "Alpha::COND_BRANCH_I";
184   case AlphaISD::COND_BRANCH_F: return "Alpha::COND_BRANCH_F";
185   }
186 }
187
188 /// getFunctionAlignment - Return the Log2 alignment of this function.
189 unsigned AlphaTargetLowering::getFunctionAlignment(const Function *F) const {
190   return 4;
191 }
192
193 static SDValue LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
194   MVT PtrVT = Op.getValueType();
195   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
196   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
197   SDValue Zero = DAG.getConstant(0, PtrVT);
198   // FIXME there isn't really any debug info here
199   DebugLoc dl = Op.getDebugLoc();
200   
201   SDValue Hi = DAG.getNode(AlphaISD::GPRelHi,  dl, MVT::i64, JTI,
202                              DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
203   SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, JTI, Hi);
204   return Lo;
205 }
206
207 //http://www.cs.arizona.edu/computer.help/policy/DIGITAL_unix/
208 //AA-PY8AC-TET1_html/callCH3.html#BLOCK21
209
210 //For now, just use variable size stack frame format
211
212 //In a standard call, the first six items are passed in registers $16
213 //- $21 and/or registers $f16 - $f21. (See Section 4.1.2 for details
214 //of argument-to-register correspondence.) The remaining items are
215 //collected in a memory argument list that is a naturally aligned
216 //array of quadwords. In a standard call, this list, if present, must
217 //be passed at 0(SP).
218 //7 ... n         0(SP) ... (n-7)*8(SP)
219
220 // //#define FP    $15
221 // //#define RA    $26
222 // //#define PV    $27
223 // //#define GP    $29
224 // //#define SP    $30
225
226 static SDValue LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG,
227                                        int &VarArgsBase,
228                                        int &VarArgsOffset) {
229   MachineFunction &MF = DAG.getMachineFunction();
230   MachineFrameInfo *MFI = MF.getFrameInfo();
231   std::vector<SDValue> ArgValues;
232   SDValue Root = Op.getOperand(0);
233   DebugLoc dl = Op.getDebugLoc();
234
235   unsigned args_int[] = {
236     Alpha::R16, Alpha::R17, Alpha::R18, Alpha::R19, Alpha::R20, Alpha::R21};
237   unsigned args_float[] = {
238     Alpha::F16, Alpha::F17, Alpha::F18, Alpha::F19, Alpha::F20, Alpha::F21};
239   
240   for (unsigned ArgNo = 0, e = Op.getNode()->getNumValues()-1; ArgNo != e; ++ArgNo) {
241     SDValue argt;
242     MVT ObjectVT = Op.getValue(ArgNo).getValueType();
243     SDValue ArgVal;
244
245     if (ArgNo  < 6) {
246       switch (ObjectVT.getSimpleVT()) {
247       default:
248         assert(false && "Invalid value type!");
249       case MVT::f64:
250         args_float[ArgNo] = AddLiveIn(MF, args_float[ArgNo], 
251                                       &Alpha::F8RCRegClass);
252         ArgVal = DAG.getCopyFromReg(Root, dl, args_float[ArgNo], ObjectVT);
253         break;
254       case MVT::f32:
255         args_float[ArgNo] = AddLiveIn(MF, args_float[ArgNo], 
256                                       &Alpha::F4RCRegClass);
257         ArgVal = DAG.getCopyFromReg(Root, dl, args_float[ArgNo], ObjectVT);
258         break;
259       case MVT::i64:
260         args_int[ArgNo] = AddLiveIn(MF, args_int[ArgNo], 
261                                     &Alpha::GPRCRegClass);
262         ArgVal = DAG.getCopyFromReg(Root, dl, args_int[ArgNo], MVT::i64);
263         break;
264       }
265     } else { //more args
266       // Create the frame index object for this incoming parameter...
267       int FI = MFI->CreateFixedObject(8, 8 * (ArgNo - 6));
268
269       // Create the SelectionDAG nodes corresponding to a load
270       //from this parameter
271       SDValue FIN = DAG.getFrameIndex(FI, MVT::i64);
272       ArgVal = DAG.getLoad(ObjectVT, dl, Root, FIN, NULL, 0);
273     }
274     ArgValues.push_back(ArgVal);
275   }
276
277   // If the functions takes variable number of arguments, copy all regs to stack
278   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
279   if (isVarArg) {
280     VarArgsOffset = (Op.getNode()->getNumValues()-1) * 8;
281     std::vector<SDValue> LS;
282     for (int i = 0; i < 6; ++i) {
283       if (TargetRegisterInfo::isPhysicalRegister(args_int[i]))
284         args_int[i] = AddLiveIn(MF, args_int[i], &Alpha::GPRCRegClass);
285       SDValue argt = DAG.getCopyFromReg(Root, dl, args_int[i], MVT::i64);
286       int FI = MFI->CreateFixedObject(8, -8 * (6 - i));
287       if (i == 0) VarArgsBase = FI;
288       SDValue SDFI = DAG.getFrameIndex(FI, MVT::i64);
289       LS.push_back(DAG.getStore(Root, dl, argt, SDFI, NULL, 0));
290
291       if (TargetRegisterInfo::isPhysicalRegister(args_float[i]))
292         args_float[i] = AddLiveIn(MF, args_float[i], &Alpha::F8RCRegClass);
293       argt = DAG.getCopyFromReg(Root, dl, args_float[i], MVT::f64);
294       FI = MFI->CreateFixedObject(8, - 8 * (12 - i));
295       SDFI = DAG.getFrameIndex(FI, MVT::i64);
296       LS.push_back(DAG.getStore(Root, dl, argt, SDFI, NULL, 0));
297     }
298
299     //Set up a token factor with all the stack traffic
300     Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &LS[0], LS.size());
301   }
302
303   ArgValues.push_back(Root);
304
305   // Return the new list of results.
306   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
307                      &ArgValues[0], ArgValues.size());
308 }
309
310 static SDValue LowerRET(SDValue Op, SelectionDAG &DAG) {
311   DebugLoc dl = Op.getDebugLoc();
312   SDValue Copy = DAG.getCopyToReg(Op.getOperand(0), dl, Alpha::R26, 
313                                     DAG.getNode(AlphaISD::GlobalRetAddr, 
314                                                 DebugLoc::getUnknownLoc(),
315                                                 MVT::i64),
316                                     SDValue());
317   switch (Op.getNumOperands()) {
318   default:
319     llvm_unreachable("Do not know how to return this many arguments!");
320   case 1: 
321     break;
322     //return SDValue(); // ret void is legal
323   case 3: {
324     MVT ArgVT = Op.getOperand(1).getValueType();
325     unsigned ArgReg;
326     if (ArgVT.isInteger())
327       ArgReg = Alpha::R0;
328     else {
329       assert(ArgVT.isFloatingPoint());
330       ArgReg = Alpha::F0;
331     }
332     Copy = DAG.getCopyToReg(Copy, dl, ArgReg, 
333                             Op.getOperand(1), Copy.getValue(1));
334     if (DAG.getMachineFunction().getRegInfo().liveout_empty())
335       DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg);
336     break;
337   }
338   case 5: {
339     MVT ArgVT = Op.getOperand(1).getValueType();
340     unsigned ArgReg1, ArgReg2;
341     if (ArgVT.isInteger()) {
342       ArgReg1 = Alpha::R0;
343       ArgReg2 = Alpha::R1;
344     } else {
345       assert(ArgVT.isFloatingPoint());
346       ArgReg1 = Alpha::F0;
347       ArgReg2 = Alpha::F1;
348     }
349     Copy = DAG.getCopyToReg(Copy, dl, ArgReg1, 
350                             Op.getOperand(1), Copy.getValue(1));
351     if (std::find(DAG.getMachineFunction().getRegInfo().liveout_begin(), 
352                   DAG.getMachineFunction().getRegInfo().liveout_end(), ArgReg1)
353         == DAG.getMachineFunction().getRegInfo().liveout_end())
354       DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg1);
355     Copy = DAG.getCopyToReg(Copy, dl, ArgReg2, 
356                             Op.getOperand(3), Copy.getValue(1));
357     if (std::find(DAG.getMachineFunction().getRegInfo().liveout_begin(), 
358                    DAG.getMachineFunction().getRegInfo().liveout_end(), ArgReg2)
359         == DAG.getMachineFunction().getRegInfo().liveout_end())
360       DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg2);
361     break;
362   }
363   }
364   return DAG.getNode(AlphaISD::RET_FLAG, dl, 
365                      MVT::Other, Copy, Copy.getValue(1));
366 }
367
368 std::pair<SDValue, SDValue>
369 AlphaTargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy, 
370                                  bool RetSExt, bool RetZExt, bool isVarArg,
371                                  bool isInreg, unsigned NumFixedArgs,
372                                  unsigned CallingConv, 
373                                  bool isTailCall, SDValue Callee, 
374                                  ArgListTy &Args, SelectionDAG &DAG,
375                                  DebugLoc dl) {
376   int NumBytes = 0;
377   if (Args.size() > 6)
378     NumBytes = (Args.size() - 6) * 8;
379
380   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
381   std::vector<SDValue> args_to_use;
382   for (unsigned i = 0, e = Args.size(); i != e; ++i)
383   {
384     switch (getValueType(Args[i].Ty).getSimpleVT()) {
385     default: llvm_unreachable("Unexpected ValueType for argument!");
386     case MVT::i1:
387     case MVT::i8:
388     case MVT::i16:
389     case MVT::i32:
390       // Promote the integer to 64 bits.  If the input type is signed use a
391       // sign extend, otherwise use a zero extend.
392       if (Args[i].isSExt)
393         Args[i].Node = DAG.getNode(ISD::SIGN_EXTEND, dl, 
394                                    MVT::i64, Args[i].Node);
395       else if (Args[i].isZExt)
396         Args[i].Node = DAG.getNode(ISD::ZERO_EXTEND, dl,
397                                    MVT::i64, Args[i].Node);
398       else
399         Args[i].Node = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, Args[i].Node);
400       break;
401     case MVT::i64:
402     case MVT::f64:
403     case MVT::f32:
404       break;
405     }
406     args_to_use.push_back(Args[i].Node);
407   }
408
409   std::vector<MVT> RetVals;
410   MVT RetTyVT = getValueType(RetTy);
411   MVT ActualRetTyVT = RetTyVT;
412   if (RetTyVT.getSimpleVT() >= MVT::i1 && RetTyVT.getSimpleVT() <= MVT::i32)
413     ActualRetTyVT = MVT::i64;
414
415   if (RetTyVT != MVT::isVoid)
416     RetVals.push_back(ActualRetTyVT);
417   RetVals.push_back(MVT::Other);
418
419   std::vector<SDValue> Ops;
420   Ops.push_back(Chain);
421   Ops.push_back(Callee);
422   Ops.insert(Ops.end(), args_to_use.begin(), args_to_use.end());
423   SDValue TheCall = DAG.getNode(AlphaISD::CALL, dl, 
424                                 RetVals, &Ops[0], Ops.size());
425   Chain = TheCall.getValue(RetTyVT != MVT::isVoid);
426   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
427                              DAG.getIntPtrConstant(0, true), SDValue());
428   SDValue RetVal = TheCall;
429
430   if (RetTyVT != ActualRetTyVT) {
431     ISD::NodeType AssertKind = ISD::DELETED_NODE;
432     if (RetSExt)
433       AssertKind = ISD::AssertSext;
434     else if (RetZExt)
435       AssertKind = ISD::AssertZext;
436
437     if (AssertKind != ISD::DELETED_NODE)
438       RetVal = DAG.getNode(AssertKind, dl, MVT::i64, RetVal,
439                            DAG.getValueType(RetTyVT));
440
441     RetVal = DAG.getNode(ISD::TRUNCATE, dl, RetTyVT, RetVal);
442   }
443
444   return std::make_pair(RetVal, Chain);
445 }
446
447 void AlphaTargetLowering::LowerVAARG(SDNode *N, SDValue &Chain,
448                                      SDValue &DataPtr, SelectionDAG &DAG) {
449   Chain = N->getOperand(0);
450   SDValue VAListP = N->getOperand(1);
451   const Value *VAListS = cast<SrcValueSDNode>(N->getOperand(2))->getValue();
452   DebugLoc dl = N->getDebugLoc();
453
454   SDValue Base = DAG.getLoad(MVT::i64, dl, Chain, VAListP, VAListS, 0);
455   SDValue Tmp = DAG.getNode(ISD::ADD, dl, MVT::i64, VAListP,
456                               DAG.getConstant(8, MVT::i64));
457   SDValue Offset = DAG.getExtLoad(ISD::SEXTLOAD, dl, MVT::i64, Base.getValue(1),
458                                     Tmp, NULL, 0, MVT::i32);
459   DataPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Base, Offset);
460   if (N->getValueType(0).isFloatingPoint())
461   {
462     //if fp && Offset < 6*8, then subtract 6*8 from DataPtr
463     SDValue FPDataPtr = DAG.getNode(ISD::SUB, dl, MVT::i64, DataPtr,
464                                       DAG.getConstant(8*6, MVT::i64));
465     SDValue CC = DAG.getSetCC(dl, MVT::i64, Offset,
466                                 DAG.getConstant(8*6, MVT::i64), ISD::SETLT);
467     DataPtr = DAG.getNode(ISD::SELECT, dl, MVT::i64, CC, FPDataPtr, DataPtr);
468   }
469
470   SDValue NewOffset = DAG.getNode(ISD::ADD, dl, MVT::i64, Offset,
471                                     DAG.getConstant(8, MVT::i64));
472   Chain = DAG.getTruncStore(Offset.getValue(1), dl, NewOffset, Tmp, NULL, 0,
473                             MVT::i32);
474 }
475
476 /// LowerOperation - Provide custom lowering hooks for some operations.
477 ///
478 SDValue AlphaTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
479   DebugLoc dl = Op.getDebugLoc();
480   switch (Op.getOpcode()) {
481   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
482   case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG, 
483                                                            VarArgsBase,
484                                                            VarArgsOffset);
485
486   case ISD::RET: return LowerRET(Op,DAG);
487   case ISD::JumpTable: return LowerJumpTable(Op, DAG);
488
489   case ISD::INTRINSIC_WO_CHAIN: {
490     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
491     switch (IntNo) {
492     default: break;    // Don't custom lower most intrinsics.
493     case Intrinsic::alpha_umulh:
494       return DAG.getNode(ISD::MULHU, dl, MVT::i64, 
495                          Op.getOperand(1), Op.getOperand(2));
496     }
497   }
498
499   case ISD::SINT_TO_FP: {
500     assert(Op.getOperand(0).getValueType() == MVT::i64 &&
501            "Unhandled SINT_TO_FP type in custom expander!");
502     SDValue LD;
503     bool isDouble = Op.getValueType() == MVT::f64;
504     LD = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op.getOperand(0));
505     SDValue FP = DAG.getNode(isDouble?AlphaISD::CVTQT_:AlphaISD::CVTQS_, dl,
506                                isDouble?MVT::f64:MVT::f32, LD);
507     return FP;
508   }
509   case ISD::FP_TO_SINT: {
510     bool isDouble = Op.getOperand(0).getValueType() == MVT::f64;
511     SDValue src = Op.getOperand(0);
512
513     if (!isDouble) //Promote
514       src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, src);
515     
516     src = DAG.getNode(AlphaISD::CVTTQ_, dl, MVT::f64, src);
517
518     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, src);
519   }
520   case ISD::ConstantPool: {
521     ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
522     Constant *C = CP->getConstVal();
523     SDValue CPI = DAG.getTargetConstantPool(C, MVT::i64, CP->getAlignment());
524     // FIXME there isn't really any debug info here
525     
526     SDValue Hi = DAG.getNode(AlphaISD::GPRelHi,  dl, MVT::i64, CPI,
527                                DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
528     SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, CPI, Hi);
529     return Lo;
530   }
531   case ISD::GlobalTLSAddress:
532     llvm_unreachable("TLS not implemented for Alpha.");
533   case ISD::GlobalAddress: {
534     GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
535     GlobalValue *GV = GSDN->getGlobal();
536     SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i64, GSDN->getOffset());
537     // FIXME there isn't really any debug info here
538
539     //    if (!GV->hasWeakLinkage() && !GV->isDeclaration() && !GV->hasLinkOnceLinkage()) {
540     if (GV->hasLocalLinkage()) {
541       SDValue Hi = DAG.getNode(AlphaISD::GPRelHi,  dl, MVT::i64, GA,
542                                 DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
543       SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, GA, Hi);
544       return Lo;
545     } else
546       return DAG.getNode(AlphaISD::RelLit, dl, MVT::i64, GA, 
547                          DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
548   }
549   case ISD::ExternalSymbol: {
550     return DAG.getNode(AlphaISD::RelLit, dl, MVT::i64, 
551                        DAG.getTargetExternalSymbol(cast<ExternalSymbolSDNode>(Op)
552                                                    ->getSymbol(), MVT::i64),
553                        DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
554   }
555
556   case ISD::UREM:
557   case ISD::SREM:
558     //Expand only on constant case
559     if (Op.getOperand(1).getOpcode() == ISD::Constant) {
560       MVT VT = Op.getNode()->getValueType(0);
561       SDValue Tmp1 = Op.getNode()->getOpcode() == ISD::UREM ?
562         BuildUDIV(Op.getNode(), DAG, NULL) :
563         BuildSDIV(Op.getNode(), DAG, NULL);
564       Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Op.getOperand(1));
565       Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Op.getOperand(0), Tmp1);
566       return Tmp1;
567     }
568     //fall through
569   case ISD::SDIV:
570   case ISD::UDIV:
571     if (Op.getValueType().isInteger()) {
572       if (Op.getOperand(1).getOpcode() == ISD::Constant)
573         return Op.getOpcode() == ISD::SDIV ? BuildSDIV(Op.getNode(), DAG, NULL) 
574           : BuildUDIV(Op.getNode(), DAG, NULL);
575       const char* opstr = 0;
576       switch (Op.getOpcode()) {
577       case ISD::UREM: opstr = "__remqu"; break;
578       case ISD::SREM: opstr = "__remq";  break;
579       case ISD::UDIV: opstr = "__divqu"; break;
580       case ISD::SDIV: opstr = "__divq";  break;
581       }
582       SDValue Tmp1 = Op.getOperand(0),
583         Tmp2 = Op.getOperand(1),
584         Addr = DAG.getExternalSymbol(opstr, MVT::i64);
585       return DAG.getNode(AlphaISD::DivCall, dl, MVT::i64, Addr, Tmp1, Tmp2);
586     }
587     break;
588
589   case ISD::VAARG: {
590     SDValue Chain, DataPtr;
591     LowerVAARG(Op.getNode(), Chain, DataPtr, DAG);
592
593     SDValue Result;
594     if (Op.getValueType() == MVT::i32)
595       Result = DAG.getExtLoad(ISD::SEXTLOAD, dl, MVT::i64, Chain, DataPtr,
596                               NULL, 0, MVT::i32);
597     else
598       Result = DAG.getLoad(Op.getValueType(), dl, Chain, DataPtr, NULL, 0);
599     return Result;
600   }
601   case ISD::VACOPY: {
602     SDValue Chain = Op.getOperand(0);
603     SDValue DestP = Op.getOperand(1);
604     SDValue SrcP = Op.getOperand(2);
605     const Value *DestS = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
606     const Value *SrcS = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
607     
608     SDValue Val = DAG.getLoad(getPointerTy(), dl, Chain, SrcP, SrcS, 0);
609     SDValue Result = DAG.getStore(Val.getValue(1), dl, Val, DestP, DestS, 0);
610     SDValue NP = DAG.getNode(ISD::ADD, dl, MVT::i64, SrcP, 
611                                DAG.getConstant(8, MVT::i64));
612     Val = DAG.getExtLoad(ISD::SEXTLOAD, dl, MVT::i64, Result, 
613                          NP, NULL,0, MVT::i32);
614     SDValue NPD = DAG.getNode(ISD::ADD, dl, MVT::i64, DestP,
615                                 DAG.getConstant(8, MVT::i64));
616     return DAG.getTruncStore(Val.getValue(1), dl, Val, NPD, NULL, 0, MVT::i32);
617   }
618   case ISD::VASTART: {
619     SDValue Chain = Op.getOperand(0);
620     SDValue VAListP = Op.getOperand(1);
621     const Value *VAListS = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
622     
623     // vastart stores the address of the VarArgsBase and VarArgsOffset
624     SDValue FR  = DAG.getFrameIndex(VarArgsBase, MVT::i64);
625     SDValue S1  = DAG.getStore(Chain, dl, FR, VAListP, VAListS, 0);
626     SDValue SA2 = DAG.getNode(ISD::ADD, dl, MVT::i64, VAListP,
627                                 DAG.getConstant(8, MVT::i64));
628     return DAG.getTruncStore(S1, dl, DAG.getConstant(VarArgsOffset, MVT::i64),
629                              SA2, NULL, 0, MVT::i32);
630   }
631   case ISD::RETURNADDR:        
632     return DAG.getNode(AlphaISD::GlobalRetAddr, DebugLoc::getUnknownLoc(),
633                        MVT::i64);
634       //FIXME: implement
635   case ISD::FRAMEADDR:          break;
636   }
637   
638   return SDValue();
639 }
640
641 void AlphaTargetLowering::ReplaceNodeResults(SDNode *N,
642                                              SmallVectorImpl<SDValue>&Results,
643                                              SelectionDAG &DAG) {
644   DebugLoc dl = N->getDebugLoc();
645   assert(N->getValueType(0) == MVT::i32 &&
646          N->getOpcode() == ISD::VAARG &&
647          "Unknown node to custom promote!");
648
649   SDValue Chain, DataPtr;
650   LowerVAARG(N, Chain, DataPtr, DAG);
651   SDValue Res = DAG.getLoad(N->getValueType(0), dl, Chain, DataPtr, NULL, 0);
652   Results.push_back(Res);
653   Results.push_back(SDValue(Res.getNode(), 1));
654 }
655
656
657 //Inline Asm
658
659 /// getConstraintType - Given a constraint letter, return the type of
660 /// constraint it is for this target.
661 AlphaTargetLowering::ConstraintType 
662 AlphaTargetLowering::getConstraintType(const std::string &Constraint) const {
663   if (Constraint.size() == 1) {
664     switch (Constraint[0]) {
665     default: break;
666     case 'f':
667     case 'r':
668       return C_RegisterClass;
669     }
670   }
671   return TargetLowering::getConstraintType(Constraint);
672 }
673
674 std::vector<unsigned> AlphaTargetLowering::
675 getRegClassForInlineAsmConstraint(const std::string &Constraint,
676                                   MVT VT) const {
677   if (Constraint.size() == 1) {
678     switch (Constraint[0]) {
679     default: break;  // Unknown constriant letter
680     case 'f': 
681       return make_vector<unsigned>(Alpha::F0 , Alpha::F1 , Alpha::F2 ,
682                                    Alpha::F3 , Alpha::F4 , Alpha::F5 ,
683                                    Alpha::F6 , Alpha::F7 , Alpha::F8 , 
684                                    Alpha::F9 , Alpha::F10, Alpha::F11, 
685                                    Alpha::F12, Alpha::F13, Alpha::F14, 
686                                    Alpha::F15, Alpha::F16, Alpha::F17, 
687                                    Alpha::F18, Alpha::F19, Alpha::F20, 
688                                    Alpha::F21, Alpha::F22, Alpha::F23, 
689                                    Alpha::F24, Alpha::F25, Alpha::F26, 
690                                    Alpha::F27, Alpha::F28, Alpha::F29, 
691                                    Alpha::F30, Alpha::F31, 0);
692     case 'r': 
693       return make_vector<unsigned>(Alpha::R0 , Alpha::R1 , Alpha::R2 , 
694                                    Alpha::R3 , Alpha::R4 , Alpha::R5 , 
695                                    Alpha::R6 , Alpha::R7 , Alpha::R8 , 
696                                    Alpha::R9 , Alpha::R10, Alpha::R11, 
697                                    Alpha::R12, Alpha::R13, Alpha::R14, 
698                                    Alpha::R15, Alpha::R16, Alpha::R17, 
699                                    Alpha::R18, Alpha::R19, Alpha::R20, 
700                                    Alpha::R21, Alpha::R22, Alpha::R23, 
701                                    Alpha::R24, Alpha::R25, Alpha::R26, 
702                                    Alpha::R27, Alpha::R28, Alpha::R29, 
703                                    Alpha::R30, Alpha::R31, 0);
704     }
705   }
706   
707   return std::vector<unsigned>();
708 }
709 //===----------------------------------------------------------------------===//
710 //  Other Lowering Code
711 //===----------------------------------------------------------------------===//
712
713 MachineBasicBlock *
714 AlphaTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
715                                                  MachineBasicBlock *BB) const {
716   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
717   assert((MI->getOpcode() == Alpha::CAS32 ||
718           MI->getOpcode() == Alpha::CAS64 ||
719           MI->getOpcode() == Alpha::LAS32 ||
720           MI->getOpcode() == Alpha::LAS64 ||
721           MI->getOpcode() == Alpha::SWAP32 ||
722           MI->getOpcode() == Alpha::SWAP64) &&
723          "Unexpected instr type to insert");
724
725   bool is32 = MI->getOpcode() == Alpha::CAS32 || 
726     MI->getOpcode() == Alpha::LAS32 ||
727     MI->getOpcode() == Alpha::SWAP32;
728   
729   //Load locked store conditional for atomic ops take on the same form
730   //start:
731   //ll
732   //do stuff (maybe branch to exit)
733   //sc
734   //test sc and maybe branck to start
735   //exit:
736   const BasicBlock *LLVM_BB = BB->getBasicBlock();
737   DebugLoc dl = MI->getDebugLoc();
738   MachineFunction::iterator It = BB;
739   ++It;
740   
741   MachineBasicBlock *thisMBB = BB;
742   MachineFunction *F = BB->getParent();
743   MachineBasicBlock *llscMBB = F->CreateMachineBasicBlock(LLVM_BB);
744   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
745
746   sinkMBB->transferSuccessors(thisMBB);
747
748   F->insert(It, llscMBB);
749   F->insert(It, sinkMBB);
750
751   BuildMI(thisMBB, dl, TII->get(Alpha::BR)).addMBB(llscMBB);
752   
753   unsigned reg_res = MI->getOperand(0).getReg(),
754     reg_ptr = MI->getOperand(1).getReg(),
755     reg_v2 = MI->getOperand(2).getReg(),
756     reg_store = F->getRegInfo().createVirtualRegister(&Alpha::GPRCRegClass);
757
758   BuildMI(llscMBB, dl, TII->get(is32 ? Alpha::LDL_L : Alpha::LDQ_L), 
759           reg_res).addImm(0).addReg(reg_ptr);
760   switch (MI->getOpcode()) {
761   case Alpha::CAS32:
762   case Alpha::CAS64: {
763     unsigned reg_cmp 
764       = F->getRegInfo().createVirtualRegister(&Alpha::GPRCRegClass);
765     BuildMI(llscMBB, dl, TII->get(Alpha::CMPEQ), reg_cmp)
766       .addReg(reg_v2).addReg(reg_res);
767     BuildMI(llscMBB, dl, TII->get(Alpha::BEQ))
768       .addImm(0).addReg(reg_cmp).addMBB(sinkMBB);
769     BuildMI(llscMBB, dl, TII->get(Alpha::BISr), reg_store)
770       .addReg(Alpha::R31).addReg(MI->getOperand(3).getReg());
771     break;
772   }
773   case Alpha::LAS32:
774   case Alpha::LAS64: {
775     BuildMI(llscMBB, dl,TII->get(is32 ? Alpha::ADDLr : Alpha::ADDQr), reg_store)
776       .addReg(reg_res).addReg(reg_v2);
777     break;
778   }
779   case Alpha::SWAP32:
780   case Alpha::SWAP64: {
781     BuildMI(llscMBB, dl, TII->get(Alpha::BISr), reg_store)
782       .addReg(reg_v2).addReg(reg_v2);
783     break;
784   }
785   }
786   BuildMI(llscMBB, dl, TII->get(is32 ? Alpha::STL_C : Alpha::STQ_C), reg_store)
787     .addReg(reg_store).addImm(0).addReg(reg_ptr);
788   BuildMI(llscMBB, dl, TII->get(Alpha::BEQ))
789     .addImm(0).addReg(reg_store).addMBB(llscMBB);
790   BuildMI(llscMBB, dl, TII->get(Alpha::BR)).addMBB(sinkMBB);
791
792   thisMBB->addSuccessor(llscMBB);
793   llscMBB->addSuccessor(llscMBB);
794   llscMBB->addSuccessor(sinkMBB);
795   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
796
797   return sinkMBB;
798 }
799
800 bool
801 AlphaTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
802   // The Alpha target isn't yet aware of offsets.
803   return false;
804 }