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