validate.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. // Copyright (c) 2015-2016 The Khronos Group Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "validate.h"
  15. #include <cassert>
  16. #include <cstdio>
  17. #include <algorithm>
  18. #include <functional>
  19. #include <iterator>
  20. #include <memory>
  21. #include <sstream>
  22. #include <string>
  23. #include <vector>
  24. #include "binary.h"
  25. #include "diagnostic.h"
  26. #include "enum_string_mapping.h"
  27. #include "extensions.h"
  28. #include "instruction.h"
  29. #include "opcode.h"
  30. #include "operand.h"
  31. #include "spirv-tools/libspirv.h"
  32. #include "spirv_constant.h"
  33. #include "spirv_endian.h"
  34. #include "spirv_target_env.h"
  35. #include "spirv_validator_options.h"
  36. #include "val/construct.h"
  37. #include "val/function.h"
  38. #include "val/validation_state.h"
  39. using std::function;
  40. using std::ostream_iterator;
  41. using std::string;
  42. using std::stringstream;
  43. using std::transform;
  44. using std::vector;
  45. using std::placeholders::_1;
  46. using libspirv::CfgPass;
  47. using libspirv::DataRulesPass;
  48. using libspirv::Extension;
  49. using libspirv::IdPass;
  50. using libspirv::InstructionPass;
  51. using libspirv::LiteralsPass;
  52. using libspirv::ModuleLayoutPass;
  53. using libspirv::ValidationState_t;
  54. spv_result_t spvValidateIDs(const spv_instruction_t* pInsts,
  55. const uint64_t count,
  56. const ValidationState_t& state,
  57. spv_position position) {
  58. position->index = SPV_INDEX_INSTRUCTION;
  59. if (auto error = spvValidateInstructionIDs(pInsts, count, state, position))
  60. return error;
  61. return SPV_SUCCESS;
  62. }
  63. namespace {
  64. // TODO(umar): Validate header
  65. // TODO(umar): The binary parser validates the magic word, and the length of the
  66. // header, but nothing else.
  67. spv_result_t setHeader(void* user_data, spv_endianness_t endian, uint32_t magic,
  68. uint32_t version, uint32_t generator, uint32_t id_bound,
  69. uint32_t reserved) {
  70. // Record the ID bound so that the validator can ensure no ID is out of bound.
  71. ValidationState_t& _ = *(reinterpret_cast<ValidationState_t*>(user_data));
  72. _.setIdBound(id_bound);
  73. (void)endian;
  74. (void)magic;
  75. (void)version;
  76. (void)generator;
  77. (void)id_bound;
  78. (void)reserved;
  79. return SPV_SUCCESS;
  80. }
  81. // Improves diagnostic messages by collecting names of IDs
  82. // NOTE: This function returns void and is not involved in validation
  83. void DebugInstructionPass(ValidationState_t& _,
  84. const spv_parsed_instruction_t* inst) {
  85. switch (inst->opcode) {
  86. case SpvOpName: {
  87. const uint32_t target = *(inst->words + inst->operands[0].offset);
  88. const char* str =
  89. reinterpret_cast<const char*>(inst->words + inst->operands[1].offset);
  90. _.AssignNameToId(target, str);
  91. } break;
  92. case SpvOpMemberName: {
  93. const uint32_t target = *(inst->words + inst->operands[0].offset);
  94. const char* str =
  95. reinterpret_cast<const char*>(inst->words + inst->operands[2].offset);
  96. _.AssignNameToId(target, str);
  97. } break;
  98. case SpvOpSourceContinued:
  99. case SpvOpSource:
  100. case SpvOpSourceExtension:
  101. case SpvOpString:
  102. case SpvOpLine:
  103. case SpvOpNoLine:
  104. default:
  105. break;
  106. }
  107. }
  108. // Parses OpExtension instruction and registers extension.
  109. void RegisterExtension(ValidationState_t& _,
  110. const spv_parsed_instruction_t* inst) {
  111. const std::string extension_str = libspirv::GetExtensionString(inst);
  112. Extension extension;
  113. if (!GetExtensionFromString(extension_str.c_str(), &extension)) {
  114. // The error will be logged in the ProcessInstruction pass.
  115. return;
  116. }
  117. _.RegisterExtension(extension);
  118. }
  119. // Parses the beginning of the module searching for OpExtension instructions.
  120. // Registers extensions if recognized. Returns SPV_REQUESTED_TERMINATION
  121. // once an instruction which is not SpvOpCapability and SpvOpExtension is
  122. // encountered. According to the SPIR-V spec extensions are declared after
  123. // capabilities and before everything else.
  124. spv_result_t ProcessExtensions(void* user_data,
  125. const spv_parsed_instruction_t* inst) {
  126. const SpvOp opcode = static_cast<SpvOp>(inst->opcode);
  127. if (opcode == SpvOpCapability) return SPV_SUCCESS;
  128. if (opcode == SpvOpExtension) {
  129. ValidationState_t& _ = *(reinterpret_cast<ValidationState_t*>(user_data));
  130. RegisterExtension(_, inst);
  131. return SPV_SUCCESS;
  132. }
  133. // OpExtension block is finished, requesting termination.
  134. return SPV_REQUESTED_TERMINATION;
  135. }
  136. spv_result_t ProcessInstruction(void* user_data,
  137. const spv_parsed_instruction_t* inst) {
  138. ValidationState_t& _ = *(reinterpret_cast<ValidationState_t*>(user_data));
  139. _.increment_instruction_count();
  140. if (static_cast<SpvOp>(inst->opcode) == SpvOpEntryPoint) {
  141. const auto entry_point = inst->words[2];
  142. const SpvExecutionModel execution_model = SpvExecutionModel(inst->words[1]);
  143. _.RegisterEntryPointId(entry_point, execution_model);
  144. // Operand 3 and later are the <id> of interfaces for the entry point.
  145. for (int i = 3; i < inst->num_operands; ++i) {
  146. _.RegisterInterfaceForEntryPoint(entry_point,
  147. inst->words[inst->operands[i].offset]);
  148. }
  149. }
  150. if (static_cast<SpvOp>(inst->opcode) == SpvOpFunctionCall) {
  151. _.AddFunctionCallTarget(inst->words[3]);
  152. }
  153. DebugInstructionPass(_, inst);
  154. if (auto error = CapabilityPass(_, inst)) return error;
  155. if (auto error = DataRulesPass(_, inst)) return error;
  156. if (auto error = IdPass(_, inst)) return error;
  157. if (auto error = ModuleLayoutPass(_, inst)) return error;
  158. if (auto error = CfgPass(_, inst)) return error;
  159. if (auto error = InstructionPass(_, inst)) return error;
  160. if (auto error = TypeUniquePass(_, inst)) return error;
  161. if (auto error = ArithmeticsPass(_, inst)) return error;
  162. if (auto error = CompositesPass(_, inst)) return error;
  163. if (auto error = ConversionPass(_, inst)) return error;
  164. if (auto error = DerivativesPass(_, inst)) return error;
  165. if (auto error = LogicalsPass(_, inst)) return error;
  166. if (auto error = BitwisePass(_, inst)) return error;
  167. if (auto error = ExtInstPass(_, inst)) return error;
  168. if (auto error = ImagePass(_, inst)) return error;
  169. if (auto error = AtomicsPass(_, inst)) return error;
  170. if (auto error = BarriersPass(_, inst)) return error;
  171. if (auto error = PrimitivesPass(_, inst)) return error;
  172. if (auto error = LiteralsPass(_, inst)) return error;
  173. return SPV_SUCCESS;
  174. }
  175. void printDot(const ValidationState_t& _, const libspirv::BasicBlock& other) {
  176. string block_string;
  177. if (other.successors()->empty()) {
  178. block_string += "end ";
  179. } else {
  180. for (auto block : *other.successors()) {
  181. block_string += _.getIdOrName(block->id()) + " ";
  182. }
  183. }
  184. printf("%10s -> {%s\b}\n", _.getIdOrName(other.id()).c_str(),
  185. block_string.c_str());
  186. }
  187. void PrintBlocks(ValidationState_t& _, libspirv::Function func) {
  188. assert(func.first_block());
  189. printf("%10s -> %s\n", _.getIdOrName(func.id()).c_str(),
  190. _.getIdOrName(func.first_block()->id()).c_str());
  191. for (const auto& block : func.ordered_blocks()) {
  192. printDot(_, *block);
  193. }
  194. }
  195. #ifdef __clang__
  196. #define UNUSED(func) [[gnu::unused]] func
  197. #elif defined(__GNUC__)
  198. #define UNUSED(func) \
  199. func __attribute__((unused)); \
  200. func
  201. #elif defined(_MSC_VER)
  202. #define UNUSED(func) func
  203. #endif
  204. UNUSED(void PrintDotGraph(ValidationState_t& _, libspirv::Function func)) {
  205. if (func.first_block()) {
  206. string func_name(_.getIdOrName(func.id()));
  207. printf("digraph %s {\n", func_name.c_str());
  208. PrintBlocks(_, func);
  209. printf("}\n");
  210. }
  211. }
  212. spv_result_t ValidateBinaryUsingContextAndValidationState(
  213. const spv_context_t& context, const uint32_t* words, const size_t num_words,
  214. spv_diagnostic* pDiagnostic, ValidationState_t* vstate) {
  215. auto binary = std::unique_ptr<spv_const_binary_t>(
  216. new spv_const_binary_t{words, num_words});
  217. spv_endianness_t endian;
  218. spv_position_t position = {};
  219. if (spvBinaryEndianness(binary.get(), &endian)) {
  220. return libspirv::DiagnosticStream(position, context.consumer,
  221. SPV_ERROR_INVALID_BINARY)
  222. << "Invalid SPIR-V magic number.";
  223. }
  224. spv_header_t header;
  225. if (spvBinaryHeaderGet(binary.get(), endian, &header)) {
  226. return libspirv::DiagnosticStream(position, context.consumer,
  227. SPV_ERROR_INVALID_BINARY)
  228. << "Invalid SPIR-V header.";
  229. }
  230. if (header.version > spvVersionForTargetEnv(context.target_env)) {
  231. return libspirv::DiagnosticStream(position, context.consumer,
  232. SPV_ERROR_WRONG_VERSION)
  233. << "Invalid SPIR-V binary version "
  234. << SPV_SPIRV_VERSION_MAJOR_PART(header.version) << "."
  235. << SPV_SPIRV_VERSION_MINOR_PART(header.version)
  236. << " for target environment "
  237. << spvTargetEnvDescription(context.target_env) << ".";
  238. }
  239. // Look for OpExtension instructions and register extensions.
  240. // Diagnostics if any will be produced in the next pass (ProcessInstruction).
  241. spvBinaryParse(&context, vstate, words, num_words,
  242. /* parsed_header = */ nullptr, ProcessExtensions,
  243. /* diagnostic = */ nullptr);
  244. // NOTE: Parse the module and perform inline validation checks. These
  245. // checks do not require the the knowledge of the whole module.
  246. if (auto error = spvBinaryParse(&context, vstate, words, num_words, setHeader,
  247. ProcessInstruction, pDiagnostic))
  248. return error;
  249. if (vstate->in_function_body())
  250. return vstate->diag(SPV_ERROR_INVALID_LAYOUT)
  251. << "Missing OpFunctionEnd at end of module.";
  252. // TODO(umar): Add validation checks which require the parsing of the entire
  253. // module. Use the information from the ProcessInstruction pass to make the
  254. // checks.
  255. if (vstate->unresolved_forward_id_count() > 0) {
  256. stringstream ss;
  257. vector<uint32_t> ids = vstate->UnresolvedForwardIds();
  258. transform(begin(ids), end(ids), ostream_iterator<string>(ss, " "),
  259. bind(&ValidationState_t::getIdName, std::ref(*vstate), _1));
  260. auto id_str = ss.str();
  261. return vstate->diag(SPV_ERROR_INVALID_ID)
  262. << "The following forward referenced IDs have not been defined:\n"
  263. << id_str.substr(0, id_str.size() - 1);
  264. }
  265. // Validate the preconditions involving adjacent instructions. e.g. SpvOpPhi
  266. // must only be preceeded by SpvOpLabel, SpvOpPhi, or SpvOpLine.
  267. if (auto error = ValidateAdjacency(*vstate)) return error;
  268. // CFG checks are performed after the binary has been parsed
  269. // and the CFGPass has collected information about the control flow
  270. if (auto error = PerformCfgChecks(*vstate)) return error;
  271. if (auto error = UpdateIdUse(*vstate)) return error;
  272. if (auto error = CheckIdDefinitionDominateUse(*vstate)) return error;
  273. if (auto error = ValidateDecorations(*vstate)) return error;
  274. // Entry point validation. Based on 2.16.1 (Universal Validation Rules) of the
  275. // SPIRV spec:
  276. // * There is at least one OpEntryPoint instruction, unless the Linkage
  277. // capability is being used.
  278. // * No function can be targeted by both an OpEntryPoint instruction and an
  279. // OpFunctionCall instruction.
  280. if (vstate->entry_points().empty() &&
  281. !vstate->HasCapability(SpvCapabilityLinkage)) {
  282. return vstate->diag(SPV_ERROR_INVALID_BINARY)
  283. << "No OpEntryPoint instruction was found. This is only allowed if "
  284. "the Linkage capability is being used.";
  285. }
  286. for (const auto& entry_point : vstate->entry_points()) {
  287. if (vstate->IsFunctionCallTarget(entry_point)) {
  288. return vstate->diag(SPV_ERROR_INVALID_BINARY)
  289. << "A function (" << entry_point
  290. << ") may not be targeted by both an OpEntryPoint instruction and "
  291. "an OpFunctionCall instruction.";
  292. }
  293. }
  294. // NOTE: Copy each instruction for easier processing
  295. std::vector<spv_instruction_t> instructions;
  296. // Expect average instruction length to be a bit over 2 words.
  297. instructions.reserve(binary->wordCount / 2);
  298. uint64_t index = SPV_INDEX_INSTRUCTION;
  299. while (index < binary->wordCount) {
  300. uint16_t wordCount;
  301. uint16_t opcode;
  302. spvOpcodeSplit(spvFixWord(binary->code[index], endian), &wordCount,
  303. &opcode);
  304. spv_instruction_t inst;
  305. spvInstructionCopy(&binary->code[index], static_cast<SpvOp>(opcode),
  306. wordCount, endian, &inst);
  307. instructions.emplace_back(std::move(inst));
  308. index += wordCount;
  309. }
  310. position.index = SPV_INDEX_INSTRUCTION;
  311. if (auto error = spvValidateIDs(instructions.data(), instructions.size(),
  312. *vstate, &position))
  313. return error;
  314. if (auto error = ValidateBuiltIns(*vstate)) return error;
  315. return SPV_SUCCESS;
  316. }
  317. } // anonymous namespace
  318. spv_result_t spvValidate(const spv_const_context context,
  319. const spv_const_binary binary,
  320. spv_diagnostic* pDiagnostic) {
  321. return spvValidateBinary(context, binary->code, binary->wordCount,
  322. pDiagnostic);
  323. }
  324. spv_result_t spvValidateBinary(const spv_const_context context,
  325. const uint32_t* words, const size_t num_words,
  326. spv_diagnostic* pDiagnostic) {
  327. spv_context_t hijack_context = *context;
  328. if (pDiagnostic) {
  329. *pDiagnostic = nullptr;
  330. libspirv::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
  331. }
  332. // This interface is used for default command line options.
  333. spv_validator_options default_options = spvValidatorOptionsCreate();
  334. // Create the ValidationState using the context and default options.
  335. ValidationState_t vstate(&hijack_context, default_options);
  336. spv_result_t result = ValidateBinaryUsingContextAndValidationState(
  337. hijack_context, words, num_words, pDiagnostic, &vstate);
  338. spvValidatorOptionsDestroy(default_options);
  339. return result;
  340. }
  341. spv_result_t spvValidateWithOptions(const spv_const_context context,
  342. spv_const_validator_options options,
  343. const spv_const_binary binary,
  344. spv_diagnostic* pDiagnostic) {
  345. spv_context_t hijack_context = *context;
  346. if (pDiagnostic) {
  347. *pDiagnostic = nullptr;
  348. libspirv::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
  349. }
  350. // Create the ValidationState using the context.
  351. ValidationState_t vstate(&hijack_context, options);
  352. return ValidateBinaryUsingContextAndValidationState(
  353. hijack_context, binary->code, binary->wordCount, pDiagnostic, &vstate);
  354. }
  355. namespace spvtools {
  356. spv_result_t ValidateBinaryAndKeepValidationState(
  357. const spv_const_context context, spv_const_validator_options options,
  358. const uint32_t* words, const size_t num_words, spv_diagnostic* pDiagnostic,
  359. std::unique_ptr<ValidationState_t>* vstate) {
  360. spv_context_t hijack_context = *context;
  361. if (pDiagnostic) {
  362. *pDiagnostic = nullptr;
  363. libspirv::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
  364. }
  365. vstate->reset(new ValidationState_t(&hijack_context, options));
  366. return ValidateBinaryUsingContextAndValidationState(
  367. hijack_context, words, num_words, pDiagnostic, vstate->get());
  368. }
  369. spv_result_t ValidateInstructionAndUpdateValidationState(
  370. ValidationState_t* vstate, const spv_parsed_instruction_t* inst) {
  371. return ProcessInstruction(vstate, inst);
  372. }
  373. } // namespace spvtools