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