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