HLSLOptions.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. //===--- HLSLOptions.cpp - Driver Options Table ---------------------------===//
  2. ///////////////////////////////////////////////////////////////////////////////
  3. // //
  4. // HLSLOptions.cpp //
  5. // Copyright (C) Microsoft Corporation. All rights reserved. //
  6. // This file is distributed under the University of Illinois Open Source //
  7. // License. See LICENSE.TXT for details. //
  8. // //
  9. ///////////////////////////////////////////////////////////////////////////////
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/Option/OptTable.h"
  12. #include "llvm/Option/Option.h"
  13. #include "llvm/Support/raw_ostream.h"
  14. #include "dxc/Support/Global.h"
  15. #include "dxc/Support/WinIncludes.h"
  16. #include "dxc/Support/HLSLOptions.h"
  17. #include "dxc/Support/Unicode.h"
  18. #include "dxc/Support/dxcapi.use.h"
  19. using namespace llvm::opt;
  20. using namespace dxc;
  21. using namespace hlsl;
  22. using namespace hlsl::options;
  23. #define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE;
  24. #include "dxc/Support/HLSLOptions.inc"
  25. #undef PREFIX
  26. static const OptTable::Info HlslInfoTable[] = {
  27. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  28. HELPTEXT, METAVAR) \
  29. { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, PARAM, \
  30. FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
  31. #include "dxc/Support/HLSLOptions.inc"
  32. #undef OPTION
  33. };
  34. namespace {
  35. class HlslOptTable : public OptTable {
  36. public:
  37. HlslOptTable()
  38. : OptTable(HlslInfoTable, llvm::array_lengthof(HlslInfoTable)) {}
  39. };
  40. }
  41. static HlslOptTable g_HlslOptTable;
  42. const OptTable * hlsl::options::getHlslOptTable() {
  43. return &g_HlslOptTable;
  44. }
  45. void DxcDefines::push_back(llvm::StringRef value) {
  46. // Skip empty defines.
  47. if (value.size() > 0) {
  48. DefineStrings.push_back(value);
  49. }
  50. }
  51. UINT32 DxcDefines::ComputeNumberOfWCharsNeededForDefines() {
  52. UINT32 wcharSize = 0;
  53. for (llvm::StringRef &S : DefineStrings) {
  54. DXASSERT(S.size() > 0,
  55. "else DxcDefines::push_back should not have added this");
  56. const int utf16Length = ::MultiByteToWideChar(
  57. CP_UTF8, MB_ERR_INVALID_CHARS, S.data(), S.size(), nullptr, 0);
  58. IFTARG(utf16Length != 0);
  59. wcharSize += utf16Length + 1; // adding null terminated character
  60. }
  61. return wcharSize;
  62. }
  63. void DxcDefines::BuildDefines() {
  64. // Calculate and prepare the size of the backing buffer.
  65. DXASSERT(DefineValues == nullptr, "else DxcDefines is already built");
  66. UINT32 wcharSize = ComputeNumberOfWCharsNeededForDefines();
  67. DefineValues = new wchar_t[wcharSize];
  68. DefineVector.resize(DefineStrings.size());
  69. // Build up the define structures while filling in the backing buffer.
  70. UINT32 remaining = wcharSize;
  71. LPWSTR pWriteCursor = DefineValues;
  72. for (size_t i = 0; i < DefineStrings.size(); ++i) {
  73. llvm::StringRef &S = DefineStrings[i];
  74. DxcDefine &D = DefineVector[i];
  75. const int utf16Length =
  76. ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, S.data(), S.size(),
  77. pWriteCursor, remaining);
  78. DXASSERT(utf16Length > 0,
  79. "else it should have failed during size calculation");
  80. LPWSTR pDefineEnd = pWriteCursor + utf16Length;
  81. D.Name = pWriteCursor;
  82. LPWSTR pEquals = std::find(pWriteCursor, pDefineEnd, L'=');
  83. if (pEquals == pDefineEnd) {
  84. D.Value = nullptr;
  85. } else {
  86. *pEquals = L'\0';
  87. D.Value = pEquals + 1;
  88. }
  89. // Advance past converted characters and include the null terminator.
  90. pWriteCursor += utf16Length;
  91. *pWriteCursor = L'\0';
  92. ++pWriteCursor;
  93. DXASSERT(pWriteCursor <= DefineValues + wcharSize,
  94. "else this function is calculating this incorrectly");
  95. remaining -= (utf16Length + 1);
  96. }
  97. }
  98. MainArgs::MainArgs(int argc, const wchar_t **argv, int skipArgCount) {
  99. if (argc > skipArgCount) {
  100. Utf8StringVector.reserve(argc - skipArgCount);
  101. Utf8CharPtrVector.reserve(argc - skipArgCount);
  102. for (int i = skipArgCount; i < argc; ++i) {
  103. Utf8StringVector.emplace_back(Unicode::UTF16ToUTF8StringOrThrow(argv[i]));
  104. Utf8CharPtrVector.push_back(Utf8StringVector.back().data());
  105. }
  106. }
  107. }
  108. MainArgs::MainArgs(llvm::ArrayRef<llvm::StringRef> args) {
  109. Utf8StringVector.reserve(args.size());
  110. Utf8CharPtrVector.reserve(args.size());
  111. for (llvm::StringRef str : args) {
  112. Utf8StringVector.emplace_back(str.str());
  113. Utf8CharPtrVector.push_back(Utf8StringVector.back().data());
  114. }
  115. }
  116. MainArgs& MainArgs::operator=(const MainArgs &other) {
  117. Utf8StringVector.clear();
  118. Utf8CharPtrVector.clear();
  119. for (const std::string &str : other.Utf8StringVector) {
  120. Utf8StringVector.emplace_back(str);
  121. Utf8CharPtrVector.push_back(Utf8StringVector.back().data());
  122. }
  123. return *this;
  124. }
  125. StringRefUtf16::StringRefUtf16(llvm::StringRef value) {
  126. if (!value.empty())
  127. m_value = Unicode::UTF8ToUTF16StringOrThrow(value.data());
  128. }
  129. namespace hlsl {
  130. namespace options {
  131. /// Reads all options from the given argument strings, populates opts, and
  132. /// validates reporting errors and warnings.
  133. int ReadDxcOpts(const OptTable *optionTable, unsigned flagsToInclude,
  134. const MainArgs &argStrings, DxcOpts &opts,
  135. llvm::raw_ostream &errors) {
  136. DXASSERT_NOMSG(optionTable != nullptr);
  137. unsigned missingArgIndex = 0, missingArgCount = 0;
  138. InputArgList Args = optionTable->ParseArgs(
  139. argStrings.getArrayRef(), missingArgIndex, missingArgCount, flagsToInclude);
  140. opts.ShowHelp = Args.hasFlag(OPT_help, OPT_INVALID, false);
  141. if (opts.ShowHelp) {
  142. return 0;
  143. }
  144. if (missingArgCount) {
  145. errors << "Argument to '" << Args.getArgString(missingArgIndex)
  146. << "' is missing.";
  147. return 1;
  148. }
  149. if (!Args.hasArg(hlsl::options::OPT_Qunused_arguments)) {
  150. for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
  151. errors << "Unknown argument: '" << A->getAsString(Args).c_str() << "'";
  152. return 1;
  153. }
  154. }
  155. // Add macros from the command line.
  156. for (const Arg *A : Args.filtered(OPT_D)) {
  157. opts.Defines.push_back(A->getValue());
  158. // If supporting OPT_U and included in filter, handle undefs.
  159. }
  160. opts.Defines.BuildDefines(); // Must be called after all defines are pushed back
  161. opts.ExternalLib = Args.getLastArgValue(OPT_external_lib);
  162. opts.ExternalFn = Args.getLastArgValue(OPT_external_fn);
  163. // Verify consistency for external library support.
  164. if (opts.ExternalLib.empty()) {
  165. if (!opts.ExternalFn.empty()) {
  166. errors << "External function cannot be specified without an external "
  167. "library name.";
  168. return 1;
  169. }
  170. }
  171. else {
  172. if (opts.ExternalFn.empty()) {
  173. errors << "External library name requires specifying an external "
  174. "function name.";
  175. return 1;
  176. }
  177. }
  178. DXASSERT(opts.ExternalLib.empty() == opts.ExternalFn.empty(),
  179. "else flow above is incorrect");
  180. opts.OutputWarnings = Args.hasFlag(OPT_no_warnings, OPT_INVALID, true);
  181. opts.EntryPoint = Args.getLastArgValue(OPT_entrypoint);
  182. // Entry point is required in arguments only for drivers; APIs take this through an argument.
  183. // The value should default to 'main', but we let the caller apply this policy.
  184. opts.TargetProfile = Args.getLastArgValue(OPT_target_profile);
  185. llvm::StringRef hlslVersion = Args.getLastArgValue(OPT_hlsl_version);
  186. if (hlslVersion.empty() || hlslVersion == "2016") {
  187. opts.HLSL2016 = true;
  188. }
  189. else if (hlslVersion == "2015") {
  190. opts.HLSL2016 = false;
  191. if (!(flagsToInclude & HlslFlags::ISenseOption)) {
  192. errors << "HLSL Version 2015 is only supported for language services";
  193. return 1;
  194. }
  195. }
  196. else {
  197. errors << "Unknown HLSL version";
  198. return 1;
  199. }
  200. opts.HLSL2015 = !opts.HLSL2016;
  201. // AssemblyCodeHex not supported (Fx)
  202. // OutputLibrary not supported (Fl)
  203. opts.AssemblyCode = Args.getLastArgValue(OPT_Fc);
  204. opts.DebugFile = Args.getLastArgValue(OPT_Fd);
  205. opts.ExtractRootSignatureFile = Args.getLastArgValue(OPT_extractrootsignature);
  206. opts.OutputObject = Args.getLastArgValue(OPT_Fo);
  207. opts.OutputHeader = Args.getLastArgValue(OPT_Fh);
  208. opts.OutputWarningsFile = Args.getLastArgValue(OPT_Fe);
  209. opts.UseColor = Args.hasFlag(OPT_Cc, OPT_INVALID);
  210. opts.UseInstructionNumbers = Args.hasFlag(OPT_Ni, OPT_INVALID);
  211. opts.UseInstructionByteOffsets = Args.hasFlag(OPT_No, OPT_INVALID);
  212. opts.UseHexLiterals = Args.hasFlag(OPT_Lx, OPT_INVALID);
  213. opts.Preprocess = Args.getLastArgValue(OPT_P);
  214. opts.AstDump = Args.hasFlag(OPT_ast_dump, OPT_INVALID, false);
  215. opts.CodeGenHighLevel = Args.hasFlag(OPT_fcgl, OPT_INVALID, false);
  216. opts.DebugInfo = Args.hasFlag(OPT__SLASH_Zi, OPT_INVALID, false);
  217. opts.VariableName = Args.getLastArgValue(OPT_Vn);
  218. opts.InputFile = Args.getLastArgValue(OPT_INPUT);
  219. opts.ForceRootSigVer = Args.getLastArgValue(OPT_force_rootsig_ver);
  220. if (!opts.ForceRootSigVer.empty() && opts.ForceRootSigVer != "rootsig_1_0" &&
  221. opts.ForceRootSigVer != "rootsig_1_1") {
  222. errors << "Unsupported value '" << opts.ForceRootSigVer
  223. << "' for root signature profile.";
  224. return 1;
  225. }
  226. opts.IEEEStrict = Args.hasFlag(OPT_Gis, OPT_INVALID, false);
  227. if (Arg *A = Args.getLastArg(OPT_O0, OPT_O1, OPT_O2, OPT_O3)) {
  228. if (A->getOption().matches(OPT_O0))
  229. opts.OptLevel = 0;
  230. if (A->getOption().matches(OPT_O1))
  231. opts.OptLevel = 1;
  232. if (A->getOption().matches(OPT_O2))
  233. opts.OptLevel = 2;
  234. if (A->getOption().matches(OPT_O3))
  235. opts.OptLevel = 3;
  236. }
  237. else
  238. opts.OptLevel = 3;
  239. opts.OptDump = Args.hasFlag(OPT_Odump, OPT_INVALID, false);
  240. opts.DisableOptimizations = Args.hasFlag(OPT_Od, OPT_INVALID, false);
  241. opts.DisableValidation = Args.hasFlag(OPT_VD, OPT_INVALID, false);
  242. opts.AllResourcesBound = Args.hasFlag(OPT_all_resources_bound, OPT_INVALID, false);
  243. opts.ColorCodeAssembly = Args.hasFlag(OPT_Cc, OPT_INVALID, false);
  244. opts.DefaultRowMajor = Args.hasFlag(OPT_Zpr, OPT_INVALID, false);
  245. opts.DefaultColMajor = Args.hasFlag(OPT_Zpc, OPT_INVALID, false);
  246. opts.DumpBin = Args.hasFlag(OPT_dumpbin, OPT_INVALID, false);
  247. opts.EnableUnboundedDescriptorTables = Args.hasFlag(OPT_enable_unbounded_descriptor_tables, OPT_INVALID, false);
  248. opts.NotUseLegacyCBufLoad = Args.hasFlag(OPT_not_use_legacy_cbuf_load, OPT_INVALID, false);
  249. opts.DisplayIncludeProcess = Args.hasFlag(OPT_H, OPT_INVALID, false);
  250. opts.WarningAsError = Args.hasFlag(OPT__SLASH_WX, OPT_INVALID, false);
  251. opts.AvoidFlowControl = Args.hasFlag(OPT_Gfa, OPT_INVALID, false);
  252. opts.PreferFlowControl = Args.hasFlag(OPT_Gfp, OPT_INVALID, false);
  253. opts.RecompileFromBinary = Args.hasFlag(OPT_recompile, OPT_INVALID, false);
  254. if (opts.DefaultColMajor && opts.DefaultRowMajor) {
  255. errors << "Cannot specify /Zpr and /Zpc together, use /? to get usage information";
  256. return 1;
  257. }
  258. if (opts.AvoidFlowControl && opts.PreferFlowControl) {
  259. errors << "Cannot specify /Gfa and /Gfp together, use /? to get usage information";
  260. return 1;
  261. }
  262. // TODO: more fxc option check.
  263. // ERR_RES_MAY_ALIAS_ONLY_IN_CS_5
  264. // ERR_NOT_ABLE_TO_FLATTEN on if that contain side effects
  265. // TODO: other front-end error.
  266. // ERR_RESOURCE_NOT_IN_TEMPLATE
  267. // ERR_COMPLEX_TEMPLATE_RESOURCE
  268. // ERR_RESOURCE_BIND_CONFLICT
  269. // ERR_TEMPLATE_VAR_CONFLICT
  270. // ERR_ATTRIBUTE_PARAM_SIDE_EFFECT
  271. if ((flagsToInclude & hlsl::options::DriverOption) && opts.InputFile.empty()) {
  272. // Input file is required in arguments only for drivers; APIs take this through an argument.
  273. errors << "Required input file argument is missing.";
  274. return 1;
  275. }
  276. if (opts.OutputHeader.empty() && !opts.VariableName.empty()) {
  277. errors << "Cannot specify a header variable name when not writing a header.";
  278. return 1;
  279. }
  280. if (!opts.Preprocess.empty() &&
  281. (!opts.OutputHeader.empty() || !opts.OutputObject.empty() ||
  282. opts.OutputWarnings || !opts.OutputWarningsFile.empty())) {
  283. errors << "Preprocess cannot be specified with other options.";
  284. return 1;
  285. }
  286. if (opts.DumpBin) {
  287. if (opts.DisplayIncludeProcess || opts.AstDump) {
  288. errors << "Cannot perform actions related to sources from a binary file.";
  289. return 1;
  290. }
  291. if (opts.AllResourcesBound || opts.AvoidFlowControl ||
  292. opts.CodeGenHighLevel || opts.DebugInfo || opts.DefaultColMajor ||
  293. opts.DefaultRowMajor || opts.Defines.size() != 0 ||
  294. opts.DisableOptimizations || opts.EnableUnboundedDescriptorTables ||
  295. !opts.EntryPoint.empty() || !opts.ForceRootSigVer.empty() ||
  296. opts.PreferFlowControl || !opts.TargetProfile.empty()) {
  297. errors << "Cannot specify compilation options when reading a binary file.";
  298. return 1;
  299. }
  300. }
  301. if ((flagsToInclude & hlsl::options::DriverOption) &&
  302. opts.TargetProfile.empty() && !opts.DumpBin && opts.Preprocess.empty() && !opts.RecompileFromBinary) {
  303. // Target profile is required in arguments only for drivers when compiling;
  304. // APIs take this through an argument.
  305. errors << "Target profile argument is missing";
  306. return 1;
  307. }
  308. opts.Args = std::move(Args);
  309. return 0;
  310. }
  311. /// Sets up the specified DxcDllSupport instance as per the given options.
  312. int SetupDxcDllSupport(const DxcOpts &opts, dxc::DxcDllSupport &dxcSupport,
  313. llvm::raw_ostream &errors) {
  314. if (!opts.ExternalLib.empty()) {
  315. DXASSERT(!opts.ExternalFn.empty(), "else ReadDxcOpts should have failed");
  316. StringRefUtf16 externalLib(opts.ExternalLib);
  317. HRESULT hrLoad =
  318. dxcSupport.InitializeForDll(externalLib, opts.ExternalFn.data());
  319. if (DXC_FAILED(hrLoad)) {
  320. errors << "Unable to load support for external DLL " << opts.ExternalLib
  321. << " with function " << opts.ExternalFn << " - error 0x";
  322. errors.write_hex(hrLoad);
  323. return 1;
  324. }
  325. }
  326. return 0;
  327. }
  328. void CopyArgsToWStrings(const InputArgList &inArgs, unsigned flagsToInclude,
  329. std::vector<std::wstring> &outArgs) {
  330. ArgStringList stringList;
  331. for (const Arg *A : inArgs) {
  332. if (A->getOption().hasFlag(flagsToInclude)) {
  333. A->renderAsInput(inArgs, stringList);
  334. }
  335. }
  336. for (const char *argText : stringList) {
  337. outArgs.emplace_back(Unicode::UTF8ToUTF16StringOrThrow(argText));
  338. }
  339. }
  340. } } // hlsl::options