Compute feature bits at time of MCSubtargetInfo initialization.
[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 "AlphaMachineFunctionInfo.h"
17 #include "llvm/CodeGen/CallingConvLower.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
26 #include "llvm/Constants.h"
27 #include "llvm/Function.h"
28 #include "llvm/Module.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/Type.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 using namespace llvm;
35
36 /// AddLiveIn - This helper function adds the specified physical register to the
37 /// MachineFunction as a live in value.  It also creates a corresponding virtual
38 /// register for it.
39 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
40                           TargetRegisterClass *RC) {
41   assert(RC->contains(PReg) && "Not the correct regclass!");
42   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
43   MF.getRegInfo().addLiveIn(PReg, VReg);
44   return VReg;
45 }
46
47 AlphaTargetLowering::AlphaTargetLowering(TargetMachine &TM)
48   : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
49   // Set up the TargetLowering object.
50   //I am having problems with shr n i8 1
51   setBooleanContents(ZeroOrOneBooleanContent);
52
53   addRegisterClass(MVT::i64, Alpha::GPRCRegisterClass);
54   addRegisterClass(MVT::f64, Alpha::F8RCRegisterClass);
55   addRegisterClass(MVT::f32, Alpha::F4RCRegisterClass);
56
57   // We want to custom lower some of our intrinsics.
58   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
59
60   setLoadExtAction(ISD::EXTLOAD, MVT::i1,  Promote);
61   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
62
63   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
64   setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
65
66   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
67   setLoadExtAction(ISD::SEXTLOAD, MVT::i8,  Expand);
68   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
69
70   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
71
72   //  setOperationAction(ISD::BRIND,        MVT::Other,   Expand);
73   setOperationAction(ISD::BR_JT,        MVT::Other, Expand);
74   setOperationAction(ISD::BR_CC,        MVT::Other, Expand);
75   setOperationAction(ISD::SELECT_CC,    MVT::Other, Expand);
76
77   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
78
79   setOperationAction(ISD::FREM, MVT::f32, Expand);
80   setOperationAction(ISD::FREM, MVT::f64, Expand);
81
82   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
83   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
84   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
85   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
86
87   if (!TM.getSubtarget<AlphaSubtarget>().hasCT()) {
88     setOperationAction(ISD::CTPOP    , MVT::i64  , Expand);
89     setOperationAction(ISD::CTTZ     , MVT::i64  , Expand);
90     setOperationAction(ISD::CTLZ     , MVT::i64  , Expand);
91   }
92   setOperationAction(ISD::BSWAP    , MVT::i64, Expand);
93   setOperationAction(ISD::ROTL     , MVT::i64, Expand);
94   setOperationAction(ISD::ROTR     , MVT::i64, Expand);
95
96   setOperationAction(ISD::SREM     , MVT::i64, Custom);
97   setOperationAction(ISD::UREM     , MVT::i64, Custom);
98   setOperationAction(ISD::SDIV     , MVT::i64, Custom);
99   setOperationAction(ISD::UDIV     , MVT::i64, Custom);
100
101   setOperationAction(ISD::ADDC     , MVT::i64, Expand);
102   setOperationAction(ISD::ADDE     , MVT::i64, Expand);
103   setOperationAction(ISD::SUBC     , MVT::i64, Expand);
104   setOperationAction(ISD::SUBE     , MVT::i64, Expand);
105
106   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
107   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
108
109   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
110   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
111   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
112
113   // We don't support sin/cos/sqrt/pow
114   setOperationAction(ISD::FSIN , MVT::f64, Expand);
115   setOperationAction(ISD::FCOS , MVT::f64, Expand);
116   setOperationAction(ISD::FSIN , MVT::f32, Expand);
117   setOperationAction(ISD::FCOS , MVT::f32, Expand);
118
119   setOperationAction(ISD::FSQRT, MVT::f64, Expand);
120   setOperationAction(ISD::FSQRT, MVT::f32, Expand);
121
122   setOperationAction(ISD::FPOW , MVT::f32, Expand);
123   setOperationAction(ISD::FPOW , MVT::f64, Expand);
124
125   setOperationAction(ISD::SETCC, MVT::f32, Promote);
126
127   setOperationAction(ISD::BITCAST, MVT::f32, Promote);
128
129   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
130
131   // Not implemented yet.
132   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
133   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
134   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
135
136   // We want to legalize GlobalAddress and ConstantPool and
137   // ExternalSymbols nodes into the appropriate instructions to
138   // materialize the address.
139   setOperationAction(ISD::GlobalAddress,  MVT::i64, Custom);
140   setOperationAction(ISD::ConstantPool,   MVT::i64, Custom);
141   setOperationAction(ISD::ExternalSymbol, MVT::i64, Custom);
142   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
143
144   setOperationAction(ISD::VASTART, MVT::Other, Custom);
145   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
146   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
147   setOperationAction(ISD::VAARG,   MVT::Other, Custom);
148   setOperationAction(ISD::VAARG,   MVT::i32,   Custom);
149
150   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
151   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
152
153   setStackPointerRegisterToSaveRestore(Alpha::R30);
154
155   setJumpBufSize(272);
156   setJumpBufAlignment(16);
157
158   setMinFunctionAlignment(4);
159
160   computeRegisterProperties();
161 }
162
163 MVT::SimpleValueType AlphaTargetLowering::getSetCCResultType(EVT VT) const {
164   return MVT::i64;
165 }
166
167 const char *AlphaTargetLowering::getTargetNodeName(unsigned Opcode) const {
168   switch (Opcode) {
169   default: return 0;
170   case AlphaISD::CVTQT_: return "Alpha::CVTQT_";
171   case AlphaISD::CVTQS_: return "Alpha::CVTQS_";
172   case AlphaISD::CVTTQ_: return "Alpha::CVTTQ_";
173   case AlphaISD::GPRelHi: return "Alpha::GPRelHi";
174   case AlphaISD::GPRelLo: return "Alpha::GPRelLo";
175   case AlphaISD::RelLit: return "Alpha::RelLit";
176   case AlphaISD::GlobalRetAddr: return "Alpha::GlobalRetAddr";
177   case AlphaISD::CALL:   return "Alpha::CALL";
178   case AlphaISD::DivCall: return "Alpha::DivCall";
179   case AlphaISD::RET_FLAG: return "Alpha::RET_FLAG";
180   case AlphaISD::COND_BRANCH_I: return "Alpha::COND_BRANCH_I";
181   case AlphaISD::COND_BRANCH_F: return "Alpha::COND_BRANCH_F";
182   }
183 }
184
185 static SDValue LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
186   EVT PtrVT = Op.getValueType();
187   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
188   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
189   // FIXME there isn't really any debug info here
190   DebugLoc dl = Op.getDebugLoc();
191
192   SDValue Hi = DAG.getNode(AlphaISD::GPRelHi,  dl, MVT::i64, JTI,
193                              DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
194   SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, JTI, Hi);
195   return Lo;
196 }
197
198 //http://www.cs.arizona.edu/computer.help/policy/DIGITAL_unix/
199 //AA-PY8AC-TET1_html/callCH3.html#BLOCK21
200
201 //For now, just use variable size stack frame format
202
203 //In a standard call, the first six items are passed in registers $16
204 //- $21 and/or registers $f16 - $f21. (See Section 4.1.2 for details
205 //of argument-to-register correspondence.) The remaining items are
206 //collected in a memory argument list that is a naturally aligned
207 //array of quadwords. In a standard call, this list, if present, must
208 //be passed at 0(SP).
209 //7 ... n         0(SP) ... (n-7)*8(SP)
210
211 // //#define FP    $15
212 // //#define RA    $26
213 // //#define PV    $27
214 // //#define GP    $29
215 // //#define SP    $30
216
217 #include "AlphaGenCallingConv.inc"
218
219 SDValue
220 AlphaTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
221                                CallingConv::ID CallConv, bool isVarArg,
222                                bool &isTailCall,
223                                const SmallVectorImpl<ISD::OutputArg> &Outs,
224                                const SmallVectorImpl<SDValue> &OutVals,
225                                const SmallVectorImpl<ISD::InputArg> &Ins,
226                                DebugLoc dl, SelectionDAG &DAG,
227                                SmallVectorImpl<SDValue> &InVals) const {
228   // Alpha target does not yet support tail call optimization.
229   isTailCall = false;
230
231   // Analyze operands of the call, assigning locations to each operand.
232   SmallVector<CCValAssign, 16> ArgLocs;
233   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
234                  getTargetMachine(), ArgLocs, *DAG.getContext());
235
236   CCInfo.AnalyzeCallOperands(Outs, CC_Alpha);
237
238     // Get a count of how many bytes are to be pushed on the stack.
239   unsigned NumBytes = CCInfo.getNextStackOffset();
240
241   Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes,
242                                                       getPointerTy(), true));
243
244   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
245   SmallVector<SDValue, 12> MemOpChains;
246   SDValue StackPtr;
247
248   // Walk the register/memloc assignments, inserting copies/loads.
249   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
250     CCValAssign &VA = ArgLocs[i];
251
252     SDValue Arg = OutVals[i];
253
254     // Promote the value if needed.
255     switch (VA.getLocInfo()) {
256       default: assert(0 && "Unknown loc info!");
257       case CCValAssign::Full: break;
258       case CCValAssign::SExt:
259         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
260         break;
261       case CCValAssign::ZExt:
262         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
263         break;
264       case CCValAssign::AExt:
265         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
266         break;
267     }
268
269     // Arguments that can be passed on register must be kept at RegsToPass
270     // vector
271     if (VA.isRegLoc()) {
272       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
273     } else {
274       assert(VA.isMemLoc());
275
276       if (StackPtr.getNode() == 0)
277         StackPtr = DAG.getCopyFromReg(Chain, dl, Alpha::R30, MVT::i64);
278
279       SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
280                                    StackPtr,
281                                    DAG.getIntPtrConstant(VA.getLocMemOffset()));
282
283       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
284                                          MachinePointerInfo(),false, false, 0));
285     }
286   }
287
288   // Transform all store nodes into one single node because all store nodes are
289   // independent of each other.
290   if (!MemOpChains.empty())
291     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
292                         &MemOpChains[0], MemOpChains.size());
293
294   // Build a sequence of copy-to-reg nodes chained together with token chain and
295   // flag operands which copy the outgoing args into registers.  The InFlag in
296   // necessary since all emitted instructions must be stuck together.
297   SDValue InFlag;
298   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
299     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
300                              RegsToPass[i].second, InFlag);
301     InFlag = Chain.getValue(1);
302   }
303
304   // Returns a chain & a flag for retval copy to use.
305   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
306   SmallVector<SDValue, 8> Ops;
307   Ops.push_back(Chain);
308   Ops.push_back(Callee);
309
310   // Add argument registers to the end of the list so that they are
311   // known live into the call.
312   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
313     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
314                                   RegsToPass[i].second.getValueType()));
315
316   if (InFlag.getNode())
317     Ops.push_back(InFlag);
318
319   Chain = DAG.getNode(AlphaISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
320   InFlag = Chain.getValue(1);
321
322   // Create the CALLSEQ_END node.
323   Chain = DAG.getCALLSEQ_END(Chain,
324                              DAG.getConstant(NumBytes, getPointerTy(), true),
325                              DAG.getConstant(0, getPointerTy(), true),
326                              InFlag);
327   InFlag = Chain.getValue(1);
328
329   // Handle result values, copying them out of physregs into vregs that we
330   // return.
331   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
332                          Ins, dl, DAG, InVals);
333 }
334
335 /// LowerCallResult - Lower the result values of a call into the
336 /// appropriate copies out of appropriate physical registers.
337 ///
338 SDValue
339 AlphaTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
340                                      CallingConv::ID CallConv, bool isVarArg,
341                                      const SmallVectorImpl<ISD::InputArg> &Ins,
342                                      DebugLoc dl, SelectionDAG &DAG,
343                                      SmallVectorImpl<SDValue> &InVals) const {
344
345   // Assign locations to each value returned by this call.
346   SmallVector<CCValAssign, 16> RVLocs;
347   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
348                  getTargetMachine(), RVLocs, *DAG.getContext());
349
350   CCInfo.AnalyzeCallResult(Ins, RetCC_Alpha);
351
352   // Copy all of the result registers out of their specified physreg.
353   for (unsigned i = 0; i != RVLocs.size(); ++i) {
354     CCValAssign &VA = RVLocs[i];
355
356     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
357                                VA.getLocVT(), InFlag).getValue(1);
358     SDValue RetValue = Chain.getValue(0);
359     InFlag = Chain.getValue(2);
360
361     // If this is an 8/16/32-bit value, it is really passed promoted to 64
362     // bits. Insert an assert[sz]ext to capture this, then truncate to the
363     // right size.
364     if (VA.getLocInfo() == CCValAssign::SExt)
365       RetValue = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), RetValue,
366                              DAG.getValueType(VA.getValVT()));
367     else if (VA.getLocInfo() == CCValAssign::ZExt)
368       RetValue = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), RetValue,
369                              DAG.getValueType(VA.getValVT()));
370
371     if (VA.getLocInfo() != CCValAssign::Full)
372       RetValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), RetValue);
373
374     InVals.push_back(RetValue);
375   }
376
377   return Chain;
378 }
379
380 SDValue
381 AlphaTargetLowering::LowerFormalArguments(SDValue Chain,
382                                           CallingConv::ID CallConv, bool isVarArg,
383                                           const SmallVectorImpl<ISD::InputArg>
384                                             &Ins,
385                                           DebugLoc dl, SelectionDAG &DAG,
386                                           SmallVectorImpl<SDValue> &InVals)
387                                             const {
388
389   MachineFunction &MF = DAG.getMachineFunction();
390   MachineFrameInfo *MFI = MF.getFrameInfo();
391   AlphaMachineFunctionInfo *FuncInfo = MF.getInfo<AlphaMachineFunctionInfo>();
392
393   unsigned args_int[] = {
394     Alpha::R16, Alpha::R17, Alpha::R18, Alpha::R19, Alpha::R20, Alpha::R21};
395   unsigned args_float[] = {
396     Alpha::F16, Alpha::F17, Alpha::F18, Alpha::F19, Alpha::F20, Alpha::F21};
397
398   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
399     SDValue argt;
400     EVT ObjectVT = Ins[ArgNo].VT;
401     SDValue ArgVal;
402
403     if (ArgNo  < 6) {
404       switch (ObjectVT.getSimpleVT().SimpleTy) {
405       default:
406         assert(false && "Invalid value type!");
407       case MVT::f64:
408         args_float[ArgNo] = AddLiveIn(MF, args_float[ArgNo],
409                                       &Alpha::F8RCRegClass);
410         ArgVal = DAG.getCopyFromReg(Chain, dl, args_float[ArgNo], ObjectVT);
411         break;
412       case MVT::f32:
413         args_float[ArgNo] = AddLiveIn(MF, args_float[ArgNo],
414                                       &Alpha::F4RCRegClass);
415         ArgVal = DAG.getCopyFromReg(Chain, dl, args_float[ArgNo], ObjectVT);
416         break;
417       case MVT::i64:
418         args_int[ArgNo] = AddLiveIn(MF, args_int[ArgNo],
419                                     &Alpha::GPRCRegClass);
420         ArgVal = DAG.getCopyFromReg(Chain, dl, args_int[ArgNo], MVT::i64);
421         break;
422       }
423     } else { //more args
424       // Create the frame index object for this incoming parameter...
425       int FI = MFI->CreateFixedObject(8, 8 * (ArgNo - 6), true);
426
427       // Create the SelectionDAG nodes corresponding to a load
428       //from this parameter
429       SDValue FIN = DAG.getFrameIndex(FI, MVT::i64);
430       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
431                            false, false, 0);
432     }
433     InVals.push_back(ArgVal);
434   }
435
436   // If the functions takes variable number of arguments, copy all regs to stack
437   if (isVarArg) {
438     FuncInfo->setVarArgsOffset(Ins.size() * 8);
439     std::vector<SDValue> LS;
440     for (int i = 0; i < 6; ++i) {
441       if (TargetRegisterInfo::isPhysicalRegister(args_int[i]))
442         args_int[i] = AddLiveIn(MF, args_int[i], &Alpha::GPRCRegClass);
443       SDValue argt = DAG.getCopyFromReg(Chain, dl, args_int[i], MVT::i64);
444       int FI = MFI->CreateFixedObject(8, -8 * (6 - i), true);
445       if (i == 0) FuncInfo->setVarArgsBase(FI);
446       SDValue SDFI = DAG.getFrameIndex(FI, MVT::i64);
447       LS.push_back(DAG.getStore(Chain, dl, argt, SDFI, MachinePointerInfo(),
448                                 false, false, 0));
449
450       if (TargetRegisterInfo::isPhysicalRegister(args_float[i]))
451         args_float[i] = AddLiveIn(MF, args_float[i], &Alpha::F8RCRegClass);
452       argt = DAG.getCopyFromReg(Chain, dl, args_float[i], MVT::f64);
453       FI = MFI->CreateFixedObject(8, - 8 * (12 - i), true);
454       SDFI = DAG.getFrameIndex(FI, MVT::i64);
455       LS.push_back(DAG.getStore(Chain, dl, argt, SDFI, MachinePointerInfo(),
456                                 false, false, 0));
457     }
458
459     //Set up a token factor with all the stack traffic
460     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &LS[0], LS.size());
461   }
462
463   return Chain;
464 }
465
466 SDValue
467 AlphaTargetLowering::LowerReturn(SDValue Chain,
468                                  CallingConv::ID CallConv, bool isVarArg,
469                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
470                                  const SmallVectorImpl<SDValue> &OutVals,
471                                  DebugLoc dl, SelectionDAG &DAG) const {
472
473   SDValue Copy = DAG.getCopyToReg(Chain, dl, Alpha::R26,
474                                   DAG.getNode(AlphaISD::GlobalRetAddr,
475                                               DebugLoc(), MVT::i64),
476                                   SDValue());
477   switch (Outs.size()) {
478   default:
479     llvm_unreachable("Do not know how to return this many arguments!");
480   case 0:
481     break;
482     //return SDValue(); // ret void is legal
483   case 1: {
484     EVT ArgVT = Outs[0].VT;
485     unsigned ArgReg;
486     if (ArgVT.isInteger())
487       ArgReg = Alpha::R0;
488     else {
489       assert(ArgVT.isFloatingPoint());
490       ArgReg = Alpha::F0;
491     }
492     Copy = DAG.getCopyToReg(Copy, dl, ArgReg,
493                             OutVals[0], Copy.getValue(1));
494     if (DAG.getMachineFunction().getRegInfo().liveout_empty())
495       DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg);
496     break;
497   }
498   case 2: {
499     EVT ArgVT = Outs[0].VT;
500     unsigned ArgReg1, ArgReg2;
501     if (ArgVT.isInteger()) {
502       ArgReg1 = Alpha::R0;
503       ArgReg2 = Alpha::R1;
504     } else {
505       assert(ArgVT.isFloatingPoint());
506       ArgReg1 = Alpha::F0;
507       ArgReg2 = Alpha::F1;
508     }
509     Copy = DAG.getCopyToReg(Copy, dl, ArgReg1,
510                             OutVals[0], Copy.getValue(1));
511     if (std::find(DAG.getMachineFunction().getRegInfo().liveout_begin(),
512                   DAG.getMachineFunction().getRegInfo().liveout_end(), ArgReg1)
513         == DAG.getMachineFunction().getRegInfo().liveout_end())
514       DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg1);
515     Copy = DAG.getCopyToReg(Copy, dl, ArgReg2,
516                             OutVals[1], Copy.getValue(1));
517     if (std::find(DAG.getMachineFunction().getRegInfo().liveout_begin(),
518                    DAG.getMachineFunction().getRegInfo().liveout_end(), ArgReg2)
519         == DAG.getMachineFunction().getRegInfo().liveout_end())
520       DAG.getMachineFunction().getRegInfo().addLiveOut(ArgReg2);
521     break;
522   }
523   }
524   return DAG.getNode(AlphaISD::RET_FLAG, dl,
525                      MVT::Other, Copy, Copy.getValue(1));
526 }
527
528 void AlphaTargetLowering::LowerVAARG(SDNode *N, SDValue &Chain,
529                                      SDValue &DataPtr,
530                                      SelectionDAG &DAG) const {
531   Chain = N->getOperand(0);
532   SDValue VAListP = N->getOperand(1);
533   const Value *VAListS = cast<SrcValueSDNode>(N->getOperand(2))->getValue();
534   DebugLoc dl = N->getDebugLoc();
535
536   SDValue Base = DAG.getLoad(MVT::i64, dl, Chain, VAListP,
537                              MachinePointerInfo(VAListS),
538                              false, false, 0);
539   SDValue Tmp = DAG.getNode(ISD::ADD, dl, MVT::i64, VAListP,
540                               DAG.getConstant(8, MVT::i64));
541   SDValue Offset = DAG.getExtLoad(ISD::SEXTLOAD, dl, MVT::i64, Base.getValue(1),
542                                   Tmp, MachinePointerInfo(),
543                                   MVT::i32, false, false, 0);
544   DataPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Base, Offset);
545   if (N->getValueType(0).isFloatingPoint())
546   {
547     //if fp && Offset < 6*8, then subtract 6*8 from DataPtr
548     SDValue FPDataPtr = DAG.getNode(ISD::SUB, dl, MVT::i64, DataPtr,
549                                       DAG.getConstant(8*6, MVT::i64));
550     SDValue CC = DAG.getSetCC(dl, MVT::i64, Offset,
551                                 DAG.getConstant(8*6, MVT::i64), ISD::SETLT);
552     DataPtr = DAG.getNode(ISD::SELECT, dl, MVT::i64, CC, FPDataPtr, DataPtr);
553   }
554
555   SDValue NewOffset = DAG.getNode(ISD::ADD, dl, MVT::i64, Offset,
556                                     DAG.getConstant(8, MVT::i64));
557   Chain = DAG.getTruncStore(Offset.getValue(1), dl, NewOffset, Tmp,
558                             MachinePointerInfo(),
559                             MVT::i32, false, false, 0);
560 }
561
562 /// LowerOperation - Provide custom lowering hooks for some operations.
563 ///
564 SDValue AlphaTargetLowering::LowerOperation(SDValue Op,
565                                             SelectionDAG &DAG) const {
566   DebugLoc dl = Op.getDebugLoc();
567   switch (Op.getOpcode()) {
568   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
569   case ISD::JumpTable: return LowerJumpTable(Op, DAG);
570
571   case ISD::INTRINSIC_WO_CHAIN: {
572     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
573     switch (IntNo) {
574     default: break;    // Don't custom lower most intrinsics.
575     case Intrinsic::alpha_umulh:
576       return DAG.getNode(ISD::MULHU, dl, MVT::i64,
577                          Op.getOperand(1), Op.getOperand(2));
578     }
579   }
580
581   case ISD::SRL_PARTS: {
582     SDValue ShOpLo = Op.getOperand(0);
583     SDValue ShOpHi = Op.getOperand(1);
584     SDValue ShAmt  = Op.getOperand(2);
585     SDValue bm = DAG.getNode(ISD::SUB, dl, MVT::i64,
586                              DAG.getConstant(64, MVT::i64), ShAmt);
587     SDValue BMCC = DAG.getSetCC(dl, MVT::i64, bm,
588                                 DAG.getConstant(0, MVT::i64), ISD::SETLE);
589     // if 64 - shAmt <= 0
590     SDValue Hi_Neg = DAG.getConstant(0, MVT::i64);
591     SDValue ShAmt_Neg = DAG.getNode(ISD::SUB, dl, MVT::i64,
592                                     DAG.getConstant(0, MVT::i64), bm);
593     SDValue Lo_Neg = DAG.getNode(ISD::SRL, dl, MVT::i64, ShOpHi, ShAmt_Neg);
594     // else
595     SDValue carries = DAG.getNode(ISD::SHL, dl, MVT::i64, ShOpHi, bm);
596     SDValue Hi_Pos =  DAG.getNode(ISD::SRL, dl, MVT::i64, ShOpHi, ShAmt);
597     SDValue Lo_Pos = DAG.getNode(ISD::SRL, dl, MVT::i64, ShOpLo, ShAmt);
598     Lo_Pos = DAG.getNode(ISD::OR, dl, MVT::i64, Lo_Pos, carries);
599     // Merge
600     SDValue Hi = DAG.getNode(ISD::SELECT, dl, MVT::i64, BMCC, Hi_Neg, Hi_Pos);
601     SDValue Lo = DAG.getNode(ISD::SELECT, dl, MVT::i64, BMCC, Lo_Neg, Lo_Pos);
602     SDValue Ops[2] = { Lo, Hi };
603     return DAG.getMergeValues(Ops, 2, dl);
604   }
605     //  case ISD::SRA_PARTS:
606
607     //  case ISD::SHL_PARTS:
608
609
610   case ISD::SINT_TO_FP: {
611     assert(Op.getOperand(0).getValueType() == MVT::i64 &&
612            "Unhandled SINT_TO_FP type in custom expander!");
613     SDValue LD;
614     bool isDouble = Op.getValueType() == MVT::f64;
615     LD = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op.getOperand(0));
616     SDValue FP = DAG.getNode(isDouble?AlphaISD::CVTQT_:AlphaISD::CVTQS_, dl,
617                                isDouble?MVT::f64:MVT::f32, LD);
618     return FP;
619   }
620   case ISD::FP_TO_SINT: {
621     bool isDouble = Op.getOperand(0).getValueType() == MVT::f64;
622     SDValue src = Op.getOperand(0);
623
624     if (!isDouble) //Promote
625       src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, src);
626
627     src = DAG.getNode(AlphaISD::CVTTQ_, dl, MVT::f64, src);
628
629     return DAG.getNode(ISD::BITCAST, dl, MVT::i64, src);
630   }
631   case ISD::ConstantPool: {
632     ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
633     const Constant *C = CP->getConstVal();
634     SDValue CPI = DAG.getTargetConstantPool(C, MVT::i64, CP->getAlignment());
635     // FIXME there isn't really any debug info here
636
637     SDValue Hi = DAG.getNode(AlphaISD::GPRelHi,  dl, MVT::i64, CPI,
638                                DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
639     SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, CPI, Hi);
640     return Lo;
641   }
642   case ISD::GlobalTLSAddress:
643     llvm_unreachable("TLS not implemented for Alpha.");
644   case ISD::GlobalAddress: {
645     GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
646     const GlobalValue *GV = GSDN->getGlobal();
647     SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i64,
648                                             GSDN->getOffset());
649     // FIXME there isn't really any debug info here
650
651     //    if (!GV->hasWeakLinkage() && !GV->isDeclaration()
652     //        && !GV->hasLinkOnceLinkage()) {
653     if (GV->hasLocalLinkage()) {
654       SDValue Hi = DAG.getNode(AlphaISD::GPRelHi,  dl, MVT::i64, GA,
655                                 DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
656       SDValue Lo = DAG.getNode(AlphaISD::GPRelLo, dl, MVT::i64, GA, Hi);
657       return Lo;
658     } else
659       return DAG.getNode(AlphaISD::RelLit, dl, MVT::i64, GA,
660                          DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
661   }
662   case ISD::ExternalSymbol: {
663     return DAG.getNode(AlphaISD::RelLit, dl, MVT::i64,
664                        DAG.getTargetExternalSymbol(cast<ExternalSymbolSDNode>(Op)
665                                                    ->getSymbol(), MVT::i64),
666                        DAG.getGLOBAL_OFFSET_TABLE(MVT::i64));
667   }
668
669   case ISD::UREM:
670   case ISD::SREM:
671     //Expand only on constant case
672     if (Op.getOperand(1).getOpcode() == ISD::Constant) {
673       EVT VT = Op.getNode()->getValueType(0);
674       SDValue Tmp1 = Op.getNode()->getOpcode() == ISD::UREM ?
675         BuildUDIV(Op.getNode(), DAG, NULL) :
676         BuildSDIV(Op.getNode(), DAG, NULL);
677       Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Op.getOperand(1));
678       Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Op.getOperand(0), Tmp1);
679       return Tmp1;
680     }
681     //fall through
682   case ISD::SDIV:
683   case ISD::UDIV:
684     if (Op.getValueType().isInteger()) {
685       if (Op.getOperand(1).getOpcode() == ISD::Constant)
686         return Op.getOpcode() == ISD::SDIV ? BuildSDIV(Op.getNode(), DAG, NULL)
687           : BuildUDIV(Op.getNode(), DAG, NULL);
688       const char* opstr = 0;
689       switch (Op.getOpcode()) {
690       case ISD::UREM: opstr = "__remqu"; break;
691       case ISD::SREM: opstr = "__remq";  break;
692       case ISD::UDIV: opstr = "__divqu"; break;
693       case ISD::SDIV: opstr = "__divq";  break;
694       }
695       SDValue Tmp1 = Op.getOperand(0),
696         Tmp2 = Op.getOperand(1),
697         Addr = DAG.getExternalSymbol(opstr, MVT::i64);
698       return DAG.getNode(AlphaISD::DivCall, dl, MVT::i64, Addr, Tmp1, Tmp2);
699     }
700     break;
701
702   case ISD::VAARG: {
703     SDValue Chain, DataPtr;
704     LowerVAARG(Op.getNode(), Chain, DataPtr, DAG);
705
706     SDValue Result;
707     if (Op.getValueType() == MVT::i32)
708       Result = DAG.getExtLoad(ISD::SEXTLOAD, dl, MVT::i64, Chain, DataPtr,
709                               MachinePointerInfo(), MVT::i32, false, false, 0);
710     else
711       Result = DAG.getLoad(Op.getValueType(), dl, Chain, DataPtr,
712                            MachinePointerInfo(),
713                            false, false, 0);
714     return Result;
715   }
716   case ISD::VACOPY: {
717     SDValue Chain = Op.getOperand(0);
718     SDValue DestP = Op.getOperand(1);
719     SDValue SrcP = Op.getOperand(2);
720     const Value *DestS = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
721     const Value *SrcS = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
722
723     SDValue Val = DAG.getLoad(getPointerTy(), dl, Chain, SrcP,
724                               MachinePointerInfo(SrcS),
725                               false, false, 0);
726     SDValue Result = DAG.getStore(Val.getValue(1), dl, Val, DestP,
727                                   MachinePointerInfo(DestS),
728                                   false, false, 0);
729     SDValue NP = DAG.getNode(ISD::ADD, dl, MVT::i64, SrcP,
730                                DAG.getConstant(8, MVT::i64));
731     Val = DAG.getExtLoad(ISD::SEXTLOAD, dl, MVT::i64, Result,
732                          NP, MachinePointerInfo(), MVT::i32, false, false, 0);
733     SDValue NPD = DAG.getNode(ISD::ADD, dl, MVT::i64, DestP,
734                                 DAG.getConstant(8, MVT::i64));
735     return DAG.getTruncStore(Val.getValue(1), dl, Val, NPD,
736                              MachinePointerInfo(), MVT::i32,
737                              false, false, 0);
738   }
739   case ISD::VASTART: {
740     MachineFunction &MF = DAG.getMachineFunction();
741     AlphaMachineFunctionInfo *FuncInfo = MF.getInfo<AlphaMachineFunctionInfo>();
742
743     SDValue Chain = Op.getOperand(0);
744     SDValue VAListP = Op.getOperand(1);
745     const Value *VAListS = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
746
747     // vastart stores the address of the VarArgsBase and VarArgsOffset
748     SDValue FR  = DAG.getFrameIndex(FuncInfo->getVarArgsBase(), MVT::i64);
749     SDValue S1  = DAG.getStore(Chain, dl, FR, VAListP,
750                                MachinePointerInfo(VAListS), false, false, 0);
751     SDValue SA2 = DAG.getNode(ISD::ADD, dl, MVT::i64, VAListP,
752                                 DAG.getConstant(8, MVT::i64));
753     return DAG.getTruncStore(S1, dl,
754                              DAG.getConstant(FuncInfo->getVarArgsOffset(),
755                                              MVT::i64),
756                              SA2, MachinePointerInfo(),
757                              MVT::i32, false, false, 0);
758   }
759   case ISD::RETURNADDR:
760     return DAG.getNode(AlphaISD::GlobalRetAddr, DebugLoc(), MVT::i64);
761       //FIXME: implement
762   case ISD::FRAMEADDR:          break;
763   }
764
765   return SDValue();
766 }
767
768 void AlphaTargetLowering::ReplaceNodeResults(SDNode *N,
769                                              SmallVectorImpl<SDValue>&Results,
770                                              SelectionDAG &DAG) const {
771   DebugLoc dl = N->getDebugLoc();
772   assert(N->getValueType(0) == MVT::i32 &&
773          N->getOpcode() == ISD::VAARG &&
774          "Unknown node to custom promote!");
775
776   SDValue Chain, DataPtr;
777   LowerVAARG(N, Chain, DataPtr, DAG);
778   SDValue Res = DAG.getLoad(N->getValueType(0), dl, Chain, DataPtr,
779                             MachinePointerInfo(),
780                             false, false, 0);
781   Results.push_back(Res);
782   Results.push_back(SDValue(Res.getNode(), 1));
783 }
784
785
786 //Inline Asm
787
788 /// getConstraintType - Given a constraint letter, return the type of
789 /// constraint it is for this target.
790 AlphaTargetLowering::ConstraintType
791 AlphaTargetLowering::getConstraintType(const std::string &Constraint) const {
792   if (Constraint.size() == 1) {
793     switch (Constraint[0]) {
794     default: break;
795     case 'f':
796     case 'r':
797       return C_RegisterClass;
798     }
799   }
800   return TargetLowering::getConstraintType(Constraint);
801 }
802
803 /// Examine constraint type and operand type and determine a weight value.
804 /// This object must already have been set up with the operand type
805 /// and the current alternative constraint selected.
806 TargetLowering::ConstraintWeight
807 AlphaTargetLowering::getSingleConstraintMatchWeight(
808     AsmOperandInfo &info, const char *constraint) const {
809   ConstraintWeight weight = CW_Invalid;
810   Value *CallOperandVal = info.CallOperandVal;
811     // If we don't have a value, we can't do a match,
812     // but allow it at the lowest weight.
813   if (CallOperandVal == NULL)
814     return CW_Default;
815   // Look at the constraint type.
816   switch (*constraint) {
817   default:
818     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
819     break;
820   case 'f':
821     weight = CW_Register;
822     break;
823   }
824   return weight;
825 }
826
827 /// Given a register class constraint, like 'r', if this corresponds directly
828 /// to an LLVM register class, return a register of 0 and the register class
829 /// pointer.
830 std::pair<unsigned, const TargetRegisterClass*> AlphaTargetLowering::
831 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
832 {
833   if (Constraint.size() == 1) {
834     switch (Constraint[0]) {
835     case 'r':
836       return std::make_pair(0U, Alpha::GPRCRegisterClass);
837     case 'f':
838       return VT == MVT::f64 ? std::make_pair(0U, Alpha::F8RCRegisterClass) :
839         std::make_pair(0U, Alpha::F4RCRegisterClass);
840     }
841   }
842   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
843 }
844
845 //===----------------------------------------------------------------------===//
846 //  Other Lowering Code
847 //===----------------------------------------------------------------------===//
848
849 MachineBasicBlock *
850 AlphaTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
851                                                  MachineBasicBlock *BB) const {
852   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
853   assert((MI->getOpcode() == Alpha::CAS32 ||
854           MI->getOpcode() == Alpha::CAS64 ||
855           MI->getOpcode() == Alpha::LAS32 ||
856           MI->getOpcode() == Alpha::LAS64 ||
857           MI->getOpcode() == Alpha::SWAP32 ||
858           MI->getOpcode() == Alpha::SWAP64) &&
859          "Unexpected instr type to insert");
860
861   bool is32 = MI->getOpcode() == Alpha::CAS32 ||
862     MI->getOpcode() == Alpha::LAS32 ||
863     MI->getOpcode() == Alpha::SWAP32;
864
865   //Load locked store conditional for atomic ops take on the same form
866   //start:
867   //ll
868   //do stuff (maybe branch to exit)
869   //sc
870   //test sc and maybe branck to start
871   //exit:
872   const BasicBlock *LLVM_BB = BB->getBasicBlock();
873   DebugLoc dl = MI->getDebugLoc();
874   MachineFunction::iterator It = BB;
875   ++It;
876
877   MachineBasicBlock *thisMBB = BB;
878   MachineFunction *F = BB->getParent();
879   MachineBasicBlock *llscMBB = F->CreateMachineBasicBlock(LLVM_BB);
880   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
881
882   sinkMBB->splice(sinkMBB->begin(), thisMBB,
883                   llvm::next(MachineBasicBlock::iterator(MI)),
884                   thisMBB->end());
885   sinkMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
886
887   F->insert(It, llscMBB);
888   F->insert(It, sinkMBB);
889
890   BuildMI(thisMBB, dl, TII->get(Alpha::BR)).addMBB(llscMBB);
891
892   unsigned reg_res = MI->getOperand(0).getReg(),
893     reg_ptr = MI->getOperand(1).getReg(),
894     reg_v2 = MI->getOperand(2).getReg(),
895     reg_store = F->getRegInfo().createVirtualRegister(&Alpha::GPRCRegClass);
896
897   BuildMI(llscMBB, dl, TII->get(is32 ? Alpha::LDL_L : Alpha::LDQ_L),
898           reg_res).addImm(0).addReg(reg_ptr);
899   switch (MI->getOpcode()) {
900   case Alpha::CAS32:
901   case Alpha::CAS64: {
902     unsigned reg_cmp
903       = F->getRegInfo().createVirtualRegister(&Alpha::GPRCRegClass);
904     BuildMI(llscMBB, dl, TII->get(Alpha::CMPEQ), reg_cmp)
905       .addReg(reg_v2).addReg(reg_res);
906     BuildMI(llscMBB, dl, TII->get(Alpha::BEQ))
907       .addImm(0).addReg(reg_cmp).addMBB(sinkMBB);
908     BuildMI(llscMBB, dl, TII->get(Alpha::BISr), reg_store)
909       .addReg(Alpha::R31).addReg(MI->getOperand(3).getReg());
910     break;
911   }
912   case Alpha::LAS32:
913   case Alpha::LAS64: {
914     BuildMI(llscMBB, dl,TII->get(is32 ? Alpha::ADDLr : Alpha::ADDQr), reg_store)
915       .addReg(reg_res).addReg(reg_v2);
916     break;
917   }
918   case Alpha::SWAP32:
919   case Alpha::SWAP64: {
920     BuildMI(llscMBB, dl, TII->get(Alpha::BISr), reg_store)
921       .addReg(reg_v2).addReg(reg_v2);
922     break;
923   }
924   }
925   BuildMI(llscMBB, dl, TII->get(is32 ? Alpha::STL_C : Alpha::STQ_C), reg_store)
926     .addReg(reg_store).addImm(0).addReg(reg_ptr);
927   BuildMI(llscMBB, dl, TII->get(Alpha::BEQ))
928     .addImm(0).addReg(reg_store).addMBB(llscMBB);
929   BuildMI(llscMBB, dl, TII->get(Alpha::BR)).addMBB(sinkMBB);
930
931   thisMBB->addSuccessor(llscMBB);
932   llscMBB->addSuccessor(llscMBB);
933   llscMBB->addSuccessor(sinkMBB);
934   MI->eraseFromParent();   // The pseudo instruction is gone now.
935
936   return sinkMBB;
937 }
938
939 bool
940 AlphaTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
941   // The Alpha target isn't yet aware of offsets.
942   return false;
943 }
944
945 bool AlphaTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
946   if (VT != MVT::f32 && VT != MVT::f64)
947     return false;
948   // +0.0   F31
949   // +0.0f  F31
950   // -0.0  -F31
951   // -0.0f -F31
952   return Imm.isZero() || Imm.isNegZero();
953 }