blob: 9b4297d1ae6cf9b03744963c339d140f6767675b [file] [log] [blame]
Jean-Luc Brouillet36090672015-04-07 15:15:53 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <algorithm>
18#include <iostream>
19#include <iterator>
20#include <sstream>
21
22#include "Generator.h"
23#include "Specification.h"
24#include "Utilities.h"
25
26using namespace std;
27
28const int kMinimumApiLevelForTests = 11;
29const int kApiLevelWithFirst64Bit = 21;
30
31// Used to map the built-in types to their mangled representations
32struct BuiltInMangling {
33 const char* token[3]; // The last two entries can be nullptr
34 const char* equivalence; // The mangled equivalent
35};
36
37BuiltInMangling builtInMangling[] = {
38 {{"long", "long"}, "x"},
39 {{"unsigned", "long", "long"}, "y"},
40 {{"long"}, "l"},
41 {{"unsigned", "long"}, "m"},
42 {{"int"}, "i"},
43 {{"unsigned", "int"}, "j"},
44 {{"short"}, "s"},
45 {{"unsigned", "short"}, "t"},
46 {{"char"}, "c"},
47 {{"unsigned", "char"}, "h"},
48 {{"signed", "char"}, "a"},
49 {{"void"}, "v"},
50 {{"wchar_t"}, "w"},
51 {{"bool"}, "b"},
52 {{"__fp16"}, "Dh"},
53 {{"float"}, "f"},
54 {{"double"}, "d"},
55};
56
57/* For the given API level and bitness (e.g. 32 or 64 bit), try to find a
58 * substitution for the provided type name, as would be done (mostly) by a
59 * preprocessor. Returns empty string if there's no substitution.
60 */
61static string findSubstitute(const string& typeName, int apiLevel, int intSize) {
62 const auto& types = systemSpecification.getTypes();
63 const auto type = types.find(typeName);
64 if (type != types.end()) {
65 for (TypeSpecification* spec : type->second->getSpecifications()) {
66 // Verify this specification applies
67 const VersionInfo info = spec->getVersionInfo();
68 if (!info.includesVersion(apiLevel) || (info.intSize != 0 && info.intSize != intSize)) {
69 continue;
70 }
71 switch (spec->getKind()) {
72 case SIMPLE: {
Stephen Hinesca51c782015-08-25 23:43:34 -070073 return spec->getSimpleType();
74 }
75 case RS_OBJECT: {
76 // Do nothing for RS object types.
Jean-Luc Brouillet36090672015-04-07 15:15:53 -070077 break;
78 }
79 case STRUCT: {
Stephen Hinesca51c782015-08-25 23:43:34 -070080 return spec->getStructName();
Jean-Luc Brouillet36090672015-04-07 15:15:53 -070081 }
82 case ENUM:
83 // Do nothing
84 break;
85 }
86 }
87 }
88 return "";
89}
90
91/* Expand the typedefs found in 'type' into their equivalents and tokenize
92 * the resulting list. 'apiLevel' and 'intSize' specifies the API level and bitness
93 * we are currently processing.
94 */
95list<string> expandTypedefs(const string type, int apiLevel, int intSize) {
96 // Split the string in tokens.
97 istringstream stream(type);
98 list<string> tokens{istream_iterator<string>{stream}, istream_iterator<string>{}};
99 // Try to substitue each token.
100 for (auto i = tokens.begin(); i != tokens.end();) {
101 const string substitute = findSubstitute(*i, apiLevel, intSize);
102 if (substitute.empty()) {
103 // No substitution possible, just go to the next token.
104 i++;
105 } else {
106 // Split the replacement string in tokens.
107 istringstream stream(substitute);
108 list<string> newTokens{istream_iterator<string>{stream}, istream_iterator<string>{}};
109 // Replace the token with the substitution. Don't advance, as the new substitution
110 // might itself be replaced.
111 auto prev = i;
112 --prev;
113 tokens.insert(i, newTokens.begin(), newTokens.end());
114 tokens.erase(i);
115 advance(i, -newTokens.size());
116 }
117 }
118 return tokens;
119}
120
121// Remove the first element of the list if it equals 'prefix'. Return true in that case.
122static bool eatFront(list<string>* tokens, const char* prefix) {
123 if (tokens->front() == prefix) {
124 tokens->pop_front();
125 return true;
126 }
127 return false;
128}
129
130/* Search the table of translations for the built-ins for the mangling that
131 * corresponds to this list of tokens. If a match is found, consume these tokens
132 * and return a pointer to the string. If not, return nullptr.
133 */
134static const char* findManglingOfBuiltInType(list<string>* tokens) {
135 for (const BuiltInMangling& a : builtInMangling) {
136 auto t = tokens->begin();
137 auto end = tokens->end();
138 bool match = true;
139 // We match up to three tokens.
140 for (int i = 0; i < 3; i++) {
141 if (!a.token[i]) {
142 // No more tokens
143 break;
144 }
145 if (t == end || *t++ != a.token[i]) {
146 match = false;
147 }
148 }
149 if (match) {
150 tokens->erase(tokens->begin(), t);
151 return a.equivalence;
152 }
153 }
154 return nullptr;
155}
156
157// Mangle a long name by prefixing it with its length, e.g. "13rs_allocation".
158static inline string mangleLongName(const string& name) {
159 return to_string(name.size()) + name;
160}
161
162/* Mangle the type name that's represented by the vector size and list of tokens.
163 * The mangling will be returned in full form in 'mangling'. 'compressedMangling'
164 * will have the compressed equivalent. This is built using the 'previousManglings'
165 * list. false is returned if an error is encountered.
166 *
167 * This function is recursive because compression is possible at each level of the definition.
168 * See http://mentorembedded.github.io/cxx-abi/abi.html#mangle.type for a description
169 * of the Itanium mangling used by llvm.
170 *
171 * This function mangles correctly the types currently used by RenderScript. It does
172 * not currently mangle more complicated types like function pointers, namespaces,
173 * or other C++ types. In particular, we don't deal correctly with parenthesis.
174 */
175static bool mangleType(string vectorSize, list<string>* tokens, vector<string>* previousManglings,
176 string* mangling, string* compressedMangling) {
177 string delta; // The part of the mangling we're generating for this recursion.
178 bool isTerminal = false; // True if this iteration parses a terminal node in the production.
179 bool canBeCompressed = true; // Will be false for manglings of builtins.
180
181 if (tokens->back() == "*") {
182 delta = "P";
183 tokens->pop_back();
184 } else if (eatFront(tokens, "const")) {
185 delta = "K";
186 } else if (eatFront(tokens, "volatile")) {
187 delta = "V";
188 } else if (vectorSize != "1" && vectorSize != "") {
189 // For vector, prefix with the abbreviation for a vector, including the size.
190 delta = "Dv" + vectorSize + "_";
191 vectorSize.clear(); // Reset to mark the size as consumed.
192 } else if (eatFront(tokens, "struct")) {
193 // For a structure, we just use the structure name
194 if (tokens->size() == 0) {
195 cerr << "Expected a name after struct\n";
196 return false;
197 }
198 delta = mangleLongName(tokens->front());
199 isTerminal = true;
200 tokens->pop_front();
201 } else {
202 const char* c = findManglingOfBuiltInType(tokens);
203 if (c) {
204 // It's a basic type. We don't use those directly for compression.
205 delta = c;
206 isTerminal = true;
207 canBeCompressed = false;
208 } else if (tokens->size() > 0) {
209 // It's a complex type name.
210 delta = mangleLongName(tokens->front());
211 isTerminal = true;
212 tokens->pop_front();
213 }
214 }
215
216 if (isTerminal) {
217 // If we're the terminal node, there should be nothing left to mangle.
218 if (tokens->size() > 0) {
219 cerr << "Expected nothing else but found";
220 for (const auto& t : *tokens) {
221 cerr << " " << t;
222 }
223 cerr << "\n";
224 return false;
225 }
226 *mangling = delta;
227 *compressedMangling = delta;
228 } else {
229 // We're not terminal. Recurse and prefix what we've translated this pass.
230 if (tokens->size() == 0) {
231 cerr << "Expected a more complete type\n";
232 return false;
233 }
234 string rest, compressedRest;
235 if (!mangleType(vectorSize, tokens, previousManglings, &rest, &compressedRest)) {
236 return false;
237 }
238 *mangling = delta + rest;
239 *compressedMangling = delta + compressedRest;
240 }
241
242 /* If it's a built-in type, we don't look at previously emitted ones and we
243 * don't keep track of it.
244 */
245 if (!canBeCompressed) {
246 return true;
247 }
248
249 // See if we've encountered this mangling before.
250 for (size_t i = 0; i < previousManglings->size(); ++i) {
251 if ((*previousManglings)[i] == *mangling) {
252 // We have a match, construct an index reference to that previously emitted mangling.
253 ostringstream stream2;
254 stream2 << 'S';
255 if (i > 0) {
256 stream2 << (char)('0' + i - 1);
257 }
258 stream2 << '_';
259 *compressedMangling = stream2.str();
260 return true;
261 }
262 }
263
264 // We have not encountered this before. Add it to the list.
265 previousManglings->push_back(*mangling);
266 return true;
267}
268
269// Write to the stream the mangled representation of each parameter.
270static bool writeParameters(ostringstream* stream, const std::vector<ParameterDefinition*>& params,
271 int apiLevel, int intSize) {
272 if (params.empty()) {
273 *stream << "v";
274 return true;
275 }
276 /* We keep track of the previously generated parameter types, as type mangling
277 * is compressed by reusing previous manglings.
278 */
279 vector<string> previousManglings;
280 for (ParameterDefinition* p : params) {
281 // Expand the typedefs and create a tokenized list.
282 list<string> tokens = expandTypedefs(p->rsType, apiLevel, intSize);
283 if (p->isOutParameter) {
284 tokens.push_back("*");
285 }
286 string mangling, compressedMangling;
287 if (!mangleType(p->mVectorSize, &tokens, &previousManglings, &mangling,
288 &compressedMangling)) {
289 return false;
290 }
291 *stream << compressedMangling;
292 }
293 return true;
294}
295
296/* Add the mangling for this permutation of the function. apiLevel and intSize is used
297 * to select the correct type when expanding complex type.
298 */
299static bool addFunctionManglingToSet(const Function& function,
300 const FunctionPermutation& permutation, bool overloadable,
301 int apiLevel, int intSize, set<string>* allManglings) {
302 const string& functionName = permutation.getName();
303 string mangling;
304 if (overloadable) {
305 ostringstream stream;
306 stream << "_Z" << mangleLongName(functionName);
307 if (!writeParameters(&stream, permutation.getParams(), apiLevel, intSize)) {
308 cerr << "Error mangling " << functionName << ". See above message.\n";
309 return false;
310 }
311 mangling = stream.str();
312 } else {
313 mangling = functionName;
314 }
315 allManglings->insert(mangling);
316 return true;
317}
318
319/* Add to the set the mangling of each function prototype that can be generated from this
320 * specification, i.e. for all the versions covered and for 32/64 bits. We call this
321 * for each API level because the implementation of a type may have changed in the range
322 * of API levels covered.
323 */
324static bool addManglingsForSpecification(const Function& function,
325 const FunctionSpecification& spec, int lastApiLevel,
326 set<string>* allManglings) {
327 // If the function is inlined, we won't generate an unresolved external for that.
328 if (spec.hasInline()) {
329 return true;
330 }
331 const VersionInfo info = spec.getVersionInfo();
332 const int minApiLevel = info.minVersion ? info.minVersion : kMinimumApiLevelForTests;
333 const int maxApiLevel = info.maxVersion ? info.maxVersion : lastApiLevel;
334 const bool overloadable = spec.isOverloadable();
335
336 /* We track success rather than aborting early in case of failure so that we
337 * generate all the error messages.
338 */
339 bool success = true;
340 for (int apiLevel = minApiLevel; apiLevel <= maxApiLevel; ++apiLevel) {
341 for (auto permutation : spec.getPermutations()) {
342 if (info.intSize == 0 || info.intSize == 32) {
343 if (!addFunctionManglingToSet(function, *permutation, overloadable, apiLevel, 32,
344 allManglings)) {
345 success = false;
346 }
347 }
348 if (apiLevel >= kApiLevelWithFirst64Bit && (info.intSize == 0 || info.intSize == 64)) {
349 if (!addFunctionManglingToSet(function, *permutation, overloadable, apiLevel, 64,
350 allManglings)) {
351 success = false;
352 }
353 }
354 }
355 }
356 return success;
357}
358
359/* Generate the white list file of the mangled function prototypes. This generated list is used
360 * to validate unresolved external references. 'lastApiLevel' is the largest api level found in
361 * all spec files.
362 */
363static bool generateWhiteListFile(int lastApiLevel) {
364 bool success = true;
365 // We generate all the manglings in a set to remove duplicates and to order them.
366 set<string> allManglings;
367 for (auto f : systemSpecification.getFunctions()) {
368 const Function* function = f.second;
369 for (auto spec : function->getSpecifications()) {
370 if (!addManglingsForSpecification(*function, *spec, lastApiLevel, &allManglings)) {
371 success = false; // We continue so we can generate all errors.
372 }
373 }
374 }
375
376 if (success) {
377 GeneratedFile file;
378 if (!file.start(".", "RSStubsWhiteList.cpp")) {
379 return false;
380 }
381
382 file.writeNotices();
383 file << "#include \"RSStubsWhiteList.h\"\n\n";
384 file << "std::vector<std::string> stubList = {\n";
385 for (const auto& e : allManglings) {
386 file << "\"" << e << "\",\n";
387 }
388 file << "};\n";
389 }
390 return success;
391}
392
393// Add a uniquely named variable definition to the file and return its name.
394static const string addVariable(GeneratedFile* file, unsigned int* variableNumber) {
395 const string name = "buf" + to_string((*variableNumber)++);
396 /* Some data structures like rs_tm can't be exported. We'll just use a dumb buffer
397 * and cast its address later on.
398 */
399 *file << "char " << name << "[200];\n";
400 return name;
401}
402
403/* Write to the file the globals needed to make the call for this permutation. The actual
404 * call is stored in 'calls', as we'll need to generate all the global variable declarations
405 * before the function definition.
406 */
407static void generateTestCall(GeneratedFile* file, ostringstream* calls,
408 unsigned int* variableNumber, const Function& function,
409 const FunctionPermutation& permutation) {
410 *calls << " ";
411
412 // Handle the return type.
413 const auto ret = permutation.getReturn();
414 if (ret && ret->rsType != "void" && ret->rsType != "const void") {
415 *calls << "*(" << ret->rsType << "*)" << addVariable(file, variableNumber) << " = ";
416 }
417
418 *calls << permutation.getName() << "(";
419
420 // Generate the arguments.
421 const char* separator = "";
422 for (auto p : permutation.getParams()) {
423 *calls << separator;
424 // Special case for the kernel context, as it has a special existence.
425 if (p->rsType == "rs_kernel_context") {
Jean-Luc Brouillet4324eec2015-08-07 16:58:38 -0700426 *calls << "context";
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700427 } else if (p->isOutParameter) {
428 *calls << "(" << p->rsType << "*) " << addVariable(file, variableNumber);
429 } else {
430 *calls << "*(" << p->rsType << "*)" << addVariable(file, variableNumber);
431 }
432 separator = ", ";
433 }
434 *calls << ");\n";
435}
436
437/* Generate a test file that will be used in the frameworks/compile/slang/tests unit tests.
438 * This file tests that all RenderScript APIs can be called for the specified API level.
439 * To avoid the compiler agressively pruning out our calls, we use globals as inputs and outputs.
440 *
441 * Since some structures can't be defined at the global level, we use casts of simple byte
442 * buffers to get around that restriction.
443 *
444 * This file can be used to verify the white list that's also generated in this file. To do so,
445 * run "llvm-nm -undefined-only -just-symbol-name" on the resulting bit code.
446 */
447static bool generateApiTesterFile(const string& slangTestDirectory, int apiLevel) {
448 GeneratedFile file;
449 if (!file.start(slangTestDirectory, "all" + to_string(apiLevel) + ".rs")) {
450 return false;
451 }
452
453 /* This unusual comment is used by slang/tests/test.py to know which parameter to pass
454 * to llvm-rs-cc when compiling the test.
455 */
456 file << "// -target-api " << apiLevel << " -Wno-deprecated-declarations\n";
457
458 file.writeNotices();
459 file << "#pragma version(1)\n";
460 file << "#pragma rs java_package_name(com.example.renderscript.testallapi)\n\n";
461 if (apiLevel < 23) { // All rs_graphics APIs were deprecated in api level 23.
462 file << "#include \"rs_graphics.rsh\"\n\n";
463 }
464
465 /* The code below emits globals and calls to functions in parallel. We store
466 * the calls in a stream so that we can emit them in the file in the proper order.
467 */
468 ostringstream calls;
469 unsigned int variableNumber = 0; // Used to generate unique names.
470 for (auto f : systemSpecification.getFunctions()) {
471 const Function* function = f.second;
472 for (auto spec : function->getSpecifications()) {
473 VersionInfo info = spec->getVersionInfo();
474 if (!info.includesVersion(apiLevel)) {
475 continue;
476 }
477 if (info.intSize == 32) {
478 calls << "#ifndef __LP64__\n";
479 } else if (info.intSize == 64) {
480 calls << "#ifdef __LP64__\n";
481 }
482 for (auto permutation : spec->getPermutations()) {
483 generateTestCall(&file, &calls, &variableNumber, *function, *permutation);
484 }
485 if (info.intSize != 0) {
486 calls << "#endif\n";
487 }
488 }
489 }
490 file << "\n";
491
492 // Modify the style of kernel as required by the API level.
493 if (apiLevel >= 23) {
Jean-Luc Brouillet4324eec2015-08-07 16:58:38 -0700494 file << "void RS_KERNEL test(int in, rs_kernel_context context) {\n";
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700495 } else if (apiLevel >= 17) {
496 file << "void RS_KERNEL test(int in) {\n";
497 } else {
498 file << "void root(const int* in) {\n";
499 }
500 file << calls.str();
501 file << "}\n";
502
503 return true;
504}
505
506bool generateStubsWhiteList(const string& slangTestDirectory, int maxApiLevel) {
507 int lastApiLevel = min(systemSpecification.getMaximumApiLevel(), maxApiLevel);
508 if (!generateWhiteListFile(lastApiLevel)) {
509 return false;
510 }
511 // Generate a test file for each apiLevel.
512 for (int i = kMinimumApiLevelForTests; i <= lastApiLevel; ++i) {
513 if (!generateApiTesterFile(slangTestDirectory, i)) {
514 return false;
515 }
516 }
517 return true;
518}