aboutsummaryrefslogtreecommitdiff
path: root/lib/RSGlobalInfoPass.cpp
blob: 40d658b7199035719dfa2a3a7465917c5df15034 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/*
 * Copyright 2015, The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Assert.h"
#include "Log.h"
#include "RSUtils.h"

#include "rsDefines.h"

#include <llvm/IR/Constant.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/Pass.h>

#include <sstream>
#include <vector>

namespace {

const bool kDebugGlobalInfo = false;

/* RSGlobalInfoPass: Embeds additional information about RenderScript global
 * variables into the Module. The 5 variables added are specified as follows:
 * 1) .rs.global_entries
 *    i32 - int
 *    Optional number of global variables.
 * 2) .rs.global_names
 *    [N * i8*] - const char *[N]
 *    Optional global variable name info. Each entry corresponds to the name
 *    of 1 of the N global variables.
 * 3) .rs.global_addresses
 *    [N * i8*] - void*[N] or void**
 *    Optional global variable address info. Each entry corresponds to the
 *    address of 1 of the N global variables.
 * 4) .rs.global_sizes
 *    [N * i32] or [N * i64] - size_t[N]
 *    Optional global variable size info. Each entry corresponds to the size
 *    of 1 of the N global variables.
 * 5) .rs.global_properties
 *    [N * i32]
 *    Optional global properties. Each entry corresponds to the properties
 *    for 1 of the N global variables. The 32-bit integer for properties
 *    can be broken down as follows:
 *    bit(s)    Encoded value
 *    ------    -------------
 *        18    Pointer (1 is pointer, 0 is non-pointer)
 *        17    Static (1 is static, 0 is extern)
 *        16    Constant (1 is const, 0 is non-const)
 *    15 - 0    RsDataType (see frameworks/rs/rsDefines.h for more info)
 */
class RSGlobalInfoPass: public llvm::ModulePass {
private:
  // If true, we don't include information about immutable global variables
  // in our various exported data structures.
  bool mSkipConstants;

  // Encodes properties of the GlobalVariable into a uint32_t.
  // These values are used to populate the .rs.global_properties array.
  static uint32_t getEncodedProperties(const llvm::GlobalVariable &GV) {
    auto GlobalType = GV.getType()->getPointerElementType();

    // We start by getting the RsDataType and placing it into our result.
    uint32_t result = getRsDataTypeForType(GlobalType);
    bccAssert(!(result & ~RS_GLOBAL_TYPE));  // Can only alter lower 16-bits.

    if (GlobalType->isPointerTy()) {
      // Global variables that are pointers can all be used with "bind".
      result |= RS_GLOBAL_POINTER;
    }

    if (GV.isConstant()) {
      result |= RS_GLOBAL_CONSTANT;
    }

    if (GV.getLinkage() == llvm::GlobalValue::InternalLinkage) {
      // We only have internal linkage in RS to signify static.
      result |= RS_GLOBAL_STATIC;
    }

    return result;
  }

public:
  static char ID;

  explicit RSGlobalInfoPass(bool pSkipConstants = false)
    : ModulePass (ID), mSkipConstants(pSkipConstants) {
  }

  void getAnalysisUsage(llvm::AnalysisUsage &AU) const override {
    // This pass does not use any other analysis passes, but it does
    // add new global variables.
  }

  bool runOnModule(llvm::Module &M) override {
    std::vector<llvm::Constant *> GVAddresses;
    std::vector<llvm::Constant *> GVNames;
    std::vector<std::string> GVNameStrings;
    std::vector<uint32_t> GVSizes32;
    std::vector<uint64_t> GVSizes64;
    std::vector<uint32_t> GVProperties;

    const llvm::DataLayout &DL = M.getDataLayout();
    const size_t PointerSizeInBits = DL.getPointerSizeInBits();

    bccAssert(PointerSizeInBits == 32 || PointerSizeInBits == 64);

    int GlobalNumber = 0;

    // i8* - LLVM uses this to represent void* and char*
    llvm::Type *VoidPtrTy = llvm::Type::getInt8PtrTy(M.getContext());

    // i32
    llvm::Type *Int32Ty = llvm::Type::getInt32Ty(M.getContext());

    // i32 or i64 depending on our actual size_t
    llvm::Type *SizeTy = llvm::Type::getIntNTy(M.getContext(),
                                               PointerSizeInBits);

    for (auto &GV : M.globals()) {
      // Skip constant variables if we were configured to do so.
      if (mSkipConstants && GV.isConstant()) {
        continue;
      }

      // Skip intrinsic variables.
      if (GV.getName().startswith("llvm.")) {
        continue;
      }

      // In LLVM, an instance of GlobalVariable is actually a Value
      // corresponding to the address of it.
      GVAddresses.push_back(llvm::ConstantExpr::getBitCast(&GV, VoidPtrTy));
      GVNameStrings.push_back(GV.getName());

      // Since these are all global variables, their type is actually a
      // pointer to the underlying data. We can extract the total underlying
      // storage size by looking at the first contained type.
      auto GlobalType = GV.getType()->getPointerElementType();
      auto TypeSize = DL.getTypeAllocSize(GlobalType);
      if (PointerSizeInBits == 32) {
        GVSizes32.push_back(TypeSize);
      } else {
        GVSizes64.push_back(TypeSize);
      }

      GVProperties.push_back(getEncodedProperties(GV));
    }

    // Create the new strings for storing the names of the global variables.
    // This has to be done as a separate pass (over the original global
    // variables), because these strings are new global variables themselves.
    for (const auto &GVN : GVNameStrings) {
      llvm::Constant *C =
          llvm::ConstantDataArray::getString(M.getContext(), GVN);
      std::stringstream VarName;
      VarName << ".rs.name_str_" << GlobalNumber++;
      llvm::Value *V = M.getOrInsertGlobal(VarName.str(), C->getType());
      llvm::GlobalVariable *VarAsStr = llvm::dyn_cast<llvm::GlobalVariable>(V);
      VarAsStr->setInitializer(C);
      VarAsStr->setConstant(true);
      VarAsStr->setLinkage(llvm::GlobalValue::PrivateLinkage);
      VarAsStr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
      // VarAsStr has type [_ x i8]*. Cast to i8* for storing in
      // .rs.global_names.
      GVNames.push_back(llvm::ConstantExpr::getBitCast(VarAsStr, VoidPtrTy));
    }

    if (PointerSizeInBits == 32) {
      bccAssert(GVAddresses.size() == GVSizes32.size());
      bccAssert(GVSizes64.size() == 0);
      bccAssert(GVAddresses.size() == GVProperties.size());
    } else {
      bccAssert(GVSizes32.size() == 0);
      bccAssert(GVAddresses.size() == GVSizes64.size());
      bccAssert(GVAddresses.size() == GVProperties.size());
    }

    size_t NumGlobals = GVAddresses.size();

    // [NumGlobals * i8*]
    llvm::ArrayType *VoidPtrArrayTy = llvm::ArrayType::get(VoidPtrTy,
                                                           NumGlobals);
    // [NumGlobals * i32] or [NumGlobals * i64]
    llvm::ArrayType *SizeArrayTy = llvm::ArrayType::get(SizeTy, NumGlobals);

    // [NumGlobals * i32]
    llvm::ArrayType *Int32ArrayTy = llvm::ArrayType::get(Int32Ty, NumGlobals);

    // 1) @.rs.global_entries = constant i32 NumGlobals
    llvm::Value *V = M.getOrInsertGlobal(kRsGlobalEntries, Int32Ty);
    llvm::GlobalVariable *GlobalEntries =
        llvm::dyn_cast<llvm::GlobalVariable>(V);
    llvm::Constant *GlobalEntriesInit =
        llvm::ConstantInt::get(Int32Ty, NumGlobals);
    GlobalEntries->setInitializer(GlobalEntriesInit);
    GlobalEntries->setConstant(true);

    // 2) @.rs.global_names = constant [N * i8*] [...]
    V = M.getOrInsertGlobal(kRsGlobalNames, VoidPtrArrayTy);
    llvm::GlobalVariable *GlobalNames =
        llvm::dyn_cast<llvm::GlobalVariable>(V);
    llvm::Constant *GlobalNamesInit =
        llvm::ConstantArray::get(VoidPtrArrayTy, GVNames);
    GlobalNames->setInitializer(GlobalNamesInit);
    GlobalNames->setConstant(true);

    // 3) @.rs.global_addresses = constant [N * i8*] [...]
    V = M.getOrInsertGlobal(kRsGlobalAddresses, VoidPtrArrayTy);
    llvm::GlobalVariable *GlobalAddresses =
        llvm::dyn_cast<llvm::GlobalVariable>(V);
    llvm::Constant *GlobalAddressesInit =
        llvm::ConstantArray::get(VoidPtrArrayTy, GVAddresses);
    GlobalAddresses->setInitializer(GlobalAddressesInit);
    GlobalAddresses->setConstant(true);


    // 4) @.rs.global_sizes = constant [N * i32 or i64] [...]
    V = M.getOrInsertGlobal(kRsGlobalSizes, SizeArrayTy);
    llvm::GlobalVariable *GlobalSizes =
        llvm::dyn_cast<llvm::GlobalVariable>(V);
    llvm::Constant *GlobalSizesInit;
    if (PointerSizeInBits == 32) {
      GlobalSizesInit = llvm::ConstantDataArray::get(M.getContext(), GVSizes32);
    } else {
      GlobalSizesInit = llvm::ConstantDataArray::get(M.getContext(), GVSizes64);
    }
    GlobalSizes->setInitializer(GlobalSizesInit);
    GlobalSizes->setConstant(true);

    // 5) @.rs.global_properties = constant i32 NumGlobals
    V = M.getOrInsertGlobal(kRsGlobalProperties, Int32ArrayTy);
    llvm::GlobalVariable *GlobalProperties =
        llvm::dyn_cast<llvm::GlobalVariable>(V);
    llvm::Constant *GlobalPropertiesInit =
        llvm::ConstantDataArray::get(M.getContext(), GVProperties);
    GlobalProperties->setInitializer(GlobalPropertiesInit);
    GlobalProperties->setConstant(true);

    if (kDebugGlobalInfo) {
      GlobalEntries->dump();
      GlobalNames->dump();
      GlobalAddresses->dump();
      GlobalSizes->dump();
      GlobalProperties->dump();
    }

    // Upon completion, this pass has always modified the Module.
    return true;
  }
};

}

char RSGlobalInfoPass::ID = 0;

static llvm::RegisterPass<RSGlobalInfoPass> X("embed-rs-global-info",
  "Embed additional information about RenderScript global variables");

namespace bcc {

llvm::ModulePass * createRSGlobalInfoPass(bool pSkipConstants) {
  return new RSGlobalInfoPass(pSkipConstants);
}

}