2
0

CommandLine.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876
  1. //===-- CommandLine.cpp - Command line parser implementation --------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This class implements a command line argument processor that is useful when
  11. // creating a tool. It provides a simple, minimalistic interface that is easily
  12. // extensible and supports nonlocal (library) command line options.
  13. //
  14. // Note that rather than trying to figure out what this code does, you could try
  15. // reading the library documentation located in docs/CommandLine.html
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/Support/CommandLine.h"
  19. #include "llvm-c/Support.h"
  20. #include "llvm/ADT/ArrayRef.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallString.h"
  24. #include "llvm/ADT/StringMap.h"
  25. #include "llvm/ADT/Twine.h"
  26. #include "llvm/Config/config.h"
  27. #include "llvm/Support/ConvertUTF.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/ErrorHandling.h"
  30. #include "llvm/Support/Host.h"
  31. #include "llvm/Support/ManagedStatic.h"
  32. #include "llvm/Support/MemoryBuffer.h"
  33. #include "llvm/Support/Path.h"
  34. #include "llvm/Support/StringSaver.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include <cstdlib>
  37. #include <map>
  38. using namespace llvm;
  39. using namespace cl;
  40. #define DEBUG_TYPE "commandline"
  41. //===----------------------------------------------------------------------===//
  42. // Template instantiations and anchors.
  43. //
  44. namespace llvm {
  45. namespace cl {
  46. template class basic_parser<bool>;
  47. template class basic_parser<boolOrDefault>;
  48. template class basic_parser<int>;
  49. template class basic_parser<unsigned>;
  50. template class basic_parser<unsigned long long>;
  51. template class basic_parser<double>;
  52. template class basic_parser<float>;
  53. template class basic_parser<std::string>;
  54. template class basic_parser<char>;
  55. template class opt<unsigned>;
  56. template class opt<int>;
  57. template class opt<std::string>;
  58. template class opt<char>;
  59. template class opt<bool>;
  60. }
  61. } // end namespace llvm::cl
  62. // Pin the vtables to this file.
  63. void GenericOptionValue::anchor() {}
  64. void OptionValue<boolOrDefault>::anchor() {}
  65. void OptionValue<std::string>::anchor() {}
  66. void Option::anchor() {}
  67. void basic_parser_impl::anchor() {}
  68. void parser<bool>::anchor() {}
  69. void parser<boolOrDefault>::anchor() {}
  70. void parser<int>::anchor() {}
  71. void parser<unsigned>::anchor() {}
  72. void parser<unsigned long long>::anchor() {}
  73. void parser<double>::anchor() {}
  74. void parser<float>::anchor() {}
  75. void parser<std::string>::anchor() {}
  76. void parser<char>::anchor() {}
  77. //===----------------------------------------------------------------------===//
  78. namespace {
  79. class CommandLineParser {
  80. public:
  81. // Globals for name and overview of program. Program name is not a string to
  82. // avoid static ctor/dtor issues.
  83. std::string ProgramName;
  84. const char *ProgramOverview;
  85. // This collects additional help to be printed.
  86. std::vector<const char *> MoreHelp;
  87. SmallVector<Option *, 4> PositionalOpts;
  88. SmallVector<Option *, 4> SinkOpts;
  89. StringMap<Option *> OptionsMap;
  90. Option *ConsumeAfterOpt; // The ConsumeAfter option if it exists.
  91. // This collects the different option categories that have been registered.
  92. SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
  93. CommandLineParser() : ProgramOverview(nullptr), ConsumeAfterOpt(nullptr) {}
  94. void ParseCommandLineOptions(int argc, const char *const *argv,
  95. const char *Overview);
  96. void addLiteralOption(Option &Opt, const char *Name) {
  97. if (!Opt.hasArgStr()) {
  98. if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
  99. errs() << ProgramName << ": CommandLine Error: Option '" << Name
  100. << "' registered more than once!\n";
  101. report_fatal_error("inconsistency in registered CommandLine options");
  102. }
  103. }
  104. }
  105. void addOption(Option *O) {
  106. bool HadErrors = false;
  107. if (O->ArgStr[0]) {
  108. // Add argument to the argument map!
  109. if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
  110. errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
  111. << "' registered more than once!\n";
  112. HadErrors = true;
  113. }
  114. }
  115. // Remember information about positional options.
  116. if (O->getFormattingFlag() == cl::Positional)
  117. PositionalOpts.push_back(O);
  118. else if (O->getMiscFlags() & cl::Sink) // Remember sink options
  119. SinkOpts.push_back(O);
  120. else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
  121. if (ConsumeAfterOpt) {
  122. O->error("Cannot specify more than one option with cl::ConsumeAfter!");
  123. HadErrors = true;
  124. }
  125. ConsumeAfterOpt = O;
  126. }
  127. // Fail hard if there were errors. These are strictly unrecoverable and
  128. // indicate serious issues such as conflicting option names or an
  129. // incorrectly
  130. // linked LLVM distribution.
  131. if (HadErrors)
  132. report_fatal_error("inconsistency in registered CommandLine options");
  133. }
  134. void removeOption(Option *O) {
  135. SmallVector<const char *, 16> OptionNames;
  136. O->getExtraOptionNames(OptionNames);
  137. if (O->ArgStr[0])
  138. OptionNames.push_back(O->ArgStr);
  139. for (auto Name : OptionNames)
  140. OptionsMap.erase(StringRef(Name));
  141. if (O->getFormattingFlag() == cl::Positional)
  142. for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
  143. ++Opt) {
  144. if (*Opt == O) {
  145. PositionalOpts.erase(Opt);
  146. break;
  147. }
  148. }
  149. else if (O->getMiscFlags() & cl::Sink)
  150. for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
  151. if (*Opt == O) {
  152. SinkOpts.erase(Opt);
  153. break;
  154. }
  155. }
  156. else if (O == ConsumeAfterOpt)
  157. ConsumeAfterOpt = nullptr;
  158. }
  159. bool hasOptions() {
  160. return (!OptionsMap.empty() || !PositionalOpts.empty() ||
  161. nullptr != ConsumeAfterOpt);
  162. }
  163. void updateArgStr(Option *O, const char *NewName) {
  164. if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
  165. errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
  166. << "' registered more than once!\n";
  167. report_fatal_error("inconsistency in registered CommandLine options");
  168. }
  169. OptionsMap.erase(StringRef(O->ArgStr));
  170. }
  171. void printOptionValues();
  172. void registerCategory(OptionCategory *cat) {
  173. assert(std::count_if(RegisteredOptionCategories.begin(),
  174. RegisteredOptionCategories.end(),
  175. [cat](const OptionCategory *Category) {
  176. return cat->getName() == Category->getName();
  177. }) == 0 &&
  178. "Duplicate option categories");
  179. RegisteredOptionCategories.insert(cat);
  180. }
  181. private:
  182. Option *LookupOption(StringRef &Arg, StringRef &Value);
  183. };
  184. } // namespace
  185. static ManagedStatic<CommandLineParser> GlobalParser;
  186. void cl::AddLiteralOption(Option &O, const char *Name) {
  187. GlobalParser->addLiteralOption(O, Name);
  188. }
  189. extrahelp::extrahelp(const char *Help) : morehelp(Help) {
  190. GlobalParser->MoreHelp.push_back(Help);
  191. }
  192. void Option::addArgument() {
  193. GlobalParser->addOption(this);
  194. FullyInitialized = true;
  195. }
  196. void Option::removeArgument() { GlobalParser->removeOption(this); }
  197. void Option::setArgStr(const char *S) {
  198. if (FullyInitialized)
  199. GlobalParser->updateArgStr(this, S);
  200. ArgStr = S;
  201. }
  202. // Initialise the general option category.
  203. OptionCategory *llvm::cl::GeneralCategory; // HLSL Change - GeneralCategory is now a pointer
  204. void OptionCategory::registerCategory() {
  205. GlobalParser->registerCategory(this);
  206. }
  207. //===----------------------------------------------------------------------===//
  208. // Basic, shared command line option processing machinery.
  209. //
  210. /// LookupOption - Lookup the option specified by the specified option on the
  211. /// command line. If there is a value specified (after an equal sign) return
  212. /// that as well. This assumes that leading dashes have already been stripped.
  213. Option *CommandLineParser::LookupOption(StringRef &Arg, StringRef &Value) {
  214. // Reject all dashes.
  215. if (Arg.empty())
  216. return nullptr;
  217. size_t EqualPos = Arg.find('=');
  218. // If we have an equals sign, remember the value.
  219. if (EqualPos == StringRef::npos) {
  220. // Look up the option.
  221. StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
  222. return I != OptionsMap.end() ? I->second : nullptr;
  223. }
  224. // If the argument before the = is a valid option name, we match. If not,
  225. // return Arg unmolested.
  226. StringMap<Option *>::const_iterator I =
  227. OptionsMap.find(Arg.substr(0, EqualPos));
  228. if (I == OptionsMap.end())
  229. return nullptr;
  230. Value = Arg.substr(EqualPos + 1);
  231. Arg = Arg.substr(0, EqualPos);
  232. return I->second;
  233. }
  234. /// LookupNearestOption - Lookup the closest match to the option specified by
  235. /// the specified option on the command line. If there is a value specified
  236. /// (after an equal sign) return that as well. This assumes that leading dashes
  237. /// have already been stripped.
  238. static Option *LookupNearestOption(StringRef Arg,
  239. const StringMap<Option *> &OptionsMap,
  240. std::string &NearestString) {
  241. // Reject all dashes.
  242. if (Arg.empty())
  243. return nullptr;
  244. // Split on any equal sign.
  245. std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
  246. StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
  247. StringRef &RHS = SplitArg.second;
  248. // Find the closest match.
  249. Option *Best = nullptr;
  250. unsigned BestDistance = 0;
  251. for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
  252. ie = OptionsMap.end();
  253. it != ie; ++it) {
  254. Option *O = it->second;
  255. SmallVector<const char *, 16> OptionNames;
  256. O->getExtraOptionNames(OptionNames);
  257. if (O->ArgStr[0])
  258. OptionNames.push_back(O->ArgStr);
  259. bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
  260. StringRef Flag = PermitValue ? LHS : Arg;
  261. for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
  262. StringRef Name = OptionNames[i];
  263. unsigned Distance = StringRef(Name).edit_distance(
  264. Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
  265. if (!Best || Distance < BestDistance) {
  266. Best = O;
  267. BestDistance = Distance;
  268. if (RHS.empty() || !PermitValue)
  269. NearestString = OptionNames[i];
  270. else
  271. NearestString = (Twine(OptionNames[i]) + "=" + RHS).str();
  272. }
  273. }
  274. }
  275. return Best;
  276. }
  277. /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
  278. /// that does special handling of cl::CommaSeparated options.
  279. static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
  280. StringRef ArgName, StringRef Value,
  281. bool MultiArg = false) {
  282. // Check to see if this option accepts a comma separated list of values. If
  283. // it does, we have to split up the value into multiple values.
  284. if (Handler->getMiscFlags() & CommaSeparated) {
  285. StringRef Val(Value);
  286. StringRef::size_type Pos = Val.find(',');
  287. while (Pos != StringRef::npos) {
  288. // Process the portion before the comma.
  289. if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
  290. return true;
  291. // Erase the portion before the comma, AND the comma.
  292. Val = Val.substr(Pos + 1);
  293. Value.substr(Pos + 1); // Increment the original value pointer as well.
  294. // Check for another comma.
  295. Pos = Val.find(',');
  296. }
  297. Value = Val;
  298. }
  299. if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
  300. return true;
  301. return false;
  302. }
  303. /// ProvideOption - For Value, this differentiates between an empty value ("")
  304. /// and a null value (StringRef()). The later is accepted for arguments that
  305. /// don't allow a value (-foo) the former is rejected (-foo=).
  306. static inline bool ProvideOption(Option *Handler, StringRef ArgName,
  307. StringRef Value, int argc,
  308. const char *const *argv, int &i) {
  309. // Is this a multi-argument option?
  310. unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
  311. // Enforce value requirements
  312. switch (Handler->getValueExpectedFlag()) {
  313. case ValueRequired:
  314. if (!Value.data()) { // No value specified?
  315. if (i + 1 >= argc)
  316. return Handler->error("requires a value!");
  317. // Steal the next argument, like for '-o filename'
  318. assert(argv && "null check");
  319. Value = argv[++i];
  320. }
  321. break;
  322. case ValueDisallowed:
  323. if (NumAdditionalVals > 0)
  324. return Handler->error("multi-valued option specified"
  325. " with ValueDisallowed modifier!");
  326. if (Value.data())
  327. return Handler->error("does not allow a value! '" + Twine(Value) +
  328. "' specified.");
  329. break;
  330. case ValueOptional:
  331. break;
  332. }
  333. // If this isn't a multi-arg option, just run the handler.
  334. if (NumAdditionalVals == 0)
  335. return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
  336. // If it is, run the handle several times.
  337. bool MultiArg = false;
  338. if (Value.data()) {
  339. if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
  340. return true;
  341. --NumAdditionalVals;
  342. MultiArg = true;
  343. }
  344. while (NumAdditionalVals > 0) {
  345. if (i + 1 >= argc)
  346. return Handler->error("not enough values!");
  347. assert(argv && "null check");
  348. Value = argv[++i];
  349. if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
  350. return true;
  351. MultiArg = true;
  352. --NumAdditionalVals;
  353. }
  354. return false;
  355. }
  356. static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
  357. int Dummy = i;
  358. return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
  359. }
  360. // Option predicates...
  361. static inline bool isGrouping(const Option *O) {
  362. return O->getFormattingFlag() == cl::Grouping;
  363. }
  364. static inline bool isPrefixedOrGrouping(const Option *O) {
  365. return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
  366. }
  367. // getOptionPred - Check to see if there are any options that satisfy the
  368. // specified predicate with names that are the prefixes in Name. This is
  369. // checked by progressively stripping characters off of the name, checking to
  370. // see if there options that satisfy the predicate. If we find one, return it,
  371. // otherwise return null.
  372. //
  373. static Option *getOptionPred(StringRef Name, size_t &Length,
  374. bool (*Pred)(const Option *),
  375. const StringMap<Option *> &OptionsMap) {
  376. StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
  377. // Loop while we haven't found an option and Name still has at least two
  378. // characters in it (so that the next iteration will not be the empty
  379. // string.
  380. while (OMI == OptionsMap.end() && Name.size() > 1) {
  381. Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
  382. OMI = OptionsMap.find(Name);
  383. }
  384. if (OMI != OptionsMap.end() && Pred(OMI->second)) {
  385. Length = Name.size();
  386. return OMI->second; // Found one!
  387. }
  388. return nullptr; // No option found!
  389. }
  390. /// HandlePrefixedOrGroupedOption - The specified argument string (which started
  391. /// with at least one '-') does not fully match an available option. Check to
  392. /// see if this is a prefix or grouped option. If so, split arg into output an
  393. /// Arg/Value pair and return the Option to parse it with.
  394. static Option *
  395. HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
  396. bool &ErrorParsing,
  397. const StringMap<Option *> &OptionsMap) {
  398. if (Arg.size() == 1)
  399. return nullptr;
  400. // Do the lookup!
  401. size_t Length = 0;
  402. Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
  403. if (!PGOpt)
  404. return nullptr;
  405. // If the option is a prefixed option, then the value is simply the
  406. // rest of the name... so fall through to later processing, by
  407. // setting up the argument name flags and value fields.
  408. if (PGOpt->getFormattingFlag() == cl::Prefix) {
  409. Value = Arg.substr(Length);
  410. Arg = Arg.substr(0, Length);
  411. assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
  412. return PGOpt;
  413. }
  414. // This must be a grouped option... handle them now. Grouping options can't
  415. // have values.
  416. assert(isGrouping(PGOpt) && "Broken getOptionPred!");
  417. do {
  418. // Move current arg name out of Arg into OneArgName.
  419. StringRef OneArgName = Arg.substr(0, Length);
  420. Arg = Arg.substr(Length);
  421. // Because ValueRequired is an invalid flag for grouped arguments,
  422. // we don't need to pass argc/argv in.
  423. assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
  424. "Option can not be cl::Grouping AND cl::ValueRequired!");
  425. int Dummy = 0;
  426. ErrorParsing |=
  427. ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
  428. // Get the next grouping option.
  429. PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
  430. } while (PGOpt && Length != Arg.size());
  431. // Return the last option with Arg cut down to just the last one.
  432. return PGOpt;
  433. }
  434. static bool RequiresValue(const Option *O) {
  435. return O->getNumOccurrencesFlag() == cl::Required ||
  436. O->getNumOccurrencesFlag() == cl::OneOrMore;
  437. }
  438. static bool EatsUnboundedNumberOfValues(const Option *O) {
  439. return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
  440. O->getNumOccurrencesFlag() == cl::OneOrMore;
  441. }
  442. static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
  443. static bool isQuote(char C) { return C == '\"' || C == '\''; }
  444. static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
  445. void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
  446. SmallVectorImpl<const char *> &NewArgv,
  447. bool MarkEOLs) {
  448. SmallString<128> Token;
  449. for (size_t I = 0, E = Src.size(); I != E; ++I) {
  450. // Consume runs of whitespace.
  451. if (Token.empty()) {
  452. while (I != E && isWhitespace(Src[I])) {
  453. // Mark the end of lines in response files
  454. if (MarkEOLs && Src[I] == '\n')
  455. NewArgv.push_back(nullptr);
  456. ++I;
  457. }
  458. if (I == E)
  459. break;
  460. }
  461. // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
  462. // they are literal. This makes it much easier to read Windows file paths.
  463. if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
  464. ++I; // Skip the escape.
  465. Token.push_back(Src[I]);
  466. continue;
  467. }
  468. // Consume a quoted string.
  469. if (isQuote(Src[I])) {
  470. char Quote = Src[I++];
  471. while (I != E && Src[I] != Quote) {
  472. // Backslashes are literal, unless they escape a special character.
  473. if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
  474. ++I;
  475. Token.push_back(Src[I]);
  476. ++I;
  477. }
  478. if (I == E)
  479. break;
  480. continue;
  481. }
  482. // End the token if this is whitespace.
  483. if (isWhitespace(Src[I])) {
  484. if (!Token.empty())
  485. NewArgv.push_back(Saver.save(Token.c_str()));
  486. Token.clear();
  487. continue;
  488. }
  489. // This is a normal character. Append it.
  490. Token.push_back(Src[I]);
  491. }
  492. // Append the last token after hitting EOF with no whitespace.
  493. if (!Token.empty())
  494. NewArgv.push_back(Saver.save(Token.c_str()));
  495. // Mark the end of response files
  496. if (MarkEOLs)
  497. NewArgv.push_back(nullptr);
  498. }
  499. /// Backslashes are interpreted in a rather complicated way in the Windows-style
  500. /// command line, because backslashes are used both to separate path and to
  501. /// escape double quote. This method consumes runs of backslashes as well as the
  502. /// following double quote if it's escaped.
  503. ///
  504. /// * If an even number of backslashes is followed by a double quote, one
  505. /// backslash is output for every pair of backslashes, and the last double
  506. /// quote remains unconsumed. The double quote will later be interpreted as
  507. /// the start or end of a quoted string in the main loop outside of this
  508. /// function.
  509. ///
  510. /// * If an odd number of backslashes is followed by a double quote, one
  511. /// backslash is output for every pair of backslashes, and a double quote is
  512. /// output for the last pair of backslash-double quote. The double quote is
  513. /// consumed in this case.
  514. ///
  515. /// * Otherwise, backslashes are interpreted literally.
  516. static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
  517. size_t E = Src.size();
  518. int BackslashCount = 0;
  519. // Skip the backslashes.
  520. do {
  521. ++I;
  522. ++BackslashCount;
  523. } while (I != E && Src[I] == '\\');
  524. bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
  525. if (FollowedByDoubleQuote) {
  526. Token.append(BackslashCount / 2, '\\');
  527. if (BackslashCount % 2 == 0)
  528. return I - 1;
  529. Token.push_back('"');
  530. return I;
  531. }
  532. Token.append(BackslashCount, '\\');
  533. return I - 1;
  534. }
  535. void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
  536. SmallVectorImpl<const char *> &NewArgv,
  537. bool MarkEOLs) {
  538. SmallString<128> Token;
  539. // This is a small state machine to consume characters until it reaches the
  540. // end of the source string.
  541. enum { INIT, UNQUOTED, QUOTED } State = INIT;
  542. for (size_t I = 0, E = Src.size(); I != E; ++I) {
  543. // INIT state indicates that the current input index is at the start of
  544. // the string or between tokens.
  545. if (State == INIT) {
  546. if (isWhitespace(Src[I])) {
  547. // Mark the end of lines in response files
  548. if (MarkEOLs && Src[I] == '\n')
  549. NewArgv.push_back(nullptr);
  550. continue;
  551. }
  552. if (Src[I] == '"') {
  553. State = QUOTED;
  554. continue;
  555. }
  556. if (Src[I] == '\\') {
  557. I = parseBackslash(Src, I, Token);
  558. State = UNQUOTED;
  559. continue;
  560. }
  561. Token.push_back(Src[I]);
  562. State = UNQUOTED;
  563. continue;
  564. }
  565. // UNQUOTED state means that it's reading a token not quoted by double
  566. // quotes.
  567. if (State == UNQUOTED) {
  568. // Whitespace means the end of the token.
  569. if (isWhitespace(Src[I])) {
  570. NewArgv.push_back(Saver.save(Token.c_str()));
  571. Token.clear();
  572. State = INIT;
  573. // Mark the end of lines in response files
  574. if (MarkEOLs && Src[I] == '\n')
  575. NewArgv.push_back(nullptr);
  576. continue;
  577. }
  578. if (Src[I] == '"') {
  579. State = QUOTED;
  580. continue;
  581. }
  582. if (Src[I] == '\\') {
  583. I = parseBackslash(Src, I, Token);
  584. continue;
  585. }
  586. Token.push_back(Src[I]);
  587. continue;
  588. }
  589. // QUOTED state means that it's reading a token quoted by double quotes.
  590. if (State == QUOTED) {
  591. if (Src[I] == '"') {
  592. State = UNQUOTED;
  593. continue;
  594. }
  595. if (Src[I] == '\\') {
  596. I = parseBackslash(Src, I, Token);
  597. continue;
  598. }
  599. Token.push_back(Src[I]);
  600. }
  601. }
  602. // Append the last token after hitting EOF with no whitespace.
  603. if (!Token.empty())
  604. NewArgv.push_back(Saver.save(Token.c_str()));
  605. // Mark the end of response files
  606. if (MarkEOLs)
  607. NewArgv.push_back(nullptr);
  608. }
  609. // It is called byte order marker but the UTF-8 BOM is actually not affected
  610. // by the host system's endianness.
  611. static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
  612. return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
  613. }
  614. static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
  615. TokenizerCallback Tokenizer,
  616. SmallVectorImpl<const char *> &NewArgv,
  617. bool MarkEOLs = false) {
  618. ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
  619. MemoryBuffer::getFile(FName);
  620. if (!MemBufOrErr)
  621. return false;
  622. MemoryBuffer &MemBuf = *MemBufOrErr.get();
  623. StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
  624. // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
  625. ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
  626. std::string UTF8Buf;
  627. if (hasUTF16ByteOrderMark(BufRef)) {
  628. if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
  629. return false;
  630. Str = StringRef(UTF8Buf);
  631. }
  632. // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
  633. // these bytes before parsing.
  634. // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
  635. else if (hasUTF8ByteOrderMark(BufRef))
  636. Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
  637. // Tokenize the contents into NewArgv.
  638. Tokenizer(Str, Saver, NewArgv, MarkEOLs);
  639. return true;
  640. }
  641. /// \brief Expand response files on a command line recursively using the given
  642. /// StringSaver and tokenization strategy.
  643. bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
  644. SmallVectorImpl<const char *> &Argv,
  645. bool MarkEOLs) {
  646. unsigned RspFiles = 0;
  647. bool AllExpanded = true;
  648. // Don't cache Argv.size() because it can change.
  649. for (unsigned I = 0; I != Argv.size();) {
  650. const char *Arg = Argv[I];
  651. // Check if it is an EOL marker
  652. if (Arg == nullptr) {
  653. ++I;
  654. continue;
  655. }
  656. if (Arg[0] != '@') {
  657. ++I;
  658. continue;
  659. }
  660. // If we have too many response files, leave some unexpanded. This avoids
  661. // crashing on self-referential response files.
  662. if (RspFiles++ > 20)
  663. return false;
  664. // Replace this response file argument with the tokenization of its
  665. // contents. Nested response files are expanded in subsequent iterations.
  666. // FIXME: If a nested response file uses a relative path, is it relative to
  667. // the cwd of the process or the response file?
  668. SmallVector<const char *, 0> ExpandedArgv;
  669. if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
  670. MarkEOLs)) {
  671. // We couldn't read this file, so we leave it in the argument stream and
  672. // move on.
  673. AllExpanded = false;
  674. ++I;
  675. continue;
  676. }
  677. Argv.erase(Argv.begin() + I);
  678. Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
  679. }
  680. return AllExpanded;
  681. }
  682. /// ParseEnvironmentOptions - An alternative entry point to the
  683. /// CommandLine library, which allows you to read the program's name
  684. /// from the caller (as PROGNAME) and its command-line arguments from
  685. /// an environment variable (whose name is given in ENVVAR).
  686. ///
  687. void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
  688. const char *Overview) {
  689. // Check args.
  690. assert(progName && "Program name not specified");
  691. assert(envVar && "Environment variable name missing");
  692. // Get the environment variable they want us to parse options out of.
  693. const char *envValue = getenv(envVar);
  694. if (!envValue)
  695. return;
  696. // Get program's "name", which we wouldn't know without the caller
  697. // telling us.
  698. SmallVector<const char *, 20> newArgv;
  699. BumpPtrAllocator A;
  700. BumpPtrStringSaver Saver(A);
  701. newArgv.push_back(Saver.save(progName));
  702. // Parse the value of the environment variable into a "command line"
  703. // and hand it off to ParseCommandLineOptions().
  704. TokenizeGNUCommandLine(envValue, Saver, newArgv);
  705. int newArgc = static_cast<int>(newArgv.size());
  706. ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
  707. }
  708. void cl::ParseCommandLineOptions(int argc, const char *const *argv,
  709. const char *Overview) {
  710. GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
  711. }
  712. void CommandLineParser::ParseCommandLineOptions(int argc,
  713. const char *const *argv,
  714. const char *Overview) {
  715. // assert(hasOptions() && "No options specified!"); // HLSL Change - it's valid to have no options for the DLL build
  716. // Expand response files.
  717. SmallVector<const char *, 20> newArgv(argv, argv + argc);
  718. BumpPtrAllocator A;
  719. BumpPtrStringSaver Saver(A);
  720. ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
  721. argv = &newArgv[0];
  722. argc = static_cast<int>(newArgv.size());
  723. // Copy the program name into ProgName, making sure not to overflow it.
  724. ProgramName = sys::path::filename(argv[0]);
  725. ProgramOverview = Overview;
  726. bool ErrorParsing = false;
  727. // Check out the positional arguments to collect information about them.
  728. unsigned NumPositionalRequired = 0;
  729. // Determine whether or not there are an unlimited number of positionals
  730. bool HasUnlimitedPositionals = false;
  731. if (ConsumeAfterOpt) {
  732. assert(PositionalOpts.size() > 0 &&
  733. "Cannot specify cl::ConsumeAfter without a positional argument!");
  734. }
  735. if (!PositionalOpts.empty()) {
  736. // Calculate how many positional values are _required_.
  737. bool UnboundedFound = false;
  738. for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
  739. Option *Opt = PositionalOpts[i];
  740. if (RequiresValue(Opt))
  741. ++NumPositionalRequired;
  742. else if (ConsumeAfterOpt) {
  743. // ConsumeAfter cannot be combined with "optional" positional options
  744. // unless there is only one positional argument...
  745. if (PositionalOpts.size() > 1)
  746. ErrorParsing |= Opt->error(
  747. "error - this positional option will never be matched, "
  748. "because it does not Require a value, and a "
  749. "cl::ConsumeAfter option is active!");
  750. } else if (UnboundedFound && !Opt->ArgStr[0]) {
  751. // This option does not "require" a value... Make sure this option is
  752. // not specified after an option that eats all extra arguments, or this
  753. // one will never get any!
  754. //
  755. ErrorParsing |= Opt->error("error - option can never match, because "
  756. "another positional argument will match an "
  757. "unbounded number of values, and this option"
  758. " does not require a value!");
  759. errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
  760. << "' is all messed up!\n";
  761. errs() << PositionalOpts.size();
  762. }
  763. UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
  764. }
  765. HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
  766. }
  767. // PositionalVals - A vector of "positional" arguments we accumulate into
  768. // the process at the end.
  769. //
  770. SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
  771. // If the program has named positional arguments, and the name has been run
  772. // across, keep track of which positional argument was named. Otherwise put
  773. // the positional args into the PositionalVals list...
  774. Option *ActivePositionalArg = nullptr;
  775. // Loop over all of the arguments... processing them.
  776. bool DashDashFound = false; // Have we read '--'?
  777. for (int i = 1; i < argc; ++i) {
  778. Option *Handler = nullptr;
  779. Option *NearestHandler = nullptr;
  780. std::string NearestHandlerString;
  781. StringRef Value;
  782. StringRef ArgName = "";
  783. // Check to see if this is a positional argument. This argument is
  784. // considered to be positional if it doesn't start with '-', if it is "-"
  785. // itself, or if we have seen "--" already.
  786. //
  787. if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
  788. // Positional argument!
  789. if (ActivePositionalArg) {
  790. ProvidePositionalOption(ActivePositionalArg, argv[i], i);
  791. continue; // We are done!
  792. }
  793. if (!PositionalOpts.empty()) {
  794. PositionalVals.push_back(std::make_pair(argv[i], i));
  795. // All of the positional arguments have been fulfulled, give the rest to
  796. // the consume after option... if it's specified...
  797. //
  798. if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
  799. for (++i; i < argc; ++i)
  800. PositionalVals.push_back(std::make_pair(argv[i], i));
  801. break; // Handle outside of the argument processing loop...
  802. }
  803. // Delay processing positional arguments until the end...
  804. continue;
  805. }
  806. } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
  807. !DashDashFound) {
  808. DashDashFound = true; // This is the mythical "--"?
  809. continue; // Don't try to process it as an argument itself.
  810. } else if (ActivePositionalArg &&
  811. (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
  812. // If there is a positional argument eating options, check to see if this
  813. // option is another positional argument. If so, treat it as an argument,
  814. // otherwise feed it to the eating positional.
  815. ArgName = argv[i] + 1;
  816. // Eat leading dashes.
  817. while (!ArgName.empty() && ArgName[0] == '-')
  818. ArgName = ArgName.substr(1);
  819. Handler = LookupOption(ArgName, Value);
  820. if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
  821. ProvidePositionalOption(ActivePositionalArg, argv[i], i);
  822. continue; // We are done!
  823. }
  824. } else { // We start with a '-', must be an argument.
  825. ArgName = argv[i] + 1;
  826. // Eat leading dashes.
  827. while (!ArgName.empty() && ArgName[0] == '-')
  828. ArgName = ArgName.substr(1);
  829. Handler = LookupOption(ArgName, Value);
  830. // Check to see if this "option" is really a prefixed or grouped argument.
  831. if (!Handler)
  832. Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
  833. OptionsMap);
  834. // Otherwise, look for the closest available option to report to the user
  835. // in the upcoming error.
  836. if (!Handler && SinkOpts.empty())
  837. NearestHandler =
  838. LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
  839. }
  840. if (!Handler) {
  841. if (SinkOpts.empty()) {
  842. errs() << ProgramName << ": Unknown command line argument '" << argv[i]
  843. << "'. Try: '" << argv[0] << " -help'\n";
  844. if (NearestHandler) {
  845. // If we know a near match, report it as well.
  846. errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
  847. << "'?\n";
  848. }
  849. ErrorParsing = true;
  850. } else {
  851. for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
  852. E = SinkOpts.end();
  853. I != E; ++I)
  854. (*I)->addOccurrence(i, "", argv[i]);
  855. }
  856. continue;
  857. }
  858. // If this is a named positional argument, just remember that it is the
  859. // active one...
  860. if (Handler->getFormattingFlag() == cl::Positional)
  861. ActivePositionalArg = Handler;
  862. else
  863. ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
  864. }
  865. // Check and handle positional arguments now...
  866. if (NumPositionalRequired > PositionalVals.size()) {
  867. errs() << ProgramName
  868. << ": Not enough positional command line arguments specified!\n"
  869. << "Must specify at least " << NumPositionalRequired
  870. << " positional arguments: See: " << argv[0] << " -help\n";
  871. ErrorParsing = true;
  872. } else if (!HasUnlimitedPositionals &&
  873. PositionalVals.size() > PositionalOpts.size()) {
  874. errs() << ProgramName << ": Too many positional arguments specified!\n"
  875. << "Can specify at most " << PositionalOpts.size()
  876. << " positional arguments: See: " << argv[0] << " -help\n";
  877. ErrorParsing = true;
  878. } else if (!ConsumeAfterOpt) {
  879. // Positional args have already been handled if ConsumeAfter is specified.
  880. unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
  881. for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
  882. if (RequiresValue(PositionalOpts[i])) {
  883. ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
  884. PositionalVals[ValNo].second);
  885. ValNo++;
  886. --NumPositionalRequired; // We fulfilled our duty...
  887. }
  888. // If we _can_ give this option more arguments, do so now, as long as we
  889. // do not give it values that others need. 'Done' controls whether the
  890. // option even _WANTS_ any more.
  891. //
  892. bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
  893. while (NumVals - ValNo > NumPositionalRequired && !Done) {
  894. switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
  895. case cl::Optional:
  896. Done = true; // Optional arguments want _at most_ one value
  897. // FALL THROUGH
  898. case cl::ZeroOrMore: // Zero or more will take all they can get...
  899. case cl::OneOrMore: // One or more will take all they can get...
  900. ProvidePositionalOption(PositionalOpts[i],
  901. PositionalVals[ValNo].first,
  902. PositionalVals[ValNo].second);
  903. ValNo++;
  904. break;
  905. default:
  906. llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
  907. "positional argument processing!");
  908. }
  909. }
  910. }
  911. } else {
  912. assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
  913. unsigned ValNo = 0;
  914. for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
  915. if (RequiresValue(PositionalOpts[j])) {
  916. ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
  917. PositionalVals[ValNo].first,
  918. PositionalVals[ValNo].second);
  919. ValNo++;
  920. }
  921. // Handle the case where there is just one positional option, and it's
  922. // optional. In this case, we want to give JUST THE FIRST option to the
  923. // positional option and keep the rest for the consume after. The above
  924. // loop would have assigned no values to positional options in this case.
  925. //
  926. if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
  927. ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
  928. PositionalVals[ValNo].first,
  929. PositionalVals[ValNo].second);
  930. ValNo++;
  931. }
  932. // Handle over all of the rest of the arguments to the
  933. // cl::ConsumeAfter command line option...
  934. for (; ValNo != PositionalVals.size(); ++ValNo)
  935. ErrorParsing |=
  936. ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
  937. PositionalVals[ValNo].second);
  938. }
  939. // Loop over args and make sure all required args are specified!
  940. for (const auto &Opt : OptionsMap) {
  941. switch (Opt.second->getNumOccurrencesFlag()) {
  942. case Required:
  943. case OneOrMore:
  944. if (Opt.second->getNumOccurrences() == 0) {
  945. Opt.second->error("must be specified at least once!");
  946. ErrorParsing = true;
  947. }
  948. // Fall through
  949. default:
  950. break;
  951. }
  952. }
  953. // Now that we know if -debug is specified, we can use it.
  954. // Note that if ReadResponseFiles == true, this must be done before the
  955. // memory allocated for the expanded command line is free()d below.
  956. DEBUG(dbgs() << "Args: ";
  957. for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
  958. dbgs() << '\n';);
  959. // Free all of the memory allocated to the map. Command line options may only
  960. // be processed once!
  961. MoreHelp.clear();
  962. // If we had an error processing our arguments, don't let the program execute
  963. if (ErrorParsing)
  964. exit(1);
  965. }
  966. //===----------------------------------------------------------------------===//
  967. // Option Base class implementation
  968. //
  969. bool Option::error(const Twine &Message, StringRef ArgName) {
  970. if (!ArgName.data())
  971. ArgName = ArgStr;
  972. if (ArgName.empty())
  973. errs() << HelpStr; // Be nice for positional arguments
  974. else
  975. errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
  976. errs() << " option: " << Message << "\n";
  977. return true;
  978. }
  979. bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
  980. bool MultiArg) {
  981. if (!MultiArg)
  982. NumOccurrences++; // Increment the number of times we have been seen
  983. switch (getNumOccurrencesFlag()) {
  984. case Optional:
  985. if (NumOccurrences > 1)
  986. return error("may only occur zero or one times!", ArgName);
  987. break;
  988. case Required:
  989. if (NumOccurrences > 1)
  990. return error("must occur exactly one time!", ArgName);
  991. // Fall through
  992. case OneOrMore:
  993. case ZeroOrMore:
  994. case ConsumeAfter:
  995. break;
  996. }
  997. return handleOccurrence(pos, ArgName, Value);
  998. }
  999. // getValueStr - Get the value description string, using "DefaultMsg" if nothing
  1000. // has been specified yet.
  1001. //
  1002. static const char *getValueStr(const Option &O, const char *DefaultMsg) {
  1003. if (O.ValueStr[0] == 0)
  1004. return DefaultMsg;
  1005. return O.ValueStr;
  1006. }
  1007. //===----------------------------------------------------------------------===//
  1008. // cl::alias class implementation
  1009. //
  1010. // Return the width of the option tag for printing...
  1011. size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; }
  1012. static void printHelpStr(StringRef HelpStr, size_t Indent,
  1013. size_t FirstLineIndentedBy) {
  1014. std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
  1015. outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
  1016. while (!Split.second.empty()) {
  1017. Split = Split.second.split('\n');
  1018. outs().indent(Indent) << Split.first << "\n";
  1019. }
  1020. }
  1021. // Print out the option for the alias.
  1022. void alias::printOptionInfo(size_t GlobalWidth) const {
  1023. outs() << " -" << ArgStr;
  1024. printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
  1025. }
  1026. //===----------------------------------------------------------------------===//
  1027. // Parser Implementation code...
  1028. //
  1029. // basic_parser implementation
  1030. //
  1031. // Return the width of the option tag for printing...
  1032. size_t basic_parser_impl::getOptionWidth(const Option &O) const {
  1033. size_t Len = std::strlen(O.ArgStr);
  1034. if (const char *ValName = getValueName())
  1035. Len += std::strlen(getValueStr(O, ValName)) + 3;
  1036. return Len + 6;
  1037. }
  1038. // printOptionInfo - Print out information about this option. The
  1039. // to-be-maintained width is specified.
  1040. //
  1041. void basic_parser_impl::printOptionInfo(const Option &O,
  1042. size_t GlobalWidth) const {
  1043. outs() << " -" << O.ArgStr;
  1044. if (const char *ValName = getValueName())
  1045. outs() << "=<" << getValueStr(O, ValName) << '>';
  1046. printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
  1047. }
  1048. void basic_parser_impl::printOptionName(const Option &O,
  1049. size_t GlobalWidth) const {
  1050. outs() << " -" << O.ArgStr;
  1051. outs().indent(GlobalWidth - std::strlen(O.ArgStr));
  1052. }
  1053. // parser<bool> implementation
  1054. //
  1055. bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1056. bool &Value) {
  1057. if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
  1058. Arg == "1") {
  1059. Value = true;
  1060. return false;
  1061. }
  1062. if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
  1063. Value = false;
  1064. return false;
  1065. }
  1066. return O.error("'" + Arg +
  1067. "' is invalid value for boolean argument! Try 0 or 1");
  1068. }
  1069. // parser<boolOrDefault> implementation
  1070. //
  1071. bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1072. boolOrDefault &Value) {
  1073. if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
  1074. Arg == "1") {
  1075. Value = BOU_TRUE;
  1076. return false;
  1077. }
  1078. if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
  1079. Value = BOU_FALSE;
  1080. return false;
  1081. }
  1082. return O.error("'" + Arg +
  1083. "' is invalid value for boolean argument! Try 0 or 1");
  1084. }
  1085. // parser<int> implementation
  1086. //
  1087. bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1088. int &Value) {
  1089. if (Arg.getAsInteger(0, Value))
  1090. return O.error("'" + Arg + "' value invalid for integer argument!");
  1091. return false;
  1092. }
  1093. // parser<unsigned> implementation
  1094. //
  1095. bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1096. unsigned &Value) {
  1097. if (Arg.getAsInteger(0, Value))
  1098. return O.error("'" + Arg + "' value invalid for uint argument!");
  1099. return false;
  1100. }
  1101. // parser<unsigned long long> implementation
  1102. //
  1103. bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
  1104. StringRef Arg,
  1105. unsigned long long &Value) {
  1106. if (Arg.getAsInteger(0, Value))
  1107. return O.error("'" + Arg + "' value invalid for uint argument!");
  1108. return false;
  1109. }
  1110. // parser<double>/parser<float> implementation
  1111. //
  1112. static bool parseDouble(Option &O, StringRef Arg, double &Value) {
  1113. SmallString<32> TmpStr(Arg.begin(), Arg.end());
  1114. const char *ArgStart = TmpStr.c_str();
  1115. char *End;
  1116. Value = strtod(ArgStart, &End);
  1117. if (*End != 0)
  1118. return O.error("'" + Arg + "' value invalid for floating point argument!");
  1119. return false;
  1120. }
  1121. bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1122. double &Val) {
  1123. return parseDouble(O, Arg, Val);
  1124. }
  1125. bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1126. float &Val) {
  1127. double dVal;
  1128. if (parseDouble(O, Arg, dVal))
  1129. return true;
  1130. Val = (float)dVal;
  1131. return false;
  1132. }
  1133. // generic_parser_base implementation
  1134. //
  1135. // findOption - Return the option number corresponding to the specified
  1136. // argument string. If the option is not found, getNumOptions() is returned.
  1137. //
  1138. unsigned generic_parser_base::findOption(const char *Name) {
  1139. unsigned e = getNumOptions();
  1140. for (unsigned i = 0; i != e; ++i) {
  1141. if (strcmp(getOption(i), Name) == 0)
  1142. return i;
  1143. }
  1144. return e;
  1145. }
  1146. // Return the width of the option tag for printing...
  1147. size_t generic_parser_base::getOptionWidth(const Option &O) const {
  1148. if (O.hasArgStr()) {
  1149. size_t Size = std::strlen(O.ArgStr) + 6;
  1150. for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
  1151. Size = std::max(Size, std::strlen(getOption(i)) + 8);
  1152. return Size;
  1153. } else {
  1154. size_t BaseSize = 0;
  1155. for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
  1156. BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
  1157. return BaseSize;
  1158. }
  1159. }
  1160. // printOptionInfo - Print out information about this option. The
  1161. // to-be-maintained width is specified.
  1162. //
  1163. void generic_parser_base::printOptionInfo(const Option &O,
  1164. size_t GlobalWidth) const {
  1165. if (O.hasArgStr()) {
  1166. outs() << " -" << O.ArgStr;
  1167. printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
  1168. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  1169. size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
  1170. outs() << " =" << getOption(i);
  1171. outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
  1172. }
  1173. } else {
  1174. if (O.HelpStr[0])
  1175. outs() << " " << O.HelpStr << '\n';
  1176. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  1177. const char *Option = getOption(i);
  1178. outs() << " -" << Option;
  1179. printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
  1180. }
  1181. }
  1182. }
  1183. static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
  1184. // printGenericOptionDiff - Print the value of this option and it's default.
  1185. //
  1186. // "Generic" options have each value mapped to a name.
  1187. void generic_parser_base::printGenericOptionDiff(
  1188. const Option &O, const GenericOptionValue &Value,
  1189. const GenericOptionValue &Default, size_t GlobalWidth) const {
  1190. outs() << " -" << O.ArgStr;
  1191. outs().indent(GlobalWidth - std::strlen(O.ArgStr));
  1192. unsigned NumOpts = getNumOptions();
  1193. for (unsigned i = 0; i != NumOpts; ++i) {
  1194. if (Value.compare(getOptionValue(i)))
  1195. continue;
  1196. outs() << "= " << getOption(i);
  1197. size_t L = std::strlen(getOption(i));
  1198. size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
  1199. outs().indent(NumSpaces) << " (default: ";
  1200. for (unsigned j = 0; j != NumOpts; ++j) {
  1201. if (Default.compare(getOptionValue(j)))
  1202. continue;
  1203. outs() << getOption(j);
  1204. break;
  1205. }
  1206. outs() << ")\n";
  1207. return;
  1208. }
  1209. outs() << "= *unknown option value*\n";
  1210. }
  1211. // printOptionDiff - Specializations for printing basic value types.
  1212. //
  1213. #define PRINT_OPT_DIFF(T) \
  1214. void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
  1215. size_t GlobalWidth) const { \
  1216. printOptionName(O, GlobalWidth); \
  1217. std::string Str; \
  1218. { \
  1219. raw_string_ostream SS(Str); \
  1220. SS << V; \
  1221. } \
  1222. outs() << "= " << Str; \
  1223. size_t NumSpaces = \
  1224. MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
  1225. outs().indent(NumSpaces) << " (default: "; \
  1226. if (D.hasValue()) \
  1227. outs() << D.getValue(); \
  1228. else \
  1229. outs() << "*no default*"; \
  1230. outs() << ")\n"; \
  1231. }
  1232. PRINT_OPT_DIFF(bool)
  1233. PRINT_OPT_DIFF(boolOrDefault)
  1234. PRINT_OPT_DIFF(int)
  1235. PRINT_OPT_DIFF(unsigned)
  1236. PRINT_OPT_DIFF(unsigned long long)
  1237. PRINT_OPT_DIFF(double)
  1238. PRINT_OPT_DIFF(float)
  1239. PRINT_OPT_DIFF(char)
  1240. void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
  1241. OptionValue<std::string> D,
  1242. size_t GlobalWidth) const {
  1243. printOptionName(O, GlobalWidth);
  1244. outs() << "= " << V;
  1245. size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
  1246. outs().indent(NumSpaces) << " (default: ";
  1247. if (D.hasValue())
  1248. outs() << D.getValue();
  1249. else
  1250. outs() << "*no default*";
  1251. outs() << ")\n";
  1252. }
  1253. // Print a placeholder for options that don't yet support printOptionDiff().
  1254. void basic_parser_impl::printOptionNoValue(const Option &O,
  1255. size_t GlobalWidth) const {
  1256. printOptionName(O, GlobalWidth);
  1257. outs() << "= *cannot print option value*\n";
  1258. }
  1259. //===----------------------------------------------------------------------===//
  1260. // -help and -help-hidden option implementation
  1261. //
  1262. // HLSL Change - __cdecl
  1263. static int __cdecl OptNameCompare(const std::pair<const char *, Option *> *LHS,
  1264. const std::pair<const char *, Option *> *RHS) {
  1265. return strcmp(LHS->first, RHS->first);
  1266. }
  1267. // Copy Options into a vector so we can sort them as we like.
  1268. static void sortOpts(StringMap<Option *> &OptMap,
  1269. SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
  1270. bool ShowHidden) {
  1271. SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
  1272. for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
  1273. I != E; ++I) {
  1274. // Ignore really-hidden options.
  1275. if (I->second->getOptionHiddenFlag() == ReallyHidden)
  1276. continue;
  1277. // Unless showhidden is set, ignore hidden flags.
  1278. if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
  1279. continue;
  1280. // If we've already seen this option, don't add it to the list again.
  1281. if (!OptionSet.insert(I->second).second)
  1282. continue;
  1283. Opts.push_back(
  1284. std::pair<const char *, Option *>(I->getKey().data(), I->second));
  1285. }
  1286. // Sort the options list alphabetically.
  1287. array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
  1288. }
  1289. namespace {
  1290. class HelpPrinter {
  1291. protected:
  1292. const bool ShowHidden;
  1293. typedef SmallVector<std::pair<const char *, Option *>, 128>
  1294. StrOptionPairVector;
  1295. // Print the options. Opts is assumed to be alphabetically sorted.
  1296. virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
  1297. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  1298. Opts[i].second->printOptionInfo(MaxArgLen);
  1299. }
  1300. public:
  1301. explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
  1302. virtual ~HelpPrinter() {}
  1303. // Invoke the printer.
  1304. void operator=(bool Value) {
  1305. if (!Value)
  1306. return;
  1307. StrOptionPairVector Opts;
  1308. sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
  1309. if (GlobalParser->ProgramOverview)
  1310. outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
  1311. outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
  1312. for (auto Opt : GlobalParser->PositionalOpts) {
  1313. if (Opt->ArgStr[0])
  1314. outs() << " --" << Opt->ArgStr;
  1315. outs() << " " << Opt->HelpStr;
  1316. }
  1317. // Print the consume after option info if it exists...
  1318. if (GlobalParser->ConsumeAfterOpt)
  1319. outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
  1320. outs() << "\n\n";
  1321. // Compute the maximum argument length...
  1322. size_t MaxArgLen = 0;
  1323. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  1324. MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
  1325. outs() << "OPTIONS:\n";
  1326. printOptions(Opts, MaxArgLen);
  1327. // Print any extra help the user has declared.
  1328. for (auto I : GlobalParser->MoreHelp)
  1329. outs() << I;
  1330. GlobalParser->MoreHelp.clear();
  1331. // Halt the program since help information was printed
  1332. exit(0);
  1333. }
  1334. };
  1335. class CategorizedHelpPrinter : public HelpPrinter {
  1336. public:
  1337. explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
  1338. // Helper function for printOptions().
  1339. // It shall return a negative value if A's name should be lexicographically
  1340. // ordered before B's name. It returns a value greater equal zero otherwise.
  1341. static int __cdecl OptionCategoryCompare(OptionCategory *const *A,
  1342. OptionCategory *const *B) {
  1343. return strcmp((*A)->getName(), (*B)->getName());
  1344. }
  1345. // Make sure we inherit our base class's operator=()
  1346. using HelpPrinter::operator=;
  1347. protected:
  1348. void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
  1349. std::vector<OptionCategory *> SortedCategories;
  1350. std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
  1351. // Collect registered option categories into vector in preparation for
  1352. // sorting.
  1353. for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
  1354. E = GlobalParser->RegisteredOptionCategories.end();
  1355. I != E; ++I) {
  1356. SortedCategories.push_back(*I);
  1357. }
  1358. // Sort the different option categories alphabetically.
  1359. assert(SortedCategories.size() > 0 && "No option categories registered!");
  1360. array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
  1361. OptionCategoryCompare);
  1362. // Create map to empty vectors.
  1363. for (std::vector<OptionCategory *>::const_iterator
  1364. I = SortedCategories.begin(),
  1365. E = SortedCategories.end();
  1366. I != E; ++I)
  1367. CategorizedOptions[*I] = std::vector<Option *>();
  1368. // Walk through pre-sorted options and assign into categories.
  1369. // Because the options are already alphabetically sorted the
  1370. // options within categories will also be alphabetically sorted.
  1371. for (size_t I = 0, E = Opts.size(); I != E; ++I) {
  1372. Option *Opt = Opts[I].second;
  1373. assert(CategorizedOptions.count(Opt->Category) > 0 &&
  1374. "Option has an unregistered category");
  1375. CategorizedOptions[Opt->Category].push_back(Opt);
  1376. }
  1377. // Now do printing.
  1378. for (std::vector<OptionCategory *>::const_iterator
  1379. Category = SortedCategories.begin(),
  1380. E = SortedCategories.end();
  1381. Category != E; ++Category) {
  1382. // Hide empty categories for -help, but show for -help-hidden.
  1383. bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
  1384. if (!ShowHidden && IsEmptyCategory)
  1385. continue;
  1386. // Print category information.
  1387. outs() << "\n";
  1388. outs() << (*Category)->getName() << ":\n";
  1389. // Check if description is set.
  1390. if ((*Category)->getDescription() != nullptr)
  1391. outs() << (*Category)->getDescription() << "\n\n";
  1392. else
  1393. outs() << "\n";
  1394. // When using -help-hidden explicitly state if the category has no
  1395. // options associated with it.
  1396. if (IsEmptyCategory) {
  1397. outs() << " This option category has no options.\n";
  1398. continue;
  1399. }
  1400. // Loop over the options in the category and print.
  1401. for (std::vector<Option *>::const_iterator
  1402. Opt = CategorizedOptions[*Category].begin(),
  1403. E = CategorizedOptions[*Category].end();
  1404. Opt != E; ++Opt)
  1405. (*Opt)->printOptionInfo(MaxArgLen);
  1406. }
  1407. }
  1408. };
  1409. // This wraps the Uncategorizing and Categorizing printers and decides
  1410. // at run time which should be invoked.
  1411. class HelpPrinterWrapper {
  1412. private:
  1413. #if 0 // HLSL Change Starts
  1414. HelpPrinter &UncategorizedPrinter;
  1415. CategorizedHelpPrinter &CategorizedPrinter;
  1416. #endif // HLSL Change Ends
  1417. public:
  1418. explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
  1419. CategorizedHelpPrinter &CategorizedPrinter)
  1420. #if 0 // HLSL Change Starts
  1421. : UncategorizedPrinter(UncategorizedPrinter),
  1422. CategorizedPrinter(CategorizedPrinter)
  1423. #endif // HLSL Change Starts
  1424. {}
  1425. // Invoke the printer.
  1426. void operator=(bool Value);
  1427. };
  1428. } // End anonymous namespace
  1429. // Declare the four HelpPrinter instances that are used to print out help, or
  1430. // help-hidden as an uncategorized list or in categories.
  1431. static HelpPrinter UncategorizedNormalPrinter(false);
  1432. static HelpPrinter UncategorizedHiddenPrinter(true);
  1433. static CategorizedHelpPrinter CategorizedNormalPrinter(false);
  1434. static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
  1435. // Declare HelpPrinter wrappers that will decide whether or not to invoke
  1436. // a categorizing help printer
  1437. static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
  1438. CategorizedNormalPrinter);
  1439. static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
  1440. CategorizedHiddenPrinter);
  1441. #if 0 // HLSL Change Starts
  1442. // Define a category for generic options that all tools should have.
  1443. static cl::OptionCategory GenericCategory("Generic Options");
  1444. // Define uncategorized help printers.
  1445. // -help-list is hidden by default because if Option categories are being used
  1446. // then -help behaves the same as -help-list.
  1447. static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
  1448. "help-list",
  1449. cl::desc("Display list of available options (-help-list-hidden for more)"),
  1450. cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
  1451. cl::cat(GenericCategory));
  1452. static cl::opt<HelpPrinter, true, parser<bool>>
  1453. HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
  1454. cl::location(UncategorizedHiddenPrinter), cl::Hidden,
  1455. cl::ValueDisallowed, cl::cat(GenericCategory));
  1456. // Define uncategorized/categorized help printers. These printers change their
  1457. // behaviour at runtime depending on whether one or more Option categories have
  1458. // been declared.
  1459. static cl::opt<HelpPrinterWrapper, true, parser<bool>>
  1460. HOp("help", cl::desc("Display available options (-help-hidden for more)"),
  1461. cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
  1462. cl::cat(GenericCategory));
  1463. static cl::opt<HelpPrinterWrapper, true, parser<bool>>
  1464. HHOp("help-hidden", cl::desc("Display all available options"),
  1465. cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
  1466. cl::cat(GenericCategory));
  1467. static cl::opt<bool> PrintOptions(
  1468. "print-options",
  1469. cl::desc("Print non-default options after command line parsing"),
  1470. cl::Hidden, cl::init(false), cl::cat(GenericCategory));
  1471. static cl::opt<bool> PrintAllOptions(
  1472. "print-all-options",
  1473. cl::desc("Print all option values after command line parsing"), cl::Hidden,
  1474. cl::init(false), cl::cat(GenericCategory));
  1475. void HelpPrinterWrapper::operator=(bool Value) {
  1476. if (!Value)
  1477. return;
  1478. // Decide which printer to invoke. If more than one option category is
  1479. // registered then it is useful to show the categorized help instead of
  1480. // uncategorized help.
  1481. if (GlobalParser->RegisteredOptionCategories.size() > 1) {
  1482. // unhide -help-list option so user can have uncategorized output if they
  1483. // want it.
  1484. HLOp.setHiddenFlag(NotHidden);
  1485. CategorizedPrinter = true; // Invoke categorized printer
  1486. } else
  1487. UncategorizedPrinter = true; // Invoke uncategorized printer
  1488. }
  1489. #else
  1490. static const bool PrintOptions = false;
  1491. static const bool PrintAllOptions = false;
  1492. #endif // HLSL Change Ends
  1493. // Print the value of each option.
  1494. void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
  1495. void CommandLineParser::printOptionValues() {
  1496. if (!PrintOptions && !PrintAllOptions)
  1497. return;
  1498. SmallVector<std::pair<const char *, Option *>, 128> Opts;
  1499. sortOpts(OptionsMap, Opts, /*ShowHidden*/ true);
  1500. // Compute the maximum argument length...
  1501. size_t MaxArgLen = 0;
  1502. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  1503. MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
  1504. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  1505. Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
  1506. }
  1507. static void (*OverrideVersionPrinter)() = nullptr;
  1508. static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
  1509. namespace {
  1510. class VersionPrinter {
  1511. public:
  1512. void print() {
  1513. raw_ostream &OS = outs();
  1514. OS << "LLVM (http://llvm.org/):\n"
  1515. << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
  1516. #ifdef LLVM_VERSION_INFO
  1517. OS << " " << LLVM_VERSION_INFO;
  1518. #endif
  1519. OS << "\n ";
  1520. #ifndef __OPTIMIZE__
  1521. OS << "DEBUG build";
  1522. #else
  1523. OS << "Optimized build";
  1524. #endif
  1525. #ifndef NDEBUG
  1526. OS << " with assertions";
  1527. #endif
  1528. std::string CPU = sys::getHostCPUName();
  1529. if (CPU == "generic")
  1530. CPU = "(unknown)";
  1531. OS << ".\n"
  1532. #if (ENABLE_TIMESTAMPS == 1)
  1533. // HLSL Change - remove any possibility that __DATE__ or __TIME__ are used (build cache)
  1534. // << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
  1535. #endif
  1536. << " Default target: " << sys::getDefaultTargetTriple() << '\n'
  1537. << " Host CPU: " << CPU << '\n';
  1538. }
  1539. void operator=(bool OptionWasSpecified) {
  1540. if (!OptionWasSpecified)
  1541. return;
  1542. if (OverrideVersionPrinter != nullptr) {
  1543. (*OverrideVersionPrinter)();
  1544. exit(0);
  1545. }
  1546. print();
  1547. // Iterate over any registered extra printers and call them to add further
  1548. // information.
  1549. if (ExtraVersionPrinters != nullptr) {
  1550. outs() << '\n';
  1551. for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
  1552. E = ExtraVersionPrinters->end();
  1553. I != E; ++I)
  1554. (*I)();
  1555. }
  1556. exit(0);
  1557. }
  1558. };
  1559. } // End anonymous namespace
  1560. // Define the --version option that prints out the LLVM version for the tool
  1561. static VersionPrinter VersionPrinterInstance;
  1562. #if 0 // HLSL Change Starts
  1563. static cl::opt<VersionPrinter, true, parser<bool>>
  1564. VersOp("version", cl::desc("Display the version of this program"),
  1565. cl::location(VersionPrinterInstance), cl::ValueDisallowed,
  1566. cl::cat(GenericCategory));
  1567. #else
  1568. static const OptionCategory *GenericCategory;
  1569. #endif // HLSL Change Ends
  1570. // Utility function for printing the help message.
  1571. void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
  1572. // This looks weird, but it actually prints the help message. The Printers are
  1573. // types of HelpPrinter and the help gets printed when its operator= is
  1574. // invoked. That's because the "normal" usages of the help printer is to be
  1575. // assigned true/false depending on whether -help or -help-hidden was given or
  1576. // not. Since we're circumventing that we have to make it look like -help or
  1577. // -help-hidden were given, so we assign true.
  1578. if (!Hidden && !Categorized)
  1579. UncategorizedNormalPrinter = true;
  1580. else if (!Hidden && Categorized)
  1581. CategorizedNormalPrinter = true;
  1582. else if (Hidden && !Categorized)
  1583. UncategorizedHiddenPrinter = true;
  1584. else
  1585. CategorizedHiddenPrinter = true;
  1586. }
  1587. /// Utility function for printing version number.
  1588. void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
  1589. void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
  1590. void cl::AddExtraVersionPrinter(void (*func)()) {
  1591. if (!ExtraVersionPrinters)
  1592. ExtraVersionPrinters = new std::vector<void (*)()>;
  1593. ExtraVersionPrinters->push_back(func);
  1594. }
  1595. StringMap<Option *> &cl::getRegisteredOptions() {
  1596. return GlobalParser->OptionsMap;
  1597. }
  1598. void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
  1599. for (auto &I : GlobalParser->OptionsMap) {
  1600. if (I.second->Category != &Category &&
  1601. I.second->Category != GenericCategory) // HLSL Change - use pointer
  1602. I.second->setHiddenFlag(cl::ReallyHidden);
  1603. }
  1604. }
  1605. void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
  1606. auto CategoriesBegin = Categories.begin();
  1607. auto CategoriesEnd = Categories.end();
  1608. for (auto &I : GlobalParser->OptionsMap) {
  1609. if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
  1610. CategoriesEnd &&
  1611. I.second->Category != GenericCategory) // HLSL Change - use pointer
  1612. I.second->setHiddenFlag(cl::ReallyHidden);
  1613. }
  1614. }
  1615. void LLVMParseCommandLineOptions(int argc, const char *const *argv,
  1616. const char *Overview) {
  1617. llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
  1618. }