NVPTX: Stop leaking memory by using a managed constant instead of a new Argument.
[oota-llvm.git] / lib / Target / NVPTX / NVPTXutil.cpp
1 //===-- NVPTXutil.cpp - Functions exported to CodeGen --*- C++ -*-===//
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 contains the functions that can be used in CodeGen.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "NVPTXutil.h"
15 #include "NVPTX.h"
16
17 using namespace llvm;
18
19 namespace llvm {
20
21 bool isParamLoad(const MachineInstr *MI)
22 {
23   if ((MI->getOpcode() != NVPTX::LD_i32_avar) &&
24       (MI->getOpcode() != NVPTX::LD_i64_avar))
25     return false;
26   if (MI->getOperand(2).isImm() == false)
27     return false;
28   if (MI->getOperand(2).getImm() != NVPTX::PTXLdStInstCode::PARAM)
29     return false;
30   return true;
31 }
32
33 #define DATA_MASK     0x7f
34 #define DIGIT_WIDTH   7
35 #define MORE_BYTES    0x80
36
37 static int encode_leb128(uint64_t val, int *nbytes,
38                          char *space, int splen)
39 {
40   char *a;
41   char *end = space + splen;
42
43   a = space;
44   do {
45     unsigned char uc;
46
47     if (a >= end)
48       return 1;
49     uc = val & DATA_MASK;
50     val >>= DIGIT_WIDTH;
51     if (val != 0)
52       uc |= MORE_BYTES;
53     *a = uc;
54     a++;
55   } while (val);
56   *nbytes = a - space;
57   return 0;
58 }
59
60 #undef DATA_MASK
61 #undef DIGIT_WIDTH
62 #undef MORE_BYTES
63
64 uint64_t encode_leb128(const char *str)
65 {
66   union { uint64_t x; char a[8]; } temp64;
67
68   temp64.x = 0;
69
70   for (unsigned i=0,e=strlen(str); i!=e; ++i)
71     temp64.a[i] = str[e-1-i];
72
73   char encoded[16];
74   int nbytes;
75
76   int retval = encode_leb128(temp64.x, &nbytes, encoded, 16);
77
78   (void)retval;
79   assert(retval == 0 &&
80          "Encoding to leb128 failed");
81
82   assert(nbytes <= 8 &&
83          "Cannot support register names with leb128 encoding > 8 bytes");
84
85   temp64.x = 0;
86   for (int i=0; i<nbytes; ++i)
87     temp64.a[i] = encoded[i];
88
89   return temp64.x;
90 }
91
92 } // end namespace llvm