blob: 4c3cb405dcea8197e1d72a192ff56a166150ca20 [file] [log] [blame]
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -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 <iomanip>
18#include <iostream>
19#include <cmath>
20#include <sstream>
21
22#include "Generator.h"
23#include "Specification.h"
24#include "Utilities.h"
25
26using namespace std;
27
28// Converts float2 to FLOAT_32 and 2, etc.
29static void convertToRsType(const string& name, string* dataType, char* vectorSize) {
30 string s = name;
31 int last = s.size() - 1;
32 char lastChar = s[last];
33 if (lastChar >= '1' && lastChar <= '4') {
34 s.erase(last);
35 *vectorSize = lastChar;
36 } else {
37 *vectorSize = '1';
38 }
39 dataType->clear();
40 for (int i = 0; i < NUM_TYPES; i++) {
41 if (s == TYPES[i].cType) {
42 *dataType = TYPES[i].rsDataType;
43 break;
44 }
45 }
46}
47
48// Returns true if any permutation of the function have tests to b
49static bool needTestFiles(const Function& function, int versionOfTestFiles) {
50 for (auto spec : function.getSpecifications()) {
51 if (spec->hasTests(versionOfTestFiles)) {
52 return true;
53 }
54 }
55 return false;
56}
57
58/* One instance of this class is generated for each permutation of a function for which
59 * we are generating test code. This instance will generate both the script and the Java
60 * section of the test files for this permutation. The class is mostly used to keep track
61 * of the various names shared between script and Java files.
62 * WARNING: Because the constructor keeps a reference to the FunctionPermutation, PermutationWriter
63 * should not exceed the lifetime of FunctionPermutation.
64 */
65class PermutationWriter {
66private:
67 FunctionPermutation& mPermutation;
68
69 string mRsKernelName;
70 string mJavaArgumentsClassName;
71 string mJavaArgumentsNClassName;
72 string mJavaVerifierComputeMethodName;
73 string mJavaVerifierVerifyMethodName;
74 string mJavaCheckMethodName;
75 string mJavaVerifyMethodName;
76
77 // Pointer to the files we are generating. Handy to avoid always passing them in the calls.
78 GeneratedFile* mRs;
79 GeneratedFile* mJava;
80
81 /* Shortcuts to the return parameter and the first input parameter of the function
82 * specification.
83 */
84 const ParameterDefinition* mReturnParam; // Can be nullptr. NOT OWNED.
85 const ParameterDefinition* mFirstInputParam; // Can be nullptr. NOT OWNED.
86
87 /* All the parameters plus the return param, if present. Collecting them together
88 * simplifies code generation. NOT OWNED.
89 */
90 vector<const ParameterDefinition*> mAllInputsAndOutputs;
91
92 /* We use a class to pass the arguments between the generated code and the CoreVerifier. This
93 * method generates this class. The set keeps track if we've generated this class already
94 * for this test file, as more than one permutation may use the same argument class.
95 */
96 void writeJavaArgumentClass(bool scalar, set<string>* javaGeneratedArgumentClasses) const;
97
98 // Generate the Check* method that invokes the script and calls the verifier.
99 void writeJavaCheckMethod(bool generateCallToVerifier) const;
100
101 // Generate code to define and randomly initialize the input allocation.
102 void writeJavaInputAllocationDefinition(const ParameterDefinition& param) const;
103
104 /* Generate code that instantiate an allocation of floats or integers and fills it with
105 * random data. This random data must be compatible with the specified type. This is
106 * used for the convert_* tests, as converting values that don't fit yield undefined results.
107 */
108 void writeJavaRandomCompatibleFloatAllocation(const string& dataType, const string& seed,
109 char vectorSize,
110 const NumericalType& compatibleType,
111 const NumericalType& generatedType) const;
112 void writeJavaRandomCompatibleIntegerAllocation(const string& dataType, const string& seed,
113 char vectorSize,
114 const NumericalType& compatibleType,
115 const NumericalType& generatedType) const;
116
117 // Generate code that defines an output allocation.
118 void writeJavaOutputAllocationDefinition(const ParameterDefinition& param) const;
119
120 /* Generate the code that verifies the results for RenderScript functions where each entry
121 * of a vector is evaluated independently. If verifierValidates is true, CoreMathVerifier
122 * does the actual validation instead of more commonly returning the range of acceptable values.
123 */
124 void writeJavaVerifyScalarMethod(bool verifierValidates) const;
125
126 /* Generate the code that verify the results for a RenderScript function where a vector
127 * is a point in n-dimensional space.
128 */
129 void writeJavaVerifyVectorMethod() const;
130
131 // Generate the method header of the verify function.
132 void writeJavaVerifyMethodHeader() const;
133
134 // Generate codes that copies the content of an allocation to an array.
135 void writeJavaArrayInitialization(const ParameterDefinition& p) const;
136
137 // Generate code that tests one value returned from the script.
138 void writeJavaTestAndSetValid(const ParameterDefinition& p, const string& argsIndex,
139 const string& actualIndex) const;
140 void writeJavaTestOneValue(const ParameterDefinition& p, const string& argsIndex,
141 const string& actualIndex) const;
142 // For test:vector cases, generate code that compares returned vector vs. expected value.
143 void writeJavaVectorComparison(const ParameterDefinition& p) const;
144
145 // Muliple functions that generates code to build the error message if an error is found.
146 void writeJavaAppendOutputToMessage(const ParameterDefinition& p, const string& argsIndex,
147 const string& actualIndex, bool verifierValidates) const;
148 void writeJavaAppendInputToMessage(const ParameterDefinition& p, const string& actual) const;
149 void writeJavaAppendNewLineToMessage() const;
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700150 void writeJavaAppendVectorInputToMessage(const ParameterDefinition& p) const;
151 void writeJavaAppendVectorOutputToMessage(const ParameterDefinition& p) const;
152
153 // Generate the set of instructions to call the script.
154 void writeJavaCallToRs(bool relaxed, bool generateCallToVerifier) const;
155
156 // Write an allocation definition if not already emitted in the .rs file.
157 void writeRsAllocationDefinition(const ParameterDefinition& param,
158 set<string>* rsAllocationsGenerated) const;
159
160public:
161 /* NOTE: We keep pointers to the permutation and the files. This object should not
162 * outlive the arguments.
163 */
164 PermutationWriter(FunctionPermutation& permutation, GeneratedFile* rsFile,
165 GeneratedFile* javaFile);
166 string getJavaCheckMethodName() const { return mJavaCheckMethodName; }
167
168 // Write the script test function for this permutation.
169 void writeRsSection(set<string>* rsAllocationsGenerated) const;
170 // Write the section of the Java code that calls the script and validates the results
171 void writeJavaSection(set<string>* javaGeneratedArgumentClasses) const;
172};
173
174PermutationWriter::PermutationWriter(FunctionPermutation& permutation, GeneratedFile* rsFile,
175 GeneratedFile* javaFile)
176 : mPermutation(permutation),
177 mRs(rsFile),
178 mJava(javaFile),
179 mReturnParam(nullptr),
180 mFirstInputParam(nullptr) {
181 mRsKernelName = "test" + capitalize(permutation.getName());
182
183 mJavaArgumentsClassName = "Arguments";
184 mJavaArgumentsNClassName = "Arguments";
185 const string trunk = capitalize(permutation.getNameTrunk());
186 mJavaCheckMethodName = "check" + trunk;
187 mJavaVerifyMethodName = "verifyResults" + trunk;
188
189 for (auto p : permutation.getParams()) {
190 mAllInputsAndOutputs.push_back(p);
191 if (mFirstInputParam == nullptr && !p->isOutParameter) {
192 mFirstInputParam = p;
193 }
194 }
195 mReturnParam = permutation.getReturn();
196 if (mReturnParam) {
197 mAllInputsAndOutputs.push_back(mReturnParam);
198 }
199
200 for (auto p : mAllInputsAndOutputs) {
201 const string capitalizedRsType = capitalize(p->rsType);
202 const string capitalizedBaseType = capitalize(p->rsBaseType);
203 mRsKernelName += capitalizedRsType;
204 mJavaArgumentsClassName += capitalizedBaseType;
205 mJavaArgumentsNClassName += capitalizedBaseType;
206 if (p->mVectorSize != "1") {
207 mJavaArgumentsNClassName += "N";
208 }
209 mJavaCheckMethodName += capitalizedRsType;
210 mJavaVerifyMethodName += capitalizedRsType;
211 }
212 mJavaVerifierComputeMethodName = "compute" + trunk;
213 mJavaVerifierVerifyMethodName = "verify" + trunk;
214}
215
216void PermutationWriter::writeJavaSection(set<string>* javaGeneratedArgumentClasses) const {
217 // By default, we test the results using item by item comparison.
218 const string test = mPermutation.getTest();
219 if (test == "scalar" || test == "limited") {
220 writeJavaArgumentClass(true, javaGeneratedArgumentClasses);
221 writeJavaCheckMethod(true);
222 writeJavaVerifyScalarMethod(false);
223 } else if (test == "custom") {
224 writeJavaArgumentClass(true, javaGeneratedArgumentClasses);
225 writeJavaCheckMethod(true);
226 writeJavaVerifyScalarMethod(true);
227 } else if (test == "vector") {
228 writeJavaArgumentClass(false, javaGeneratedArgumentClasses);
229 writeJavaCheckMethod(true);
230 writeJavaVerifyVectorMethod();
231 } else if (test == "noverify") {
232 writeJavaCheckMethod(false);
233 }
234}
235
236void PermutationWriter::writeJavaArgumentClass(bool scalar,
237 set<string>* javaGeneratedArgumentClasses) const {
238 string name;
239 if (scalar) {
240 name = mJavaArgumentsClassName;
241 } else {
242 name = mJavaArgumentsNClassName;
243 }
244
245 // Make sure we have not generated the argument class already.
246 if (!testAndSet(name, javaGeneratedArgumentClasses)) {
247 mJava->indent() << "public class " << name;
248 mJava->startBlock();
249
250 for (auto p : mAllInputsAndOutputs) {
251 mJava->indent() << "public ";
252 if (p->isOutParameter && p->isFloatType && mPermutation.getTest() != "custom") {
253 *mJava << "Target.Floaty";
254 } else {
255 *mJava << p->javaBaseType;
256 }
257 if (!scalar && p->mVectorSize != "1") {
258 *mJava << "[]";
259 }
260 *mJava << " " << p->variableName << ";\n";
261 }
262 mJava->endBlock();
263 *mJava << "\n";
264 }
265}
266
267void PermutationWriter::writeJavaCheckMethod(bool generateCallToVerifier) const {
268 mJava->indent() << "private void " << mJavaCheckMethodName << "()";
269 mJava->startBlock();
270
271 // Generate the input allocations and initialization.
272 for (auto p : mAllInputsAndOutputs) {
273 if (!p->isOutParameter) {
274 writeJavaInputAllocationDefinition(*p);
275 }
276 }
277 // Generate code to enforce ordering between two allocations if needed.
278 for (auto p : mAllInputsAndOutputs) {
279 if (!p->isOutParameter && !p->smallerParameter.empty()) {
280 string smallerAlloc = "in" + capitalize(p->smallerParameter);
281 mJava->indent() << "enforceOrdering(" << smallerAlloc << ", " << p->javaAllocName
282 << ");\n";
283 }
284 }
285
286 // Generate code to check the full and relaxed scripts.
287 writeJavaCallToRs(false, generateCallToVerifier);
288 writeJavaCallToRs(true, generateCallToVerifier);
289
290 mJava->endBlock();
291 *mJava << "\n";
292}
293
294void PermutationWriter::writeJavaInputAllocationDefinition(const ParameterDefinition& param) const {
295 string dataType;
296 char vectorSize;
297 convertToRsType(param.rsType, &dataType, &vectorSize);
298
299 const string seed = hashString(mJavaCheckMethodName + param.javaAllocName);
300 mJava->indent() << "Allocation " << param.javaAllocName << " = ";
301 if (param.compatibleTypeIndex >= 0) {
302 if (TYPES[param.typeIndex].kind == FLOATING_POINT) {
303 writeJavaRandomCompatibleFloatAllocation(dataType, seed, vectorSize,
304 TYPES[param.compatibleTypeIndex],
305 TYPES[param.typeIndex]);
306 } else {
307 writeJavaRandomCompatibleIntegerAllocation(dataType, seed, vectorSize,
308 TYPES[param.compatibleTypeIndex],
309 TYPES[param.typeIndex]);
310 }
311 } else if (!param.minValue.empty()) {
312 *mJava << "createRandomFloatAllocation(mRS, Element.DataType." << dataType << ", "
313 << vectorSize << ", " << seed << ", " << param.minValue << ", " << param.maxValue
314 << ")";
315 } else {
316 /* TODO Instead of passing always false, check whether we are doing a limited test.
317 * Use instead: (mPermutation.getTest() == "limited" ? "false" : "true")
318 */
319 *mJava << "createRandomAllocation(mRS, Element.DataType." << dataType << ", " << vectorSize
320 << ", " << seed << ", false)";
321 }
322 *mJava << ";\n";
323}
324
325void PermutationWriter::writeJavaRandomCompatibleFloatAllocation(
326 const string& dataType, const string& seed, char vectorSize,
327 const NumericalType& compatibleType, const NumericalType& generatedType) const {
328 *mJava << "createRandomFloatAllocation"
329 << "(mRS, Element.DataType." << dataType << ", " << vectorSize << ", " << seed << ", ";
330 double minValue = 0.0;
331 double maxValue = 0.0;
332 switch (compatibleType.kind) {
333 case FLOATING_POINT: {
334 // We're generating floating point values. We just worry about the exponent.
335 // Subtract 1 for the exponent sign.
336 int bits = min(compatibleType.exponentBits, generatedType.exponentBits) - 1;
337 maxValue = ldexp(0.95, (1 << bits) - 1);
338 minValue = -maxValue;
339 break;
340 }
341 case UNSIGNED_INTEGER:
342 maxValue = maxDoubleForInteger(compatibleType.significantBits,
343 generatedType.significantBits);
344 minValue = 0.0;
345 break;
346 case SIGNED_INTEGER:
347 maxValue = maxDoubleForInteger(compatibleType.significantBits,
348 generatedType.significantBits);
349 minValue = -maxValue - 1.0;
350 break;
351 }
352 *mJava << scientific << std::setprecision(19);
353 *mJava << minValue << ", " << maxValue << ")";
354 mJava->unsetf(ios_base::floatfield);
355}
356
357void PermutationWriter::writeJavaRandomCompatibleIntegerAllocation(
358 const string& dataType, const string& seed, char vectorSize,
359 const NumericalType& compatibleType, const NumericalType& generatedType) const {
360 *mJava << "createRandomIntegerAllocation"
361 << "(mRS, Element.DataType." << dataType << ", " << vectorSize << ", " << seed << ", ";
362
363 if (compatibleType.kind == FLOATING_POINT) {
364 // Currently, all floating points can take any number we generate.
365 bool isSigned = generatedType.kind == SIGNED_INTEGER;
366 *mJava << (isSigned ? "true" : "false") << ", " << generatedType.significantBits;
367 } else {
368 bool isSigned =
369 compatibleType.kind == SIGNED_INTEGER && generatedType.kind == SIGNED_INTEGER;
370 *mJava << (isSigned ? "true" : "false") << ", "
371 << min(compatibleType.significantBits, generatedType.significantBits);
372 }
373 *mJava << ")";
374}
375
376void PermutationWriter::writeJavaOutputAllocationDefinition(
377 const ParameterDefinition& param) const {
378 string dataType;
379 char vectorSize;
380 convertToRsType(param.rsType, &dataType, &vectorSize);
381 mJava->indent() << "Allocation " << param.javaAllocName << " = Allocation.createSized(mRS, "
382 << "getElement(mRS, Element.DataType." << dataType << ", " << vectorSize
383 << "), INPUTSIZE);\n";
384}
385
386void PermutationWriter::writeJavaVerifyScalarMethod(bool verifierValidates) const {
387 writeJavaVerifyMethodHeader();
388 mJava->startBlock();
389
390 string vectorSize = "1";
391 for (auto p : mAllInputsAndOutputs) {
392 writeJavaArrayInitialization(*p);
393 if (p->mVectorSize != "1" && p->mVectorSize != vectorSize) {
394 if (vectorSize == "1") {
395 vectorSize = p->mVectorSize;
396 } else {
397 cerr << "Error. Had vector " << vectorSize << " and " << p->mVectorSize << "\n";
398 }
399 }
400 }
401
402 mJava->indent() << "for (int i = 0; i < INPUTSIZE; i++)";
403 mJava->startBlock();
404
405 mJava->indent() << "for (int j = 0; j < " << vectorSize << " ; j++)";
406 mJava->startBlock();
407
408 mJava->indent() << "// Extract the inputs.\n";
409 mJava->indent() << mJavaArgumentsClassName << " args = new " << mJavaArgumentsClassName
410 << "();\n";
411 for (auto p : mAllInputsAndOutputs) {
412 if (!p->isOutParameter) {
413 mJava->indent() << "args." << p->variableName << " = " << p->javaArrayName << "[i";
414 if (p->vectorWidth != "1") {
415 *mJava << " * " << p->vectorWidth << " + j";
416 }
417 *mJava << "];\n";
418 }
419 }
420 const bool hasFloat = mPermutation.hasFloatAnswers();
421 if (verifierValidates) {
422 mJava->indent() << "// Extract the outputs.\n";
423 for (auto p : mAllInputsAndOutputs) {
424 if (p->isOutParameter) {
425 mJava->indent() << "args." << p->variableName << " = " << p->javaArrayName
Jean-Luc Brouillet49736b32015-04-14 14:23:48 -0700426 << "[i * " << p->vectorWidth << " + j];\n";
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700427 }
428 }
429 mJava->indent() << "// Ask the CoreMathVerifier to validate.\n";
430 if (hasFloat) {
431 mJava->indent() << "Target target = new Target(relaxed);\n";
432 }
433 mJava->indent() << "String errorMessage = CoreMathVerifier."
434 << mJavaVerifierVerifyMethodName << "(args";
435 if (hasFloat) {
436 *mJava << ", target";
437 }
438 *mJava << ");\n";
439 mJava->indent() << "boolean valid = errorMessage == null;\n";
440 } else {
441 mJava->indent() << "// Figure out what the outputs should have been.\n";
442 if (hasFloat) {
443 mJava->indent() << "Target target = new Target(relaxed);\n";
444 }
445 mJava->indent() << "CoreMathVerifier." << mJavaVerifierComputeMethodName << "(args";
446 if (hasFloat) {
447 *mJava << ", target";
448 }
449 *mJava << ");\n";
450 mJava->indent() << "// Validate the outputs.\n";
451 mJava->indent() << "boolean valid = true;\n";
452 for (auto p : mAllInputsAndOutputs) {
453 if (p->isOutParameter) {
454 writeJavaTestAndSetValid(*p, "", "[i * " + p->vectorWidth + " + j]");
455 }
456 }
457 }
458
459 mJava->indent() << "if (!valid)";
460 mJava->startBlock();
461
462 mJava->indent() << "StringBuilder message = new StringBuilder();\n";
463 for (auto p : mAllInputsAndOutputs) {
464 if (p->isOutParameter) {
465 writeJavaAppendOutputToMessage(*p, "", "[i * " + p->vectorWidth + " + j]",
466 verifierValidates);
467 } else {
468 writeJavaAppendInputToMessage(*p, "args." + p->variableName);
469 }
470 }
471 if (verifierValidates) {
472 mJava->indent() << "message.append(errorMessage);\n";
473 }
474
475 mJava->indent() << "assertTrue(\"Incorrect output for " << mJavaCheckMethodName << "\" +\n";
476 mJava->indentPlus()
477 << "(relaxed ? \"_relaxed\" : \"\") + \":\\n\" + message.toString(), valid);\n";
478
479 mJava->endBlock();
480 mJava->endBlock();
481 mJava->endBlock();
482 mJava->endBlock();
483 *mJava << "\n";
484}
485
486void PermutationWriter::writeJavaVerifyVectorMethod() const {
487 writeJavaVerifyMethodHeader();
488 mJava->startBlock();
489
490 for (auto p : mAllInputsAndOutputs) {
491 writeJavaArrayInitialization(*p);
492 }
493 mJava->indent() << "for (int i = 0; i < INPUTSIZE; i++)";
494 mJava->startBlock();
495
496 mJava->indent() << mJavaArgumentsNClassName << " args = new " << mJavaArgumentsNClassName
497 << "();\n";
498
499 mJava->indent() << "// Create the appropriate sized arrays in args\n";
500 for (auto p : mAllInputsAndOutputs) {
501 if (p->mVectorSize != "1") {
502 string type = p->javaBaseType;
503 if (p->isOutParameter && p->isFloatType) {
504 type = "Target.Floaty";
505 }
506 mJava->indent() << "args." << p->variableName << " = new " << type << "["
507 << p->mVectorSize << "];\n";
508 }
509 }
510
511 mJava->indent() << "// Fill args with the input values\n";
512 for (auto p : mAllInputsAndOutputs) {
513 if (!p->isOutParameter) {
514 if (p->mVectorSize == "1") {
Jean-Luc Brouillet49736b32015-04-14 14:23:48 -0700515 mJava->indent() << "args." << p->variableName << " = " << p->javaArrayName << "[i]"
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700516 << ";\n";
517 } else {
518 mJava->indent() << "for (int j = 0; j < " << p->mVectorSize << " ; j++)";
519 mJava->startBlock();
Jean-Luc Brouillet49736b32015-04-14 14:23:48 -0700520 mJava->indent() << "args." << p->variableName << "[j] = "
521 << p->javaArrayName << "[i * " << p->vectorWidth << " + j]"
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700522 << ";\n";
523 mJava->endBlock();
524 }
525 }
526 }
527 mJava->indent() << "Target target = new Target(relaxed);\n";
528 mJava->indent() << "CoreMathVerifier." << mJavaVerifierComputeMethodName
529 << "(args, target);\n\n";
530
531 mJava->indent() << "// Compare the expected outputs to the actual values returned by RS.\n";
532 mJava->indent() << "boolean valid = true;\n";
533 for (auto p : mAllInputsAndOutputs) {
534 if (p->isOutParameter) {
535 writeJavaVectorComparison(*p);
536 }
537 }
538
539 mJava->indent() << "if (!valid)";
540 mJava->startBlock();
541
542 mJava->indent() << "StringBuilder message = new StringBuilder();\n";
543 for (auto p : mAllInputsAndOutputs) {
544 if (p->isOutParameter) {
545 writeJavaAppendVectorOutputToMessage(*p);
546 } else {
547 writeJavaAppendVectorInputToMessage(*p);
548 }
549 }
550
551 mJava->indent() << "assertTrue(\"Incorrect output for " << mJavaCheckMethodName << "\" +\n";
552 mJava->indentPlus()
553 << "(relaxed ? \"_relaxed\" : \"\") + \":\\n\" + message.toString(), valid);\n";
554
555 mJava->endBlock();
556 mJava->endBlock();
557 mJava->endBlock();
558 *mJava << "\n";
559}
560
561void PermutationWriter::writeJavaVerifyMethodHeader() const {
562 mJava->indent() << "private void " << mJavaVerifyMethodName << "(";
563 for (auto p : mAllInputsAndOutputs) {
564 *mJava << "Allocation " << p->javaAllocName << ", ";
565 }
566 *mJava << "boolean relaxed)";
567}
568
569void PermutationWriter::writeJavaArrayInitialization(const ParameterDefinition& p) const {
570 mJava->indent() << p.javaBaseType << "[] " << p.javaArrayName << " = new " << p.javaBaseType
571 << "[INPUTSIZE * " << p.vectorWidth << "];\n";
572 mJava->indent() << p.javaAllocName << ".copyTo(" << p.javaArrayName << ");\n";
573}
574
575void PermutationWriter::writeJavaTestAndSetValid(const ParameterDefinition& p,
576 const string& argsIndex,
577 const string& actualIndex) const {
578 writeJavaTestOneValue(p, argsIndex, actualIndex);
579 mJava->startBlock();
580 mJava->indent() << "valid = false;\n";
581 mJava->endBlock();
582}
583
584void PermutationWriter::writeJavaTestOneValue(const ParameterDefinition& p, const string& argsIndex,
585 const string& actualIndex) const {
586 mJava->indent() << "if (";
587 if (p.isFloatType) {
588 *mJava << "!args." << p.variableName << argsIndex << ".couldBe(" << p.javaArrayName
589 << actualIndex;
590 const string s = mPermutation.getPrecisionLimit();
591 if (!s.empty()) {
592 *mJava << ", " << s;
593 }
594 *mJava << ")";
595 } else {
596 *mJava << "args." << p.variableName << argsIndex << " != " << p.javaArrayName
597 << actualIndex;
598 }
599
600 if (p.undefinedIfOutIsNan && mReturnParam) {
601 *mJava << " && !args." << mReturnParam->variableName << argsIndex << ".isNaN()";
602 }
603 *mJava << ")";
604}
605
606void PermutationWriter::writeJavaVectorComparison(const ParameterDefinition& p) const {
607 if (p.mVectorSize == "1") {
608 writeJavaTestAndSetValid(p, "", "[i]");
609 } else {
610 mJava->indent() << "for (int j = 0; j < " << p.mVectorSize << " ; j++)";
611 mJava->startBlock();
612 writeJavaTestAndSetValid(p, "[j]", "[i * " + p.vectorWidth + " + j]");
613 mJava->endBlock();
614 }
615}
616
617void PermutationWriter::writeJavaAppendOutputToMessage(const ParameterDefinition& p,
618 const string& argsIndex,
619 const string& actualIndex,
620 bool verifierValidates) const {
621 if (verifierValidates) {
Jean-Luc Brouillet49736b32015-04-14 14:23:48 -0700622 mJava->indent() << "message.append(\"Output " << p.variableName << ": \");\n";
623 mJava->indent() << "appendVariableToMessage(message, args." << p.variableName << argsIndex
624 << ");\n";
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700625 writeJavaAppendNewLineToMessage();
626 } else {
Jean-Luc Brouillet49736b32015-04-14 14:23:48 -0700627 mJava->indent() << "message.append(\"Expected output " << p.variableName << ": \");\n";
628 mJava->indent() << "appendVariableToMessage(message, args." << p.variableName << argsIndex
629 << ");\n";
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700630 writeJavaAppendNewLineToMessage();
Jean-Luc Brouillet49736b32015-04-14 14:23:48 -0700631
632 mJava->indent() << "message.append(\"Actual output " << p.variableName << ": \");\n";
633 mJava->indent() << "appendVariableToMessage(message, " << p.javaArrayName << actualIndex
634 << ");\n";
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700635
636 writeJavaTestOneValue(p, argsIndex, actualIndex);
637 mJava->startBlock();
638 mJava->indent() << "message.append(\" FAIL\");\n";
639 mJava->endBlock();
640 writeJavaAppendNewLineToMessage();
641 }
642}
643
644void PermutationWriter::writeJavaAppendInputToMessage(const ParameterDefinition& p,
645 const string& actual) const {
Jean-Luc Brouillet49736b32015-04-14 14:23:48 -0700646 mJava->indent() << "message.append(\"Input " << p.variableName << ": \");\n";
647 mJava->indent() << "appendVariableToMessage(message, " << actual << ");\n";
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700648 writeJavaAppendNewLineToMessage();
649}
650
651void PermutationWriter::writeJavaAppendNewLineToMessage() const {
652 mJava->indent() << "message.append(\"\\n\");\n";
653}
654
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700655void PermutationWriter::writeJavaAppendVectorInputToMessage(const ParameterDefinition& p) const {
656 if (p.mVectorSize == "1") {
657 writeJavaAppendInputToMessage(p, p.javaArrayName + "[i]");
658 } else {
659 mJava->indent() << "for (int j = 0; j < " << p.mVectorSize << " ; j++)";
660 mJava->startBlock();
661 writeJavaAppendInputToMessage(p, p.javaArrayName + "[i * " + p.vectorWidth + " + j]");
662 mJava->endBlock();
663 }
664}
665
666void PermutationWriter::writeJavaAppendVectorOutputToMessage(const ParameterDefinition& p) const {
667 if (p.mVectorSize == "1") {
668 writeJavaAppendOutputToMessage(p, "", "[i]", false);
669 } else {
670 mJava->indent() << "for (int j = 0; j < " << p.mVectorSize << " ; j++)";
671 mJava->startBlock();
672 writeJavaAppendOutputToMessage(p, "[j]", "[i * " + p.vectorWidth + " + j]", false);
673 mJava->endBlock();
674 }
675}
676
677void PermutationWriter::writeJavaCallToRs(bool relaxed, bool generateCallToVerifier) const {
678 string script = "script";
679 if (relaxed) {
680 script += "Relaxed";
681 }
682
683 mJava->indent() << "try";
684 mJava->startBlock();
685
686 for (auto p : mAllInputsAndOutputs) {
687 if (p->isOutParameter) {
688 writeJavaOutputAllocationDefinition(*p);
689 }
690 }
691
692 for (auto p : mPermutation.getParams()) {
693 if (p != mFirstInputParam) {
694 mJava->indent() << script << ".set_" << p->rsAllocName << "(" << p->javaAllocName
695 << ");\n";
696 }
697 }
698
699 mJava->indent() << script << ".forEach_" << mRsKernelName << "(";
700 bool needComma = false;
701 if (mFirstInputParam) {
702 *mJava << mFirstInputParam->javaAllocName;
703 needComma = true;
704 }
705 if (mReturnParam) {
706 if (needComma) {
707 *mJava << ", ";
708 }
709 *mJava << mReturnParam->variableName << ");\n";
710 }
711
712 if (generateCallToVerifier) {
713 mJava->indent() << mJavaVerifyMethodName << "(";
714 for (auto p : mAllInputsAndOutputs) {
715 *mJava << p->variableName << ", ";
716 }
717
718 if (relaxed) {
719 *mJava << "true";
720 } else {
721 *mJava << "false";
722 }
723 *mJava << ");\n";
724 }
725 mJava->decreaseIndent();
726 mJava->indent() << "} catch (Exception e) {\n";
727 mJava->increaseIndent();
728 mJava->indent() << "throw new RSRuntimeException(\"RenderScript. Can't invoke forEach_"
729 << mRsKernelName << ": \" + e.toString());\n";
730 mJava->endBlock();
731}
732
733/* Write the section of the .rs file for this permutation.
734 *
735 * We communicate the extra input and output parameters via global allocations.
736 * For example, if we have a function that takes three arguments, two for input
737 * and one for output:
738 *
739 * start:
740 * name: gamn
741 * ret: float3
742 * arg: float3 a
743 * arg: int b
744 * arg: float3 *c
745 * end:
746 *
747 * We'll produce:
748 *
749 * rs_allocation gAllocInB;
750 * rs_allocation gAllocOutC;
751 *
752 * float3 __attribute__((kernel)) test_gamn_float3_int_float3(float3 inA, unsigned int x) {
753 * int inB;
754 * float3 outC;
755 * float2 out;
756 * inB = rsGetElementAt_int(gAllocInB, x);
757 * out = gamn(a, in_b, &outC);
758 * rsSetElementAt_float4(gAllocOutC, &outC, x);
759 * return out;
760 * }
761 *
762 * We avoid re-using x and y from the definition because these have reserved
763 * meanings in a .rs file.
764 */
765void PermutationWriter::writeRsSection(set<string>* rsAllocationsGenerated) const {
766 // Write the allocation declarations we'll need.
767 for (auto p : mPermutation.getParams()) {
768 // Don't need allocation for one input and one return value.
769 if (p != mFirstInputParam) {
770 writeRsAllocationDefinition(*p, rsAllocationsGenerated);
771 }
772 }
773 *mRs << "\n";
774
775 // Write the function header.
776 if (mReturnParam) {
777 *mRs << mReturnParam->rsType;
778 } else {
779 *mRs << "void";
780 }
781 *mRs << " __attribute__((kernel)) " << mRsKernelName;
782 *mRs << "(";
783 bool needComma = false;
784 if (mFirstInputParam) {
785 *mRs << mFirstInputParam->rsType << " " << mFirstInputParam->variableName;
786 needComma = true;
787 }
788 if (mPermutation.getOutputCount() > 1 || mPermutation.getInputCount() > 1) {
789 if (needComma) {
790 *mRs << ", ";
791 }
792 *mRs << "unsigned int x";
793 }
794 *mRs << ")";
795 mRs->startBlock();
796
797 // Write the local variable declarations and initializations.
798 for (auto p : mPermutation.getParams()) {
799 if (p == mFirstInputParam) {
800 continue;
801 }
802 mRs->indent() << p->rsType << " " << p->variableName;
803 if (p->isOutParameter) {
804 *mRs << " = 0;\n";
805 } else {
806 *mRs << " = rsGetElementAt_" << p->rsType << "(" << p->rsAllocName << ", x);\n";
807 }
808 }
809
810 // Write the function call.
811 if (mReturnParam) {
812 if (mPermutation.getOutputCount() > 1) {
813 mRs->indent() << mReturnParam->rsType << " " << mReturnParam->variableName << " = ";
814 } else {
815 mRs->indent() << "return ";
816 }
817 }
818 *mRs << mPermutation.getName() << "(";
819 needComma = false;
820 for (auto p : mPermutation.getParams()) {
821 if (needComma) {
822 *mRs << ", ";
823 }
824 if (p->isOutParameter) {
825 *mRs << "&";
826 }
827 *mRs << p->variableName;
828 needComma = true;
829 }
830 *mRs << ");\n";
831
832 if (mPermutation.getOutputCount() > 1) {
833 // Write setting the extra out parameters into the allocations.
834 for (auto p : mPermutation.getParams()) {
835 if (p->isOutParameter) {
836 mRs->indent() << "rsSetElementAt_" << p->rsType << "(" << p->rsAllocName << ", ";
837 // Check if we need to use '&' for this type of argument.
838 char lastChar = p->variableName.back();
839 if (lastChar >= '0' && lastChar <= '9') {
840 *mRs << "&";
841 }
842 *mRs << p->variableName << ", x);\n";
843 }
844 }
845 if (mReturnParam) {
846 mRs->indent() << "return " << mReturnParam->variableName << ";\n";
847 }
848 }
849 mRs->endBlock();
850}
851
852void PermutationWriter::writeRsAllocationDefinition(const ParameterDefinition& param,
853 set<string>* rsAllocationsGenerated) const {
854 if (!testAndSet(param.rsAllocName, rsAllocationsGenerated)) {
855 *mRs << "rs_allocation " << param.rsAllocName << ";\n";
856 }
857}
858
859// Open the mJavaFile and writes the header.
Jean-Luc Brouillet62e09932015-03-22 11:14:07 -0700860static bool startJavaFile(GeneratedFile* file, const Function& function, const string& directory,
861 const string& testName, const string& relaxedTestName) {
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700862 const string fileName = testName + ".java";
Jean-Luc Brouillet62e09932015-03-22 11:14:07 -0700863 if (!file->start(directory, fileName)) {
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700864 return false;
865 }
866 file->writeNotices();
867
868 *file << "package android.renderscript.cts;\n\n";
869
870 *file << "import android.renderscript.Allocation;\n";
871 *file << "import android.renderscript.RSRuntimeException;\n";
872 *file << "import android.renderscript.Element;\n\n";
873
874 *file << "public class " << testName << " extends RSBaseCompute";
875 file->startBlock(); // The corresponding endBlock() is in finishJavaFile()
876 *file << "\n";
877
878 file->indent() << "private ScriptC_" << testName << " script;\n";
879 file->indent() << "private ScriptC_" << relaxedTestName << " scriptRelaxed;\n\n";
880
881 file->indent() << "@Override\n";
882 file->indent() << "protected void setUp() throws Exception";
883 file->startBlock();
884
885 file->indent() << "super.setUp();\n";
886 file->indent() << "script = new ScriptC_" << testName << "(mRS);\n";
887 file->indent() << "scriptRelaxed = new ScriptC_" << relaxedTestName << "(mRS);\n";
888
889 file->endBlock();
890 *file << "\n";
891 return true;
892}
893
894// Write the test method that calls all the generated Check methods.
895static void finishJavaFile(GeneratedFile* file, const Function& function,
896 const vector<string>& javaCheckMethods) {
897 file->indent() << "public void test" << function.getCapitalizedName() << "()";
898 file->startBlock();
899 for (auto m : javaCheckMethods) {
900 file->indent() << m << "();\n";
901 }
902 file->endBlock();
903
904 file->endBlock();
905}
906
907// Open the script file and write its header.
Jean-Luc Brouillet62e09932015-03-22 11:14:07 -0700908static bool startRsFile(GeneratedFile* file, const Function& function, const string& directory,
909 const string& testName) {
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700910 string fileName = testName + ".rs";
Jean-Luc Brouillet62e09932015-03-22 11:14:07 -0700911 if (!file->start(directory, fileName)) {
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700912 return false;
913 }
914 file->writeNotices();
915
916 *file << "#pragma version(1)\n";
917 *file << "#pragma rs java_package_name(android.renderscript.cts)\n\n";
918 return true;
919}
920
921// Write the entire *Relaxed.rs test file, as it only depends on the name.
Jean-Luc Brouillet62e09932015-03-22 11:14:07 -0700922static bool writeRelaxedRsFile(const Function& function, const string& directory,
923 const string& testName, const string& relaxedTestName) {
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700924 string name = relaxedTestName + ".rs";
925
926 GeneratedFile file;
Jean-Luc Brouillet62e09932015-03-22 11:14:07 -0700927 if (!file.start(directory, name)) {
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700928 return false;
929 }
930 file.writeNotices();
931
932 file << "#include \"" << testName << ".rs\"\n";
933 file << "#pragma rs_fp_relaxed\n";
934 file.close();
935 return true;
936}
937
938/* Write the .java and the two .rs test files. versionOfTestFiles is used to restrict which API
939 * to test.
940 */
Jean-Luc Brouillet62e09932015-03-22 11:14:07 -0700941static bool writeTestFilesForFunction(const Function& function, const string& directory,
942 int versionOfTestFiles) {
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700943 // Avoid creating empty files if we're not testing this function.
944 if (!needTestFiles(function, versionOfTestFiles)) {
945 return true;
946 }
947
Jean-Luc Brouillet62e09932015-03-22 11:14:07 -0700948 const string testName = "Test" + function.getCapitalizedName();
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700949 const string relaxedTestName = testName + "Relaxed";
950
Jean-Luc Brouillet62e09932015-03-22 11:14:07 -0700951 if (!writeRelaxedRsFile(function, directory, testName, relaxedTestName)) {
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700952 return false;
953 }
954
955 GeneratedFile rsFile; // The Renderscript test file we're generating.
956 GeneratedFile javaFile; // The Jave test file we're generating.
Jean-Luc Brouillet62e09932015-03-22 11:14:07 -0700957 if (!startRsFile(&rsFile, function, directory, testName)) {
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700958 return false;
959 }
960
Jean-Luc Brouillet62e09932015-03-22 11:14:07 -0700961 if (!startJavaFile(&javaFile, function, directory, testName, relaxedTestName)) {
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700962 return false;
963 }
964
965 /* We keep track of the allocations generated in the .rs file and the argument classes defined
966 * in the Java file, as we share these between the functions created for each specification.
967 */
968 set<string> rsAllocationsGenerated;
969 set<string> javaGeneratedArgumentClasses;
970 // Lines of Java code to invoke the check methods.
971 vector<string> javaCheckMethods;
972
973 for (auto spec : function.getSpecifications()) {
974 if (spec->hasTests(versionOfTestFiles)) {
975 for (auto permutation : spec->getPermutations()) {
976 PermutationWriter w(*permutation, &rsFile, &javaFile);
977 w.writeRsSection(&rsAllocationsGenerated);
978 w.writeJavaSection(&javaGeneratedArgumentClasses);
979
980 // Store the check method to be called.
981 javaCheckMethods.push_back(w.getJavaCheckMethodName());
982 }
983 }
984 }
985
986 finishJavaFile(&javaFile, function, javaCheckMethods);
987 // There's no work to wrap-up in the .rs file.
988
989 rsFile.close();
990 javaFile.close();
991 return true;
992}
993
Jean-Luc Brouillet66fea242015-04-09 16:47:59 -0700994bool generateTestFiles(const string& directory, int versionOfTestFiles) {
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700995 bool success = true;
Jean-Luc Brouillet7c078542015-03-23 16:16:08 -0700996 for (auto f : systemSpecification.getFunctions()) {
997 if (!writeTestFilesForFunction(*f.second, directory, versionOfTestFiles)) {
998 success = false;
Jean-Luc Brouilletc5184e22015-03-13 13:51:24 -0700999 }
1000 }
1001 return success;
1002}