This patch adds a new NVPTX back-end to LLVM which supports code generation for NVIDI...
[oota-llvm.git] / lib / Target / NVPTX / NVPTXISelLowering.cpp
1 //
2 //                     The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that NVPTX uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13
14
15 #include "NVPTX.h"
16 #include "NVPTXISelLowering.h"
17 #include "NVPTXTargetMachine.h"
18 #include "NVPTXTargetObjectFile.h"
19 #include "NVPTXUtilities.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalValue.h"
25 #include "llvm/Module.h"
26 #include "llvm/Function.h"
27 #include "llvm/CodeGen/Analysis.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
37 #include "llvm/MC/MCSectionELF.h"
38 #include <sstream>
39
40 #undef DEBUG_TYPE
41 #define DEBUG_TYPE "nvptx-lower"
42
43 using namespace llvm;
44
45 static unsigned int uniqueCallSite = 0;
46
47 static cl::opt<bool>
48 RetainVectorOperands("nvptx-codegen-vectors",
49      cl::desc("NVPTX Specific: Retain LLVM's vectors and generate PTX vectors"),
50                      cl::init(true));
51
52 static cl::opt<bool>
53 sched4reg("nvptx-sched4reg",
54           cl::desc("NVPTX Specific: schedule for register pressue"),
55           cl::init(false));
56
57 // NVPTXTargetLowering Constructor.
58 NVPTXTargetLowering::NVPTXTargetLowering(NVPTXTargetMachine &TM)
59 : TargetLowering(TM, new NVPTXTargetObjectFile()),
60   nvTM(&TM),
61   nvptxSubtarget(TM.getSubtarget<NVPTXSubtarget>()) {
62
63   // always lower memset, memcpy, and memmove intrinsics to load/store
64   // instructions, rather
65   // then generating calls to memset, mempcy or memmove.
66   maxStoresPerMemset = (unsigned)0xFFFFFFFF;
67   maxStoresPerMemcpy = (unsigned)0xFFFFFFFF;
68   maxStoresPerMemmove = (unsigned)0xFFFFFFFF;
69
70   setBooleanContents(ZeroOrNegativeOneBooleanContent);
71
72   // Jump is Expensive. Don't create extra control flow for 'and', 'or'
73   // condition branches.
74   setJumpIsExpensive(true);
75
76   // By default, use the Source scheduling
77   if (sched4reg)
78     setSchedulingPreference(Sched::RegPressure);
79   else
80     setSchedulingPreference(Sched::Source);
81
82   addRegisterClass(MVT::i1, &NVPTX::Int1RegsRegClass);
83   addRegisterClass(MVT::i8, &NVPTX::Int8RegsRegClass);
84   addRegisterClass(MVT::i16, &NVPTX::Int16RegsRegClass);
85   addRegisterClass(MVT::i32, &NVPTX::Int32RegsRegClass);
86   addRegisterClass(MVT::i64, &NVPTX::Int64RegsRegClass);
87   addRegisterClass(MVT::f32, &NVPTX::Float32RegsRegClass);
88   addRegisterClass(MVT::f64, &NVPTX::Float64RegsRegClass);
89
90   if (RetainVectorOperands) {
91     addRegisterClass(MVT::v2f32, &NVPTX::V2F32RegsRegClass);
92     addRegisterClass(MVT::v4f32, &NVPTX::V4F32RegsRegClass);
93     addRegisterClass(MVT::v2i32, &NVPTX::V2I32RegsRegClass);
94     addRegisterClass(MVT::v4i32, &NVPTX::V4I32RegsRegClass);
95     addRegisterClass(MVT::v2f64, &NVPTX::V2F64RegsRegClass);
96     addRegisterClass(MVT::v2i64, &NVPTX::V2I64RegsRegClass);
97     addRegisterClass(MVT::v2i16, &NVPTX::V2I16RegsRegClass);
98     addRegisterClass(MVT::v4i16, &NVPTX::V4I16RegsRegClass);
99     addRegisterClass(MVT::v2i8, &NVPTX::V2I8RegsRegClass);
100     addRegisterClass(MVT::v4i8, &NVPTX::V4I8RegsRegClass);
101
102     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32  , Custom);
103     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32  , Custom);
104     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16  , Custom);
105     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i8   , Custom);
106     setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64  , Custom);
107     setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64  , Custom);
108     setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32  , Custom);
109     setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32  , Custom);
110     setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16  , Custom);
111     setOperationAction(ISD::BUILD_VECTOR, MVT::v2i8   , Custom);
112
113     setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i32  , Custom);
114     setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4f32  , Custom);
115     setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i16  , Custom);
116     setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i8   , Custom);
117     setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i64  , Custom);
118     setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2f64  , Custom);
119     setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i32  , Custom);
120     setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2f32  , Custom);
121     setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i16  , Custom);
122     setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i8   , Custom);
123   }
124
125   // Operations not directly supported by NVPTX.
126   setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
127   setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
128   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i64, Expand);
129   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Expand);
130   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
131   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
132   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
133
134   if (nvptxSubtarget.hasROT64()) {
135     setOperationAction(ISD::ROTL , MVT::i64, Legal);
136     setOperationAction(ISD::ROTR , MVT::i64, Legal);
137   }
138   else {
139     setOperationAction(ISD::ROTL , MVT::i64, Expand);
140     setOperationAction(ISD::ROTR , MVT::i64, Expand);
141   }
142   if (nvptxSubtarget.hasROT32()) {
143     setOperationAction(ISD::ROTL , MVT::i32, Legal);
144     setOperationAction(ISD::ROTR , MVT::i32, Legal);
145   }
146   else {
147     setOperationAction(ISD::ROTL , MVT::i32, Expand);
148     setOperationAction(ISD::ROTR , MVT::i32, Expand);
149   }
150
151   setOperationAction(ISD::ROTL , MVT::i16, Expand);
152   setOperationAction(ISD::ROTR , MVT::i16, Expand);
153   setOperationAction(ISD::ROTL , MVT::i8, Expand);
154   setOperationAction(ISD::ROTR , MVT::i8, Expand);
155   setOperationAction(ISD::BSWAP , MVT::i16, Expand);
156   setOperationAction(ISD::BSWAP , MVT::i32, Expand);
157   setOperationAction(ISD::BSWAP , MVT::i64, Expand);
158
159   // Indirect branch is not supported.
160   // This also disables Jump Table creation.
161   setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
162   setOperationAction(ISD::BRIND,             MVT::Other, Expand);
163
164   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
165   setOperationAction(ISD::GlobalAddress   , MVT::i64  , Custom);
166
167   // We want to legalize constant related memmove and memcopy
168   // intrinsics.
169   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
170
171   // Turn FP extload into load/fextend
172   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
173   // Turn FP truncstore into trunc + store.
174   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
175
176   // PTX does not support load / store predicate registers
177   setOperationAction(ISD::LOAD, MVT::i1, Expand);
178   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
179   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
180   setOperationAction(ISD::STORE, MVT::i1, Expand);
181   setTruncStoreAction(MVT::i64, MVT::i1, Expand);
182   setTruncStoreAction(MVT::i32, MVT::i1, Expand);
183   setTruncStoreAction(MVT::i16, MVT::i1, Expand);
184   setTruncStoreAction(MVT::i8, MVT::i1, Expand);
185
186   // This is legal in NVPTX
187   setOperationAction(ISD::ConstantFP,         MVT::f64, Legal);
188   setOperationAction(ISD::ConstantFP,         MVT::f32, Legal);
189
190   // TRAP can be lowered to PTX trap
191   setOperationAction(ISD::TRAP,               MVT::Other, Legal);
192
193   // By default, CONCAT_VECTORS is implemented via store/load
194   // through stack. It is slow and uses local memory. We need
195   // to custom-lowering them.
196   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32  , Custom);
197   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32  , Custom);
198   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i16  , Custom);
199   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i8   , Custom);
200   setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64  , Custom);
201   setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64  , Custom);
202   setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i32  , Custom);
203   setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f32  , Custom);
204   setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i16  , Custom);
205   setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i8   , Custom);
206
207   // Expand vector int to float and float to int conversions
208   // - For SINT_TO_FP and UINT_TO_FP, the src type
209   //   (Node->getOperand(0).getValueType())
210   //   is used to determine the action, while for FP_TO_UINT and FP_TO_SINT,
211   //   the dest type (Node->getValueType(0)) is used.
212   //
213   //   See VectorLegalizer::LegalizeOp() (LegalizeVectorOps.cpp) for the vector
214   //   case, and
215   //   SelectionDAGLegalize::LegalizeOp() (LegalizeDAG.cpp) for the scalar case.
216   //
217   //   That is why v4i32 or v2i32 are used here.
218   //
219   //   The expansion for vectors happens in VectorLegalizer::LegalizeOp()
220   //   (LegalizeVectorOps.cpp).
221   setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Expand);
222   setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Expand);
223   setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Expand);
224   setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Expand);
225   setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Expand);
226   setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Expand);
227   setOperationAction(ISD::FP_TO_UINT, MVT::v2i32, Expand);
228   setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Expand);
229
230   // Now deduce the information based on the above mentioned
231   // actions
232   computeRegisterProperties();
233 }
234
235
236 const char *NVPTXTargetLowering::getTargetNodeName(unsigned Opcode) const {
237   switch (Opcode) {
238   default: return 0;
239   case NVPTXISD::CALL:            return "NVPTXISD::CALL";
240   case NVPTXISD::RET_FLAG:        return "NVPTXISD::RET_FLAG";
241   case NVPTXISD::Wrapper:         return "NVPTXISD::Wrapper";
242   case NVPTXISD::NVBuiltin:       return "NVPTXISD::NVBuiltin";
243   case NVPTXISD::DeclareParam:    return "NVPTXISD::DeclareParam";
244   case NVPTXISD::DeclareScalarParam:
245     return "NVPTXISD::DeclareScalarParam";
246   case NVPTXISD::DeclareRet:      return "NVPTXISD::DeclareRet";
247   case NVPTXISD::DeclareRetParam: return "NVPTXISD::DeclareRetParam";
248   case NVPTXISD::PrintCall:       return "NVPTXISD::PrintCall";
249   case NVPTXISD::LoadParam:       return "NVPTXISD::LoadParam";
250   case NVPTXISD::StoreParam:      return "NVPTXISD::StoreParam";
251   case NVPTXISD::StoreParamS32:   return "NVPTXISD::StoreParamS32";
252   case NVPTXISD::StoreParamU32:   return "NVPTXISD::StoreParamU32";
253   case NVPTXISD::MoveToParam:     return "NVPTXISD::MoveToParam";
254   case NVPTXISD::CallArgBegin:    return "NVPTXISD::CallArgBegin";
255   case NVPTXISD::CallArg:         return "NVPTXISD::CallArg";
256   case NVPTXISD::LastCallArg:     return "NVPTXISD::LastCallArg";
257   case NVPTXISD::CallArgEnd:      return "NVPTXISD::CallArgEnd";
258   case NVPTXISD::CallVoid:        return "NVPTXISD::CallVoid";
259   case NVPTXISD::CallVal:         return "NVPTXISD::CallVal";
260   case NVPTXISD::CallSymbol:      return "NVPTXISD::CallSymbol";
261   case NVPTXISD::Prototype:       return "NVPTXISD::Prototype";
262   case NVPTXISD::MoveParam:       return "NVPTXISD::MoveParam";
263   case NVPTXISD::MoveRetval:      return "NVPTXISD::MoveRetval";
264   case NVPTXISD::MoveToRetval:    return "NVPTXISD::MoveToRetval";
265   case NVPTXISD::StoreRetval:     return "NVPTXISD::StoreRetval";
266   case NVPTXISD::PseudoUseParam:  return "NVPTXISD::PseudoUseParam";
267   case NVPTXISD::RETURN:          return "NVPTXISD::RETURN";
268   case NVPTXISD::CallSeqBegin:    return "NVPTXISD::CallSeqBegin";
269   case NVPTXISD::CallSeqEnd:      return "NVPTXISD::CallSeqEnd";
270   }
271 }
272
273
274 SDValue
275 NVPTXTargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
276   DebugLoc dl = Op.getDebugLoc();
277   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
278   Op = DAG.getTargetGlobalAddress(GV, dl, getPointerTy());
279   return DAG.getNode(NVPTXISD::Wrapper, dl, getPointerTy(), Op);
280 }
281
282 std::string NVPTXTargetLowering::getPrototype(Type *retTy,
283                                               const ArgListTy &Args,
284                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
285                                               unsigned retAlignment) const {
286
287   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
288
289   std::stringstream O;
290   O << "prototype_" << uniqueCallSite << " : .callprototype ";
291
292   if (retTy->getTypeID() == Type::VoidTyID)
293     O << "()";
294   else {
295     O << "(";
296     if (isABI) {
297       if (retTy->isPrimitiveType() || retTy->isIntegerTy()) {
298         unsigned size = 0;
299         if (const IntegerType *ITy = dyn_cast<IntegerType>(retTy)) {
300           size = ITy->getBitWidth();
301           if (size < 32) size = 32;
302         }
303         else {
304           assert(retTy->isFloatingPointTy() &&
305                  "Floating point type expected here");
306           size = retTy->getPrimitiveSizeInBits();
307         }
308
309         O << ".param .b" << size << " _";
310       }
311       else if (isa<PointerType>(retTy))
312         O << ".param .b" << getPointerTy().getSizeInBits()
313         << " _";
314       else {
315         if ((retTy->getTypeID() == Type::StructTyID) ||
316             isa<VectorType>(retTy)) {
317           SmallVector<EVT, 16> vtparts;
318           ComputeValueVTs(*this, retTy, vtparts);
319           unsigned totalsz = 0;
320           for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
321             unsigned elems = 1;
322             EVT elemtype = vtparts[i];
323             if (vtparts[i].isVector()) {
324               elems = vtparts[i].getVectorNumElements();
325               elemtype = vtparts[i].getVectorElementType();
326             }
327             for (unsigned j=0, je=elems; j!=je; ++j) {
328               unsigned sz = elemtype.getSizeInBits();
329               if (elemtype.isInteger() && (sz < 8)) sz = 8;
330               totalsz += sz/8;
331             }
332           }
333           O << ".param .align "
334               << retAlignment
335               << " .b8 _["
336               << totalsz << "]";
337         }
338         else {
339           assert(false &&
340                  "Unknown return type");
341         }
342       }
343     }
344     else {
345       SmallVector<EVT, 16> vtparts;
346       ComputeValueVTs(*this, retTy, vtparts);
347       unsigned idx = 0;
348       for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
349         unsigned elems = 1;
350         EVT elemtype = vtparts[i];
351         if (vtparts[i].isVector()) {
352           elems = vtparts[i].getVectorNumElements();
353           elemtype = vtparts[i].getVectorElementType();
354         }
355
356         for (unsigned j=0, je=elems; j!=je; ++j) {
357           unsigned sz = elemtype.getSizeInBits();
358           if (elemtype.isInteger() && (sz < 32)) sz = 32;
359           O << ".reg .b" << sz << " _";
360           if (j<je-1) O << ", ";
361           ++idx;
362         }
363         if (i < e-1)
364           O << ", ";
365       }
366     }
367     O << ") ";
368   }
369   O << "_ (";
370
371   bool first = true;
372   MVT thePointerTy = getPointerTy();
373
374   for (unsigned i=0,e=Args.size(); i!=e; ++i) {
375     const Type *Ty = Args[i].Ty;
376     if (!first) {
377       O << ", ";
378     }
379     first = false;
380
381     if (Outs[i].Flags.isByVal() == false) {
382       unsigned sz = 0;
383       if (isa<IntegerType>(Ty)) {
384         sz = cast<IntegerType>(Ty)->getBitWidth();
385         if (sz < 32) sz = 32;
386       }
387       else if (isa<PointerType>(Ty))
388         sz = thePointerTy.getSizeInBits();
389       else
390         sz = Ty->getPrimitiveSizeInBits();
391       if (isABI)
392         O << ".param .b" << sz << " ";
393       else
394         O << ".reg .b" << sz << " ";
395       O << "_";
396       continue;
397     }
398     const PointerType *PTy = dyn_cast<PointerType>(Ty);
399     assert(PTy &&
400            "Param with byval attribute should be a pointer type");
401     Type *ETy = PTy->getElementType();
402
403     if (isABI) {
404       unsigned align = Outs[i].Flags.getByValAlign();
405       unsigned sz = getTargetData()->getTypeAllocSize(ETy);
406       O << ".param .align " << align
407           << " .b8 ";
408       O << "_";
409       O << "[" << sz << "]";
410       continue;
411     }
412     else {
413       SmallVector<EVT, 16> vtparts;
414       ComputeValueVTs(*this, ETy, vtparts);
415       for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
416         unsigned elems = 1;
417         EVT elemtype = vtparts[i];
418         if (vtparts[i].isVector()) {
419           elems = vtparts[i].getVectorNumElements();
420           elemtype = vtparts[i].getVectorElementType();
421         }
422
423         for (unsigned j=0,je=elems; j!=je; ++j) {
424           unsigned sz = elemtype.getSizeInBits();
425           if (elemtype.isInteger() && (sz < 32)) sz = 32;
426           O << ".reg .b" << sz << " ";
427           O << "_";
428           if (j<je-1) O << ", ";
429         }
430         if (i<e-1)
431           O << ", ";
432       }
433       continue;
434     }
435   }
436   O << ");";
437   return O.str();
438 }
439
440
441 #if 0
442 SDValue
443 NVPTXTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
444                                CallingConv::ID CallConv, bool isVarArg,
445                                bool doesNotRet, bool &isTailCall,
446                                const SmallVectorImpl<ISD::OutputArg> &Outs,
447                                const SmallVectorImpl<SDValue> &OutVals,
448                                const SmallVectorImpl<ISD::InputArg> &Ins,
449                                DebugLoc dl, SelectionDAG &DAG,
450                                SmallVectorImpl<SDValue> &InVals, Type *retTy,
451                                const ArgListTy &Args) const {
452   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
453
454   SDValue tempChain = Chain;
455   Chain = DAG.getCALLSEQ_START(Chain,
456                                DAG.getIntPtrConstant(uniqueCallSite, true));
457   SDValue InFlag = Chain.getValue(1);
458
459   assert((Outs.size() == Args.size()) &&
460          "Unexpected number of arguments to function call");
461   unsigned paramCount = 0;
462   // Declare the .params or .reg need to pass values
463   // to the function
464   for (unsigned i=0, e=Outs.size(); i!=e; ++i) {
465     EVT VT = Outs[i].VT;
466
467     if (Outs[i].Flags.isByVal() == false) {
468       // Plain scalar
469       // for ABI,    declare .param .b<size> .param<n>;
470       // for nonABI, declare .reg .b<size> .param<n>;
471       unsigned isReg = 1;
472       if (isABI)
473         isReg = 0;
474       unsigned sz = VT.getSizeInBits();
475       if (VT.isInteger() && (sz < 32)) sz = 32;
476       SDVTList DeclareParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
477       SDValue DeclareParamOps[] = { Chain,
478                                     DAG.getConstant(paramCount, MVT::i32),
479                                     DAG.getConstant(sz, MVT::i32),
480                                     DAG.getConstant(isReg, MVT::i32),
481                                     InFlag };
482       Chain = DAG.getNode(NVPTXISD::DeclareScalarParam, dl, DeclareParamVTs,
483                           DeclareParamOps, 5);
484       InFlag = Chain.getValue(1);
485       SDVTList CopyParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
486       SDValue CopyParamOps[] = { Chain, DAG.getConstant(paramCount, MVT::i32),
487                              DAG.getConstant(0, MVT::i32), OutVals[i], InFlag };
488
489       unsigned opcode = NVPTXISD::StoreParam;
490       if (isReg)
491         opcode = NVPTXISD::MoveToParam;
492       else {
493         if (Outs[i].Flags.isZExt())
494           opcode = NVPTXISD::StoreParamU32;
495         else if (Outs[i].Flags.isSExt())
496           opcode = NVPTXISD::StoreParamS32;
497       }
498       Chain = DAG.getNode(opcode, dl, CopyParamVTs, CopyParamOps, 5);
499
500       InFlag = Chain.getValue(1);
501       ++paramCount;
502       continue;
503     }
504     // struct or vector
505     SmallVector<EVT, 16> vtparts;
506     const PointerType *PTy = dyn_cast<PointerType>(Args[i].Ty);
507     assert(PTy &&
508            "Type of a byval parameter should be pointer");
509     ComputeValueVTs(*this, PTy->getElementType(), vtparts);
510
511     if (isABI) {
512       // declare .param .align 16 .b8 .param<n>[<size>];
513       unsigned sz = Outs[i].Flags.getByValSize();
514       SDVTList DeclareParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
515       // The ByValAlign in the Outs[i].Flags is alway set at this point, so we
516       // don't need to
517       // worry about natural alignment or not. See TargetLowering::LowerCallTo()
518       SDValue DeclareParamOps[] = { Chain,
519                        DAG.getConstant(Outs[i].Flags.getByValAlign(), MVT::i32),
520                                     DAG.getConstant(paramCount, MVT::i32),
521                                     DAG.getConstant(sz, MVT::i32),
522                                     InFlag };
523       Chain = DAG.getNode(NVPTXISD::DeclareParam, dl, DeclareParamVTs,
524                           DeclareParamOps, 5);
525       InFlag = Chain.getValue(1);
526       unsigned curOffset = 0;
527       for (unsigned j=0,je=vtparts.size(); j!=je; ++j) {
528         unsigned elems = 1;
529         EVT elemtype = vtparts[j];
530         if (vtparts[j].isVector()) {
531           elems = vtparts[j].getVectorNumElements();
532           elemtype = vtparts[j].getVectorElementType();
533         }
534         for (unsigned k=0,ke=elems; k!=ke; ++k) {
535           unsigned sz = elemtype.getSizeInBits();
536           if (elemtype.isInteger() && (sz < 8)) sz = 8;
537           SDValue srcAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(),
538                                         OutVals[i],
539                                         DAG.getConstant(curOffset,
540                                                         getPointerTy()));
541           SDValue theVal = DAG.getLoad(elemtype, dl, tempChain, srcAddr,
542                                 MachinePointerInfo(), false, false, false, 0);
543           SDVTList CopyParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
544           SDValue CopyParamOps[] = { Chain, DAG.getConstant(paramCount,
545                                                             MVT::i32),
546                                            DAG.getConstant(curOffset, MVT::i32),
547                                                             theVal, InFlag };
548           Chain = DAG.getNode(NVPTXISD::StoreParam, dl, CopyParamVTs,
549                               CopyParamOps, 5);
550           InFlag = Chain.getValue(1);
551           curOffset += sz/8;
552         }
553       }
554       ++paramCount;
555       continue;
556     }
557     // Non-abi, struct or vector
558     // Declare a bunch or .reg .b<size> .param<n>
559     unsigned curOffset = 0;
560     for (unsigned j=0,je=vtparts.size(); j!=je; ++j) {
561       unsigned elems = 1;
562       EVT elemtype = vtparts[j];
563       if (vtparts[j].isVector()) {
564         elems = vtparts[j].getVectorNumElements();
565         elemtype = vtparts[j].getVectorElementType();
566       }
567       for (unsigned k=0,ke=elems; k!=ke; ++k) {
568         unsigned sz = elemtype.getSizeInBits();
569         if (elemtype.isInteger() && (sz < 32)) sz = 32;
570         SDVTList DeclareParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
571         SDValue DeclareParamOps[] = { Chain, DAG.getConstant(paramCount,
572                                                              MVT::i32),
573                                                   DAG.getConstant(sz, MVT::i32),
574                                                    DAG.getConstant(1, MVT::i32),
575                                                              InFlag };
576         Chain = DAG.getNode(NVPTXISD::DeclareScalarParam, dl, DeclareParamVTs,
577                             DeclareParamOps, 5);
578         InFlag = Chain.getValue(1);
579         SDValue srcAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), OutVals[i],
580                                       DAG.getConstant(curOffset,
581                                                       getPointerTy()));
582         SDValue theVal = DAG.getLoad(elemtype, dl, tempChain, srcAddr,
583                                   MachinePointerInfo(), false, false, false, 0);
584         SDVTList CopyParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
585         SDValue CopyParamOps[] = { Chain, DAG.getConstant(paramCount, MVT::i32),
586                                    DAG.getConstant(0, MVT::i32), theVal,
587                                    InFlag };
588         Chain = DAG.getNode(NVPTXISD::MoveToParam, dl, CopyParamVTs,
589                             CopyParamOps, 5);
590         InFlag = Chain.getValue(1);
591         ++paramCount;
592       }
593     }
594   }
595
596   GlobalAddressSDNode *Func = dyn_cast<GlobalAddressSDNode>(Callee.getNode());
597   unsigned retAlignment = 0;
598
599   // Handle Result
600   unsigned retCount = 0;
601   if (Ins.size() > 0) {
602     SmallVector<EVT, 16> resvtparts;
603     ComputeValueVTs(*this, retTy, resvtparts);
604
605     // Declare one .param .align 16 .b8 func_retval0[<size>] for ABI or
606     // individual .reg .b<size> func_retval<0..> for non ABI
607     unsigned resultsz = 0;
608     for (unsigned i=0,e=resvtparts.size(); i!=e; ++i) {
609       unsigned elems = 1;
610       EVT elemtype = resvtparts[i];
611       if (resvtparts[i].isVector()) {
612         elems = resvtparts[i].getVectorNumElements();
613         elemtype = resvtparts[i].getVectorElementType();
614       }
615       for (unsigned j=0,je=elems; j!=je; ++j) {
616         unsigned sz = elemtype.getSizeInBits();
617         if (isABI == false) {
618           if (elemtype.isInteger() && (sz < 32)) sz = 32;
619         }
620         else {
621           if (elemtype.isInteger() && (sz < 8)) sz = 8;
622         }
623         if (isABI == false) {
624           SDVTList DeclareRetVTs = DAG.getVTList(MVT::Other, MVT::Glue);
625           SDValue DeclareRetOps[] = { Chain, DAG.getConstant(2, MVT::i32),
626                                       DAG.getConstant(sz, MVT::i32),
627                                       DAG.getConstant(retCount, MVT::i32),
628                                       InFlag };
629           Chain = DAG.getNode(NVPTXISD::DeclareRet, dl, DeclareRetVTs,
630                               DeclareRetOps, 5);
631           InFlag = Chain.getValue(1);
632           ++retCount;
633         }
634         resultsz += sz;
635       }
636     }
637     if (isABI) {
638       if (retTy->isPrimitiveType() || retTy->isIntegerTy() ||
639           retTy->isPointerTy() ) {
640         // Scalar needs to be at least 32bit wide
641         if (resultsz < 32)
642           resultsz = 32;
643         SDVTList DeclareRetVTs = DAG.getVTList(MVT::Other, MVT::Glue);
644         SDValue DeclareRetOps[] = { Chain, DAG.getConstant(1, MVT::i32),
645                                     DAG.getConstant(resultsz, MVT::i32),
646                                     DAG.getConstant(0, MVT::i32), InFlag };
647         Chain = DAG.getNode(NVPTXISD::DeclareRet, dl, DeclareRetVTs,
648                             DeclareRetOps, 5);
649         InFlag = Chain.getValue(1);
650       }
651       else {
652         // @TODO: Re-enable getAlign calls.  We do not have the
653         // ImmutableCallSite object here anymore.
654         //if (Func) { // direct call
655         //if (!llvm::getAlign(*(CS->getCalledFunction()), 0, retAlignment))
656         //retAlignment = TD->getABITypeAlignment(retTy);
657         //}
658         //else { // indirect call
659         //const CallInst *CallI = dyn_cast<CallInst>(CS->getInstruction());
660         //if (!llvm::getAlign(*CallI, 0, retAlignment))
661         //retAlignment = TD->getABITypeAlignment(retTy);
662         //}
663         // @TODO: Remove this hack!
664         // Functions with explicit alignment metadata will be broken, for now.
665         retAlignment = 16;
666         SDVTList DeclareRetVTs = DAG.getVTList(MVT::Other, MVT::Glue);
667         SDValue DeclareRetOps[] = { Chain, DAG.getConstant(retAlignment,
668                                                            MVT::i32),
669                                           DAG.getConstant(resultsz/8, MVT::i32),
670                                          DAG.getConstant(0, MVT::i32), InFlag };
671         Chain = DAG.getNode(NVPTXISD::DeclareRetParam, dl, DeclareRetVTs,
672                             DeclareRetOps, 5);
673         InFlag = Chain.getValue(1);
674       }
675     }
676   }
677
678   if (!Func) {
679     // This is indirect function call case : PTX requires a prototype of the
680     // form
681     // proto_0 : .callprototype(.param .b32 _) _ (.param .b32 _);
682     // to be emitted, and the label has to used as the last arg of call
683     // instruction.
684     // The prototype is embedded in a string and put as the operand for an
685     // INLINEASM SDNode.
686     SDVTList InlineAsmVTs = DAG.getVTList(MVT::Other, MVT::Glue);
687     std::string proto_string = getPrototype(retTy, Args, Outs, retAlignment);
688     const char *asmstr = nvTM->getManagedStrPool()->
689         getManagedString(proto_string.c_str())->c_str();
690     SDValue InlineAsmOps[] = { Chain,
691                                DAG.getTargetExternalSymbol(asmstr,
692                                                            getPointerTy()),
693                                                            DAG.getMDNode(0),
694                                    DAG.getTargetConstant(0, MVT::i32), InFlag };
695     Chain = DAG.getNode(ISD::INLINEASM, dl, InlineAsmVTs, InlineAsmOps, 5);
696     InFlag = Chain.getValue(1);
697   }
698   // Op to just print "call"
699   SDVTList PrintCallVTs = DAG.getVTList(MVT::Other, MVT::Glue);
700   SDValue PrintCallOps[] = { Chain,
701                              DAG.getConstant(isABI ? ((Ins.size()==0) ? 0 : 1)
702                                  : retCount, MVT::i32),
703                                    InFlag };
704   Chain = DAG.getNode(Func?(NVPTXISD::PrintCallUni):(NVPTXISD::PrintCall), dl,
705       PrintCallVTs, PrintCallOps, 3);
706   InFlag = Chain.getValue(1);
707
708   // Ops to print out the function name
709   SDVTList CallVoidVTs = DAG.getVTList(MVT::Other, MVT::Glue);
710   SDValue CallVoidOps[] = { Chain, Callee, InFlag };
711   Chain = DAG.getNode(NVPTXISD::CallVoid, dl, CallVoidVTs, CallVoidOps, 3);
712   InFlag = Chain.getValue(1);
713
714   // Ops to print out the param list
715   SDVTList CallArgBeginVTs = DAG.getVTList(MVT::Other, MVT::Glue);
716   SDValue CallArgBeginOps[] = { Chain, InFlag };
717   Chain = DAG.getNode(NVPTXISD::CallArgBegin, dl, CallArgBeginVTs,
718                       CallArgBeginOps, 2);
719   InFlag = Chain.getValue(1);
720
721   for (unsigned i=0, e=paramCount; i!=e; ++i) {
722     unsigned opcode;
723     if (i==(e-1))
724       opcode = NVPTXISD::LastCallArg;
725     else
726       opcode = NVPTXISD::CallArg;
727     SDVTList CallArgVTs = DAG.getVTList(MVT::Other, MVT::Glue);
728     SDValue CallArgOps[] = { Chain, DAG.getConstant(1, MVT::i32),
729                              DAG.getConstant(i, MVT::i32),
730                              InFlag };
731     Chain = DAG.getNode(opcode, dl, CallArgVTs, CallArgOps, 4);
732     InFlag = Chain.getValue(1);
733   }
734   SDVTList CallArgEndVTs = DAG.getVTList(MVT::Other, MVT::Glue);
735   SDValue CallArgEndOps[] = { Chain,
736                               DAG.getConstant(Func ? 1 : 0, MVT::i32),
737                               InFlag };
738   Chain = DAG.getNode(NVPTXISD::CallArgEnd, dl, CallArgEndVTs, CallArgEndOps,
739                       3);
740   InFlag = Chain.getValue(1);
741
742   if (!Func) {
743     SDVTList PrototypeVTs = DAG.getVTList(MVT::Other, MVT::Glue);
744     SDValue PrototypeOps[] = { Chain,
745                                DAG.getConstant(uniqueCallSite, MVT::i32),
746                                InFlag };
747     Chain = DAG.getNode(NVPTXISD::Prototype, dl, PrototypeVTs, PrototypeOps, 3);
748     InFlag = Chain.getValue(1);
749   }
750
751   // Generate loads from param memory/moves from registers for result
752   if (Ins.size() > 0) {
753     if (isABI) {
754       unsigned resoffset = 0;
755       for (unsigned i=0,e=Ins.size(); i!=e; ++i) {
756         unsigned sz = Ins[i].VT.getSizeInBits();
757         if (Ins[i].VT.isInteger() && (sz < 8)) sz = 8;
758         std::vector<EVT> LoadRetVTs;
759         LoadRetVTs.push_back(Ins[i].VT);
760         LoadRetVTs.push_back(MVT::Other); LoadRetVTs.push_back(MVT::Glue);
761         std::vector<SDValue> LoadRetOps;
762         LoadRetOps.push_back(Chain);
763         LoadRetOps.push_back(DAG.getConstant(1, MVT::i32));
764         LoadRetOps.push_back(DAG.getConstant(resoffset, MVT::i32));
765         LoadRetOps.push_back(InFlag);
766         SDValue retval = DAG.getNode(NVPTXISD::LoadParam, dl, LoadRetVTs,
767                                      &LoadRetOps[0], LoadRetOps.size());
768         Chain = retval.getValue(1);
769         InFlag = retval.getValue(2);
770         InVals.push_back(retval);
771         resoffset += sz/8;
772       }
773     }
774     else {
775       SmallVector<EVT, 16> resvtparts;
776       ComputeValueVTs(*this, retTy, resvtparts);
777
778       assert(Ins.size() == resvtparts.size() &&
779              "Unexpected number of return values in non-ABI case");
780       unsigned paramNum = 0;
781       for (unsigned i=0,e=Ins.size(); i!=e; ++i) {
782         assert(EVT(Ins[i].VT) == resvtparts[i] &&
783                "Unexpected EVT type in non-ABI case");
784         unsigned numelems = 1;
785         EVT elemtype = Ins[i].VT;
786         if (Ins[i].VT.isVector()) {
787           numelems = Ins[i].VT.getVectorNumElements();
788           elemtype = Ins[i].VT.getVectorElementType();
789         }
790         std::vector<SDValue> tempRetVals;
791         for (unsigned j=0; j<numelems; ++j) {
792           std::vector<EVT> MoveRetVTs;
793           MoveRetVTs.push_back(elemtype);
794           MoveRetVTs.push_back(MVT::Other); MoveRetVTs.push_back(MVT::Glue);
795           std::vector<SDValue> MoveRetOps;
796           MoveRetOps.push_back(Chain);
797           MoveRetOps.push_back(DAG.getConstant(0, MVT::i32));
798           MoveRetOps.push_back(DAG.getConstant(paramNum, MVT::i32));
799           MoveRetOps.push_back(InFlag);
800           SDValue retval = DAG.getNode(NVPTXISD::LoadParam, dl, MoveRetVTs,
801                                        &MoveRetOps[0], MoveRetOps.size());
802           Chain = retval.getValue(1);
803           InFlag = retval.getValue(2);
804           tempRetVals.push_back(retval);
805           ++paramNum;
806         }
807         if (Ins[i].VT.isVector())
808           InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, Ins[i].VT,
809                                        &tempRetVals[0], tempRetVals.size()));
810         else
811           InVals.push_back(tempRetVals[0]);
812       }
813     }
814   }
815   Chain = DAG.getCALLSEQ_END(Chain,
816                              DAG.getIntPtrConstant(uniqueCallSite, true),
817                              DAG.getIntPtrConstant(uniqueCallSite+1, true),
818                              InFlag);
819   uniqueCallSite++;
820
821   // set isTailCall to false for now, until we figure out how to express
822   // tail call optimization in PTX
823   isTailCall = false;
824   return Chain;
825 }
826 #endif
827
828 // By default CONCAT_VECTORS is lowered by ExpandVectorBuildThroughStack()
829 // (see LegalizeDAG.cpp). This is slow and uses local memory.
830 // We use extract/insert/build vector just as what LegalizeOp() does in llvm 2.5
831 SDValue NVPTXTargetLowering::
832 LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
833   SDNode *Node = Op.getNode();
834   DebugLoc dl = Node->getDebugLoc();
835   SmallVector<SDValue, 8> Ops;
836   unsigned NumOperands = Node->getNumOperands();
837   for (unsigned i=0; i < NumOperands; ++i) {
838     SDValue SubOp = Node->getOperand(i);
839     EVT VVT = SubOp.getNode()->getValueType(0);
840     EVT EltVT = VVT.getVectorElementType();
841     unsigned NumSubElem = VVT.getVectorNumElements();
842     for (unsigned j=0; j < NumSubElem; ++j) {
843       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, SubOp,
844                                 DAG.getIntPtrConstant(j)));
845     }
846   }
847   return DAG.getNode(ISD::BUILD_VECTOR, dl, Node->getValueType(0),
848                      &Ops[0], Ops.size());
849 }
850
851 SDValue NVPTXTargetLowering::
852 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
853   switch (Op.getOpcode()) {
854   case ISD::RETURNADDR: return SDValue();
855   case ISD::FRAMEADDR:  return SDValue();
856   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
857   case ISD::INTRINSIC_W_CHAIN: return Op;
858   case ISD::BUILD_VECTOR:
859   case ISD::EXTRACT_SUBVECTOR:
860     return Op;
861   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
862   default:
863     assert(0 && "Custom lowering not defined for operation");
864   }
865 }
866
867 SDValue
868 NVPTXTargetLowering::getExtSymb(SelectionDAG &DAG, const char *inname, int idx,
869                                 EVT v) const {
870   std::string *name = nvTM->getManagedStrPool()->getManagedString(inname);
871   std::stringstream suffix;
872   suffix << idx;
873   *name += suffix.str();
874   return DAG.getTargetExternalSymbol(name->c_str(), v);
875 }
876
877 SDValue
878 NVPTXTargetLowering::getParamSymbol(SelectionDAG &DAG, int idx, EVT v) const {
879   return getExtSymb(DAG, ".PARAM", idx, v);
880 }
881
882 SDValue
883 NVPTXTargetLowering::getParamHelpSymbol(SelectionDAG &DAG, int idx) {
884   return getExtSymb(DAG, ".HLPPARAM", idx);
885 }
886
887 // Check to see if the kernel argument is image*_t or sampler_t
888
889 bool llvm::isImageOrSamplerVal(const Value *arg, const Module *context) {
890   const char *specialTypes[] = {
891                                 "struct._image2d_t",
892                                 "struct._image3d_t",
893                                 "struct._sampler_t"
894   };
895
896   const Type *Ty = arg->getType();
897   const PointerType *PTy = dyn_cast<PointerType>(Ty);
898
899   if (!PTy)
900     return false;
901
902   if (!context)
903     return false;
904
905   const StructType *STy = dyn_cast<StructType>(PTy->getElementType());
906   const std::string TypeName = STy ? STy->getName() : "";
907
908   for (int i=0, e=sizeof(specialTypes)/sizeof(specialTypes[0]); i!=e; ++i)
909     if (TypeName == specialTypes[i])
910       return true;
911
912   return false;
913 }
914
915 SDValue
916 NVPTXTargetLowering::LowerFormalArguments(SDValue Chain,
917                                         CallingConv::ID CallConv, bool isVarArg,
918                                       const SmallVectorImpl<ISD::InputArg> &Ins,
919                                           DebugLoc dl, SelectionDAG &DAG,
920                                        SmallVectorImpl<SDValue> &InVals) const {
921   MachineFunction &MF = DAG.getMachineFunction();
922   const TargetData *TD = getTargetData();
923
924   const Function *F = MF.getFunction();
925   const AttrListPtr &PAL = F->getAttributes();
926
927   SDValue Root = DAG.getRoot();
928   std::vector<SDValue> OutChains;
929
930   bool isKernel = llvm::isKernelFunction(*F);
931   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
932
933   std::vector<Type *> argTypes;
934   std::vector<const Argument *> theArgs;
935   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
936       I != E; ++I) {
937     theArgs.push_back(I);
938     argTypes.push_back(I->getType());
939   }
940   assert(argTypes.size() == Ins.size() &&
941          "Ins types and function types did not match");
942
943   int idx = 0;
944   for (unsigned i=0, e=Ins.size(); i!=e; ++i, ++idx) {
945     Type *Ty = argTypes[i];
946     EVT ObjectVT = getValueType(Ty);
947     assert(ObjectVT == Ins[i].VT &&
948            "Ins type did not match function type");
949
950     // If the kernel argument is image*_t or sampler_t, convert it to
951     // a i32 constant holding the parameter position. This can later
952     // matched in the AsmPrinter to output the correct mangled name.
953     if (isImageOrSamplerVal(theArgs[i],
954                            (theArgs[i]->getParent() ?
955                                theArgs[i]->getParent()->getParent() : 0))) {
956       assert(isKernel && "Only kernels can have image/sampler params");
957       InVals.push_back(DAG.getConstant(i+1, MVT::i32));
958       continue;
959     }
960
961     if (theArgs[i]->use_empty()) {
962       // argument is dead
963       InVals.push_back(DAG.getNode(ISD::UNDEF, dl, ObjectVT));
964       continue;
965     }
966
967     // In the following cases, assign a node order of "idx+1"
968     // to newly created nodes. The SDNOdes for params have to
969     // appear in the same order as their order of appearance
970     // in the original function. "idx+1" holds that order.
971     if (PAL.paramHasAttr(i+1, Attribute::ByVal) == false) {
972       // A plain scalar.
973       if (isABI || isKernel) {
974         // If ABI, load from the param symbol
975         SDValue Arg = getParamSymbol(DAG, idx);
976         Value *srcValue = new Argument(PointerType::get(ObjectVT.getTypeForEVT(
977             F->getContext()),
978             llvm::ADDRESS_SPACE_PARAM));
979         SDValue p = DAG.getLoad(ObjectVT, dl, Root, Arg,
980                                 MachinePointerInfo(srcValue), false, false,
981                                 false,
982                                 TD->getABITypeAlignment(ObjectVT.getTypeForEVT(
983                                   F->getContext())));
984         if (p.getNode())
985           DAG.AssignOrdering(p.getNode(), idx+1);
986         InVals.push_back(p);
987       }
988       else {
989         // If no ABI, just move the param symbol
990         SDValue Arg = getParamSymbol(DAG, idx, ObjectVT);
991         SDValue p = DAG.getNode(NVPTXISD::MoveParam, dl, ObjectVT, Arg);
992         if (p.getNode())
993           DAG.AssignOrdering(p.getNode(), idx+1);
994         InVals.push_back(p);
995       }
996       continue;
997     }
998
999     // Param has ByVal attribute
1000     if (isABI || isKernel) {
1001       // Return MoveParam(param symbol).
1002       // Ideally, the param symbol can be returned directly,
1003       // but when SDNode builder decides to use it in a CopyToReg(),
1004       // machine instruction fails because TargetExternalSymbol
1005       // (not lowered) is target dependent, and CopyToReg assumes
1006       // the source is lowered.
1007       SDValue Arg = getParamSymbol(DAG, idx, getPointerTy());
1008       SDValue p = DAG.getNode(NVPTXISD::MoveParam, dl, ObjectVT, Arg);
1009       if (p.getNode())
1010         DAG.AssignOrdering(p.getNode(), idx+1);
1011       if (isKernel)
1012         InVals.push_back(p);
1013       else {
1014         SDValue p2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, ObjectVT,
1015                     DAG.getConstant(Intrinsic::nvvm_ptr_local_to_gen, MVT::i32),
1016                                  p);
1017         InVals.push_back(p2);
1018       }
1019     } else {
1020       // Have to move a set of param symbols to registers and
1021       // store them locally and return the local pointer in InVals
1022       const PointerType *elemPtrType = dyn_cast<PointerType>(argTypes[i]);
1023       assert(elemPtrType &&
1024              "Byval parameter should be a pointer type");
1025       Type *elemType = elemPtrType->getElementType();
1026       // Compute the constituent parts
1027       SmallVector<EVT, 16> vtparts;
1028       SmallVector<uint64_t, 16> offsets;
1029       ComputeValueVTs(*this, elemType, vtparts, &offsets, 0);
1030       unsigned totalsize = 0;
1031       for (unsigned j=0, je=vtparts.size(); j!=je; ++j)
1032         totalsize += vtparts[j].getStoreSizeInBits();
1033       SDValue localcopy =  DAG.getFrameIndex(MF.getFrameInfo()->
1034                                       CreateStackObject(totalsize/8, 16, false),
1035                                              getPointerTy());
1036       unsigned sizesofar = 0;
1037       std::vector<SDValue> theChains;
1038       for (unsigned j=0, je=vtparts.size(); j!=je; ++j) {
1039         unsigned numElems = 1;
1040         if (vtparts[j].isVector()) numElems = vtparts[j].getVectorNumElements();
1041         for (unsigned k=0, ke=numElems; k!=ke; ++k) {
1042           EVT tmpvt = vtparts[j];
1043           if (tmpvt.isVector()) tmpvt = tmpvt.getVectorElementType();
1044           SDValue arg = DAG.getNode(NVPTXISD::MoveParam, dl, tmpvt,
1045                                     getParamSymbol(DAG, idx, tmpvt));
1046           SDValue addr = DAG.getNode(ISD::ADD, dl, getPointerTy(), localcopy,
1047                                     DAG.getConstant(sizesofar, getPointerTy()));
1048           theChains.push_back(DAG.getStore(Chain, dl, arg, addr,
1049                                         MachinePointerInfo(), false, false, 0));
1050           sizesofar += tmpvt.getStoreSizeInBits()/8;
1051           ++idx;
1052         }
1053       }
1054       --idx;
1055       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &theChains[0],
1056                           theChains.size());
1057       InVals.push_back(localcopy);
1058     }
1059   }
1060
1061   // Clang will check explicit VarArg and issue error if any. However, Clang
1062   // will let code with
1063   // implicit var arg like f() pass.
1064   // We treat this case as if the arg list is empty.
1065   //if (F.isVarArg()) {
1066   // assert(0 && "VarArg not supported yet!");
1067   //}
1068
1069   if (!OutChains.empty())
1070     DAG.setRoot(DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1071                             &OutChains[0], OutChains.size()));
1072
1073   return Chain;
1074 }
1075
1076 SDValue
1077 NVPTXTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1078                                  bool isVarArg,
1079                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
1080                                  const SmallVectorImpl<SDValue> &OutVals,
1081                                  DebugLoc dl, SelectionDAG &DAG) const {
1082
1083   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1084
1085   unsigned sizesofar = 0;
1086   unsigned idx = 0;
1087   for (unsigned i=0, e=Outs.size(); i!=e; ++i) {
1088     SDValue theVal = OutVals[i];
1089     EVT theValType = theVal.getValueType();
1090     unsigned numElems = 1;
1091     if (theValType.isVector()) numElems = theValType.getVectorNumElements();
1092     for (unsigned j=0,je=numElems; j!=je; ++j) {
1093       SDValue tmpval = theVal;
1094       if (theValType.isVector())
1095         tmpval = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
1096                              theValType.getVectorElementType(),
1097                              tmpval, DAG.getIntPtrConstant(j));
1098       Chain = DAG.getNode(isABI ? NVPTXISD::StoreRetval :NVPTXISD::MoveToRetval,
1099           dl, MVT::Other,
1100           Chain,
1101           DAG.getConstant(isABI ? sizesofar : idx, MVT::i32),
1102           tmpval);
1103       if (theValType.isVector())
1104         sizesofar += theValType.getVectorElementType().getStoreSizeInBits()/8;
1105       else
1106         sizesofar += theValType.getStoreSizeInBits()/8;
1107       ++idx;
1108     }
1109   }
1110
1111   return DAG.getNode(NVPTXISD::RET_FLAG, dl, MVT::Other, Chain);
1112 }
1113
1114 void
1115 NVPTXTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
1116                                                   std::string &Constraint,
1117                                                   std::vector<SDValue> &Ops,
1118                                                   SelectionDAG &DAG) const
1119 {
1120   if (Constraint.length() > 1)
1121     return;
1122   else
1123     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
1124 }
1125
1126 // NVPTX suuport vector of legal types of any length in Intrinsics because the
1127 // NVPTX specific type legalizer
1128 // will legalize them to the PTX supported length.
1129 bool
1130 NVPTXTargetLowering::isTypeSupportedInIntrinsic(MVT VT) const {
1131   if (isTypeLegal(VT))
1132     return true;
1133   if (VT.isVector()) {
1134     MVT eVT = VT.getVectorElementType();
1135     if (isTypeLegal(eVT))
1136       return true;
1137   }
1138   return false;
1139 }
1140
1141
1142 // llvm.ptx.memcpy.const and llvm.ptx.memmove.const need to be modeled as
1143 // TgtMemIntrinsic
1144 // because we need the information that is only available in the "Value" type
1145 // of destination
1146 // pointer. In particular, the address space information.
1147 bool
1148 NVPTXTargetLowering::getTgtMemIntrinsic(IntrinsicInfo& Info, const CallInst &I,
1149                                         unsigned Intrinsic) const {
1150   switch (Intrinsic) {
1151   default:
1152     return false;
1153
1154   case Intrinsic::nvvm_atomic_load_add_f32:
1155     Info.opc = ISD::INTRINSIC_W_CHAIN;
1156     Info.memVT = MVT::f32;
1157     Info.ptrVal = I.getArgOperand(0);
1158     Info.offset = 0;
1159     Info.vol = 0;
1160     Info.readMem = true;
1161     Info.writeMem = true;
1162     Info.align = 0;
1163     return true;
1164
1165   case Intrinsic::nvvm_atomic_load_inc_32:
1166   case Intrinsic::nvvm_atomic_load_dec_32:
1167     Info.opc = ISD::INTRINSIC_W_CHAIN;
1168     Info.memVT = MVT::i32;
1169     Info.ptrVal = I.getArgOperand(0);
1170     Info.offset = 0;
1171     Info.vol = 0;
1172     Info.readMem = true;
1173     Info.writeMem = true;
1174     Info.align = 0;
1175     return true;
1176
1177   case Intrinsic::nvvm_ldu_global_i:
1178   case Intrinsic::nvvm_ldu_global_f:
1179   case Intrinsic::nvvm_ldu_global_p:
1180
1181     Info.opc = ISD::INTRINSIC_W_CHAIN;
1182     if (Intrinsic == Intrinsic::nvvm_ldu_global_i)
1183       Info.memVT = MVT::i32;
1184     else if (Intrinsic == Intrinsic::nvvm_ldu_global_p)
1185       Info.memVT = getPointerTy();
1186     else
1187       Info.memVT = MVT::f32;
1188     Info.ptrVal = I.getArgOperand(0);
1189     Info.offset = 0;
1190     Info.vol = 0;
1191     Info.readMem = true;
1192     Info.writeMem = false;
1193     Info.align = 0;
1194     return true;
1195
1196   }
1197   return false;
1198 }
1199
1200 /// isLegalAddressingMode - Return true if the addressing mode represented
1201 /// by AM is legal for this target, for a load/store of the specified type.
1202 /// Used to guide target specific optimizations, like loop strength reduction
1203 /// (LoopStrengthReduce.cpp) and memory optimization for address mode
1204 /// (CodeGenPrepare.cpp)
1205 bool
1206 NVPTXTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1207                                            Type *Ty) const {
1208
1209   // AddrMode - This represents an addressing mode of:
1210   //    BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1211   //
1212   // The legal address modes are
1213   // - [avar]
1214   // - [areg]
1215   // - [areg+immoff]
1216   // - [immAddr]
1217
1218   if (AM.BaseGV) {
1219     if (AM.BaseOffs || AM.HasBaseReg || AM.Scale)
1220       return false;
1221     return true;
1222   }
1223
1224   switch (AM.Scale) {
1225   case 0:  // "r", "r+i" or "i" is allowed
1226     break;
1227   case 1:
1228     if (AM.HasBaseReg)  // "r+r+i" or "r+r" is not allowed.
1229       return false;
1230     // Otherwise we have r+i.
1231     break;
1232   default:
1233     // No scale > 1 is allowed
1234     return false;
1235   }
1236   return true;
1237 }
1238
1239 //===----------------------------------------------------------------------===//
1240 //                         NVPTX Inline Assembly Support
1241 //===----------------------------------------------------------------------===//
1242
1243 /// getConstraintType - Given a constraint letter, return the type of
1244 /// constraint it is for this target.
1245 NVPTXTargetLowering::ConstraintType
1246 NVPTXTargetLowering::getConstraintType(const std::string &Constraint) const {
1247   if (Constraint.size() == 1) {
1248     switch (Constraint[0]) {
1249     default:
1250       break;
1251     case 'r':
1252     case 'h':
1253     case 'c':
1254     case 'l':
1255     case 'f':
1256     case 'd':
1257     case '0':
1258     case 'N':
1259       return C_RegisterClass;
1260     }
1261   }
1262   return TargetLowering::getConstraintType(Constraint);
1263 }
1264
1265
1266 std::pair<unsigned, const TargetRegisterClass*>
1267 NVPTXTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
1268                                                   EVT VT) const {
1269   if (Constraint.size() == 1) {
1270     switch (Constraint[0]) {
1271     case 'c':
1272       return std::make_pair(0U, &NVPTX::Int8RegsRegClass);
1273     case 'h':
1274       return std::make_pair(0U, &NVPTX::Int16RegsRegClass);
1275     case 'r':
1276       return std::make_pair(0U, &NVPTX::Int32RegsRegClass);
1277     case 'l':
1278     case 'N':
1279       return std::make_pair(0U, &NVPTX::Int64RegsRegClass);
1280     case 'f':
1281       return std::make_pair(0U, &NVPTX::Float32RegsRegClass);
1282     case 'd':
1283       return std::make_pair(0U, &NVPTX::Float64RegsRegClass);
1284     }
1285   }
1286   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1287 }
1288
1289
1290
1291 /// getFunctionAlignment - Return the Log2 alignment of this function.
1292 unsigned NVPTXTargetLowering::getFunctionAlignment(const Function *) const {
1293   return 4;
1294 }